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
54f23ac10f1c29a482e591211734ff51e60d3402
11,622,181,561,005
305ea1c88b93714cd33b38d0ad387bd6ab050906
/src/main/java/com/js/dao/material/MaterialSplitRecordMapper.java
32d80df599e3f383c7a05e1cfb4a09fc8c001817
[]
no_license
xpxupengxp/jsJXC
https://github.com/xpxupengxp/jsJXC
0a37c88311b1a3334af64569e04b579b10e745ba
a9ad021e2018350d1cd924c342a6acc181192301
refs/heads/master
2020-04-27T15:57:26.449000
2019-03-15T05:50:05
2019-03-15T05:50:05
174,466,689
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.js.dao.material; import com.js.entity.material.MaterialSplitRecord; public interface MaterialSplitRecordMapper { int deleteByPrimaryKey(Long id); int insert(MaterialSplitRecord record); int insertSelective(MaterialSplitRecord record); MaterialSplitRecord selectByPrimaryKey(Long id); int updateByPrimaryKeySelective(MaterialSplitRecord record); int updateByPrimaryKey(MaterialSplitRecord record); }
UTF-8
Java
441
java
MaterialSplitRecordMapper.java
Java
[]
null
[]
package com.js.dao.material; import com.js.entity.material.MaterialSplitRecord; public interface MaterialSplitRecordMapper { int deleteByPrimaryKey(Long id); int insert(MaterialSplitRecord record); int insertSelective(MaterialSplitRecord record); MaterialSplitRecord selectByPrimaryKey(Long id); int updateByPrimaryKeySelective(MaterialSplitRecord record); int updateByPrimaryKey(MaterialSplitRecord record); }
441
0.804989
0.804989
17
25
24.578804
64
false
false
0
0
0
0
0
0
0.470588
false
false
14
3d56532b6b717f0bb8b6ad75237d9539ae5e089f
16,947,940,995,097
bf0ff2e498ff8211c3228e48955999ddd622bfe6
/src/project3/task2/KNearestNeighbour.java
7c03266cf1570155926df3d8f9edd49796a38770
[]
no_license
tandberg/IT3105
https://github.com/tandberg/IT3105
a6a8c8be91127fcaf4036007319b2b4afefe0d65
5c3f084a734929102244defe59ec4d0684554017
refs/heads/master
2021-01-02T22:51:33.069000
2017-01-12T11:11:56
2017-01-12T11:11:56
12,374,668
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package project3.task2; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class KNearestNeighbour { public static List<Particle> algorithm(List<Particle> all, Particle current, int k) { double[] currentPosition = current.getPositions(); List<Particle> result = new ArrayList<Particle>(); List<ParticleDistance> neighbourDistances = new ArrayList<ParticleDistance>(); for (Particle particle : all) { double distance = euclidianDistance(currentPosition, particle.getPositions()); neighbourDistances.add(new ParticleDistance(particle, distance)); } Collections.sort(neighbourDistances); for (int i = 0; i < k; i++) { result.add(neighbourDistances.get(i).getParticle()); } return result; } public static double euclidianDistance(double[] a, double[] b) { double aSum = 0; double bSum = 0; for (int i = 0; i < a.length; i++) { aSum += Math.pow(a[i], 2); bSum += Math.pow(b[i], 2); } return Math.abs(Math.sqrt(aSum) - Math.sqrt(bSum)); } }
UTF-8
Java
1,171
java
KNearestNeighbour.java
Java
[]
null
[]
package project3.task2; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class KNearestNeighbour { public static List<Particle> algorithm(List<Particle> all, Particle current, int k) { double[] currentPosition = current.getPositions(); List<Particle> result = new ArrayList<Particle>(); List<ParticleDistance> neighbourDistances = new ArrayList<ParticleDistance>(); for (Particle particle : all) { double distance = euclidianDistance(currentPosition, particle.getPositions()); neighbourDistances.add(new ParticleDistance(particle, distance)); } Collections.sort(neighbourDistances); for (int i = 0; i < k; i++) { result.add(neighbourDistances.get(i).getParticle()); } return result; } public static double euclidianDistance(double[] a, double[] b) { double aSum = 0; double bSum = 0; for (int i = 0; i < a.length; i++) { aSum += Math.pow(a[i], 2); bSum += Math.pow(b[i], 2); } return Math.abs(Math.sqrt(aSum) - Math.sqrt(bSum)); } }
1,171
0.614859
0.608027
40
28.275
28.094473
90
false
false
0
0
0
0
0
0
0.7
false
false
14
4a066dc9bcb369c8f93b9205ffa184d2dd47a3b2
2,791,728,786,171
3177df89fbf016b65cdc67171d5c35c7d588a280
/src/main/java/com/manojkk/learning/cardweb/dto/UserCardObject.java
651fbe0ec6dbfbff77873962a47f4e7ee644f28f
[]
no_license
mak0128/learningrepo
https://github.com/mak0128/learningrepo
dc4429f70e156e122d38bd8ae988ba69b7ed563b
1f2276b20f1281f3169202df05c1ed377a7d52b7
refs/heads/master
2021-01-11T13:38:31.061000
2017-06-21T21:18:58
2017-06-21T21:18:58
95,047,313
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.manojkk.learning.cardweb.dto; import java.util.List; public class UserCardObject { private String username; private List<Card> cards; /** * @return the username */ public String getUsername() { return username; } /** * @param username the username to set */ public void setUsername(String username) { this.username = username; } /** * @return the cards */ public List<Card> getCards() { return cards; } /** * @param cards the cards to set */ public void setCards(List<Card> cards) { this.cards = cards; } }
UTF-8
Java
563
java
UserCardObject.java
Java
[]
null
[]
package com.manojkk.learning.cardweb.dto; import java.util.List; public class UserCardObject { private String username; private List<Card> cards; /** * @return the username */ public String getUsername() { return username; } /** * @param username the username to set */ public void setUsername(String username) { this.username = username; } /** * @return the cards */ public List<Card> getCards() { return cards; } /** * @param cards the cards to set */ public void setCards(List<Card> cards) { this.cards = cards; } }
563
0.660746
0.660746
34
15.558824
14.30794
43
false
false
0
0
0
0
0
0
1.176471
false
false
14
ed35febcb7f15a53cb467c0250ecc2b367b1df49
30,666,066,539,501
e5e600abd7a233d46afb200225cf16097160e0af
/books/sk-mka-books-heroult/src/main/java/cz/heroult/pavel/java/book/Kap02/S28/Soubory2.java
f1b9d90d5c1cddcaf2caf15b7d6056b92754e5a4
[]
no_license
bracek/books
https://github.com/bracek/books
760de42aea42eb1e5e634610ef0c46f5a092fe80
c0a192ca7fd9432d7b024b93cff61e4d68d5e3df
refs/heads/master
2020-04-02T10:33:28.901000
2014-01-24T09:34:17
2014-01-24T09:34:17
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cz.heroult.pavel.java.book.Kap02.S28; ///////////////////////////////////////////////////////////////// // // // Tento zdrojov� k�d je sou��st� distribuce bal�ku program�, // // poskytovan�ch jako dopl�uj�c� informace ke knize // // // // U�ebnice jazyka Java // // // // P�e�t�te si, pros�m, d�kladn� upozorn�n� v souboru // // CTI_ME.TXT // // kter� je ned�lnou sou��st� t�to distribuce // // // // (c) Pavel Herout, 2000 // // // ///////////////////////////////////////////////////////////////// import java.io.*; import java.util.*; public class Soubory2 { public static void main(final String[] argv) throws IOException{ File soub = new File("b.txt"); File adr = new File("TMP"); System.out.println(new Date(soub.lastModified())); System.out.println(new Date(adr.lastModified())); System.out.println(soub.length()); System.out.println(adr.length()); File jiny = new File("c.txt"); soub.renameTo(jiny); adr.renameTo(new File("TMP-OLD")); soub.delete(); // nevyma�e c.txt adr.delete(); // nevyma�e TMP-OLD jiny.delete(); // skute�n� vymaz�n� c.txt } }
UTF-8
Java
1,658
java
Soubory2.java
Java
[ { "context": " //\n// (c) Pavel Herout, 2000 // \n// ", "end": 809, "score": 0.9998424053192139, "start": 797, "tag": "NAME", "value": "Pavel Herout" } ]
null
[]
package cz.heroult.pavel.java.book.Kap02.S28; ///////////////////////////////////////////////////////////////// // // // Tento zdrojov� k�d je sou��st� distribuce bal�ku program�, // // poskytovan�ch jako dopl�uj�c� informace ke knize // // // // U�ebnice jazyka Java // // // // P�e�t�te si, pros�m, d�kladn� upozorn�n� v souboru // // CTI_ME.TXT // // kter� je ned�lnou sou��st� t�to distribuce // // // // (c) <NAME>, 2000 // // // ///////////////////////////////////////////////////////////////// import java.io.*; import java.util.*; public class Soubory2 { public static void main(final String[] argv) throws IOException{ File soub = new File("b.txt"); File adr = new File("TMP"); System.out.println(new Date(soub.lastModified())); System.out.println(new Date(adr.lastModified())); System.out.println(soub.length()); System.out.println(adr.length()); File jiny = new File("c.txt"); soub.renameTo(jiny); adr.renameTo(new File("TMP-OLD")); soub.delete(); // nevyma�e c.txt adr.delete(); // nevyma�e TMP-OLD jiny.delete(); // skute�n� vymaz�n� c.txt } }
1,652
0.385194
0.379548
40
38.849998
25.344181
66
false
false
0
0
0
0
76
0.091593
0.475
false
false
14
fef121c27a76c0d2e5aff909d2636318d3b12d8f
22,866,405,925,338
eeaeddeab4775a1742dba5c8898686fd38caf669
/base/base-rocketmq/src/main/java/com/zsw/mq/spring/autoconfigure/RocketMQAutoConfiguration.java
5f1c79a5d434e76b7404205b33238ee16f01c683
[ "Apache-2.0" ]
permissive
MasterOogwayis/spring
https://github.com/MasterOogwayis/spring
8250dddd5d6ee9730c8aec4a7aeab1b80c3bf750
c9210e8d3533982faa3e7b89885fd4c54f27318e
refs/heads/master
2023-07-23T09:49:37.930000
2023-07-21T03:04:27
2023-07-21T03:04:27
89,329,352
0
0
Apache-2.0
false
2023-06-14T22:51:13
2017-04-25T07:13:03
2022-03-14T12:06:51
2023-06-14T22:51:12
13,631
1
0
6
Java
false
false
package com.zsw.mq.spring.autoconfigure; import com.aliyun.openservices.ons.api.PropertyKeyConst; import com.aliyun.openservices.ons.api.bean.ProducerBean; import com.aliyun.openservices.shade.com.alibaba.rocketmq.client.MQAdmin; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.zsw.mq.spring.adapter.Producer; import com.zsw.mq.spring.adapter.core.AliProducerAdapter; import com.zsw.mq.spring.adapter.core.DefaultProducerAdapter; import com.zsw.mq.spring.config.RocketMQConfigUtils; import com.zsw.mq.spring.core.RocketMQTemplate; import com.zsw.mq.spring.serializer.JacksonMessageSerializer; import com.zsw.mq.spring.serializer.MessageSerializer; import com.zsw.mq.spring.support.bean.AbstractMQListenerContainer; import com.zsw.mq.spring.support.bean.AliRocketMQListenerContainer; import com.zsw.mq.spring.support.bean.DefaultRocketMQListenerContainer; import lombok.extern.slf4j.Slf4j; import org.apache.rocketmq.acl.common.AclClientRPCHook; import org.apache.rocketmq.acl.common.SessionCredentials; import org.apache.rocketmq.client.AccessChannel; import org.apache.rocketmq.client.producer.DefaultMQProducer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.core.env.Environment; import org.springframework.core.env.StandardEnvironment; import org.springframework.util.Assert; import org.springframework.util.StringUtils; import javax.annotation.PostConstruct; import java.text.SimpleDateFormat; import java.util.Properties; import static com.zsw.mq.spring.config.RocketMQConfigUtils.PREFIX; /** * @author ZhangShaowei on 2019/9/12 11:19 **/ @Slf4j @Configuration @EnableConfigurationProperties(RocketMQProperties.class) @ConditionalOnProperty(prefix = "rocketmq", value = "name-server", matchIfMissing = true) @AutoConfigureAfter(JacksonAutoConfiguration.class) public class RocketMQAutoConfiguration { @Autowired private Environment environment; @PostConstruct public void checkProperties() { String nameServer = environment.getProperty("rocketmq.name-server", String.class); log.debug("rocketmq.nameServer = {}", nameServer); if (nameServer == null) { log.warn("The necessary spring property 'rocketmq.name-server' is not defined, all rockertmq beans creation are skipped!"); } } @Bean(destroyMethod = "destroy") @ConditionalOnBean(Producer.class) @ConditionalOnMissingBean(name = RocketMQConfigUtils.ROCKETMQ_TEMPLATE_DEFAULT_GLOBAL_NAME) public RocketMQTemplate rocketMQTemplate(Producer producer, ObjectMapper objectMapper) { RocketMQTemplate rocketMQTemplate = new RocketMQTemplate(); rocketMQTemplate.setProducer(producer); rocketMQTemplate.setObjectMapper(objectMapper); return rocketMQTemplate; } @Bean @ConditionalOnMissingBean(MessageSerializer.class) public MessageSerializer messageSerializer(ObjectMapper objectMapper) { return new JacksonMessageSerializer(objectMapper); } @Bean @ConditionalOnMissingBean(ObjectMapper.class) public ObjectMapper objectMapper() { ObjectMapper mapper = new ObjectMapper(); //忽略没有的属性 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); //允许没有双引号 mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); //允许转义字符 mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true); //允许单引号 mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); return mapper; } // @Profile(PROFILE_DEFAULT) @ConditionalOnClass(org.apache.rocketmq.client.MQAdmin.class) @ConditionalOnProperty(prefix = "rocketmq", value = {"name-server", "producer.group"}) @Import({DefaultListenerContainerConfiguration.class}) public class DefaultConfiguration { @Bean(initMethod = "start", destroyMethod = "stop") public Producer defaultMQProducer( RocketMQProperties rocketMQProperties, MessageSerializer serializer) { RocketMQProperties.Producer producerConfig = rocketMQProperties.getProducer(); String nameServer = rocketMQProperties.getNameServer(); String groupName = producerConfig.getGroup(); Assert.hasText(nameServer, "[rocketmq.name-server] must not be null"); Assert.hasText(groupName, "[rocketmq.producer.group] must not be null"); String accessChannel = rocketMQProperties.getAccessChannel(); DefaultMQProducer producer; String ak = rocketMQProperties.getProducer().getAccessKey(); String sk = rocketMQProperties.getProducer().getSecretKey(); if (!StringUtils.isEmpty(ak) && !StringUtils.isEmpty(sk)) { producer = new DefaultMQProducer(groupName, new AclClientRPCHook(new SessionCredentials(ak, sk)), rocketMQProperties.getProducer().isEnableMsgTrace(), rocketMQProperties.getProducer().getCustomizedTraceTopic()); producer.setVipChannelEnabled(false); } else { producer = new DefaultMQProducer(groupName, rocketMQProperties.getProducer().isEnableMsgTrace(), rocketMQProperties.getProducer().getCustomizedTraceTopic()); } producer.setNamesrvAddr(nameServer); if (!StringUtils.isEmpty(accessChannel)) { producer.setAccessChannel(AccessChannel.valueOf(accessChannel)); } producer.setSendMsgTimeout(producerConfig.getSendMessageTimeout()); producer.setRetryTimesWhenSendFailed(producerConfig.getRetryTimesWhenSendFailed()); producer.setRetryTimesWhenSendAsyncFailed(producerConfig.getRetryTimesWhenSendAsyncFailed()); producer.setMaxMessageSize(producerConfig.getMaxMessageSize()); producer.setCompressMsgBodyOverHowmuch(producerConfig.getCompressMessageBodyThreshold()); producer.setRetryAnotherBrokerWhenNotStoreOK(producerConfig.isRetryNextServer()); return new DefaultProducerAdapter(producer, serializer); } } // @Profile(PROFILE_ALIYUN) @ConditionalOnClass(MQAdmin.class) @ConditionalOnProperty(prefix = "rocketmq", value = {"name-server", "producer.group"}) @Import({AliyunListenerContainerConfiguration.class}) public class AliyunConfiguration { @Autowired private MessageSerializer serializer; @Bean(initMethod = "start", destroyMethod = "stop") public Producer defaultMQProducer(RocketMQProperties rocketMQProperties) { RocketMQProperties.Producer producerConfig = rocketMQProperties.getProducer(); String nameServer = rocketMQProperties.getNameServer(); String groupName = producerConfig.getGroup(); Assert.hasText(nameServer, "[rocketmq.name-server] must not be null"); Assert.hasText(groupName, "[rocketmq.producer.group] must not be null"); String ak = rocketMQProperties.getProducer().getAccessKey(); String sk = rocketMQProperties.getProducer().getSecretKey(); Properties properties = new Properties(); // properties.setProperty(PropertyKeyConst.GROUP_ID, groupName); properties.setProperty(PropertyKeyConst.AccessKey, ak); properties.setProperty(PropertyKeyConst.SecretKey, sk); properties.setProperty(PropertyKeyConst.NAMESRV_ADDR, nameServer); String appName = RocketMQAutoConfiguration.this.environment.resolvePlaceholders("${spring.application.name}"); properties.setProperty(PropertyKeyConst.InstanceName, appName + PREFIX + "defaultMQProducer"); properties.setProperty(PropertyKeyConst.SendMsgTimeoutMillis, String.valueOf(producerConfig.getSendMessageTimeout())); ProducerBean producerBean = new ProducerBean(); producerBean.setProperties(properties); return new AliProducerAdapter(producerBean, serializer); } } /** * Consumer Proxy */ class AliyunListenerContainerConfiguration extends AbstractListenerContainerConfiguration { public AliyunListenerContainerConfiguration(MessageSerializer serializer, StandardEnvironment environment, RocketMQProperties rocketMQProperties) { super(serializer, environment, rocketMQProperties); } @Override Class<? extends AbstractMQListenerContainer> getContainerClazz() { return AliRocketMQListenerContainer.class; } } class DefaultListenerContainerConfiguration extends AbstractListenerContainerConfiguration { public DefaultListenerContainerConfiguration( MessageSerializer serializer, StandardEnvironment environment, RocketMQProperties rocketMQProperties) { super(serializer, environment, rocketMQProperties); } @Override Class<? extends AbstractMQListenerContainer> getContainerClazz() { return DefaultRocketMQListenerContainer.class; } } }
UTF-8
Java
10,340
java
RocketMQAutoConfiguration.java
Java
[ { "context": "config.RocketMQConfigUtils.PREFIX;\n\n/**\n * @author ZhangShaowei on 2019/9/12 11:19\n **/\n@Slf4j\n@Configuration\n@En", "end": 2459, "score": 0.9998687505722046, "start": 2447, "tag": "NAME", "value": "ZhangShaowei" }, { "context": "properties.setProperty(PropertyKeyConst.SecretKey, sk);\n properties.setProperty(PropertyKeyC", "end": 8457, "score": 0.9902229309082031, "start": 8455, "tag": "KEY", "value": "sk" } ]
null
[]
package com.zsw.mq.spring.autoconfigure; import com.aliyun.openservices.ons.api.PropertyKeyConst; import com.aliyun.openservices.ons.api.bean.ProducerBean; import com.aliyun.openservices.shade.com.alibaba.rocketmq.client.MQAdmin; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.zsw.mq.spring.adapter.Producer; import com.zsw.mq.spring.adapter.core.AliProducerAdapter; import com.zsw.mq.spring.adapter.core.DefaultProducerAdapter; import com.zsw.mq.spring.config.RocketMQConfigUtils; import com.zsw.mq.spring.core.RocketMQTemplate; import com.zsw.mq.spring.serializer.JacksonMessageSerializer; import com.zsw.mq.spring.serializer.MessageSerializer; import com.zsw.mq.spring.support.bean.AbstractMQListenerContainer; import com.zsw.mq.spring.support.bean.AliRocketMQListenerContainer; import com.zsw.mq.spring.support.bean.DefaultRocketMQListenerContainer; import lombok.extern.slf4j.Slf4j; import org.apache.rocketmq.acl.common.AclClientRPCHook; import org.apache.rocketmq.acl.common.SessionCredentials; import org.apache.rocketmq.client.AccessChannel; import org.apache.rocketmq.client.producer.DefaultMQProducer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.core.env.Environment; import org.springframework.core.env.StandardEnvironment; import org.springframework.util.Assert; import org.springframework.util.StringUtils; import javax.annotation.PostConstruct; import java.text.SimpleDateFormat; import java.util.Properties; import static com.zsw.mq.spring.config.RocketMQConfigUtils.PREFIX; /** * @author ZhangShaowei on 2019/9/12 11:19 **/ @Slf4j @Configuration @EnableConfigurationProperties(RocketMQProperties.class) @ConditionalOnProperty(prefix = "rocketmq", value = "name-server", matchIfMissing = true) @AutoConfigureAfter(JacksonAutoConfiguration.class) public class RocketMQAutoConfiguration { @Autowired private Environment environment; @PostConstruct public void checkProperties() { String nameServer = environment.getProperty("rocketmq.name-server", String.class); log.debug("rocketmq.nameServer = {}", nameServer); if (nameServer == null) { log.warn("The necessary spring property 'rocketmq.name-server' is not defined, all rockertmq beans creation are skipped!"); } } @Bean(destroyMethod = "destroy") @ConditionalOnBean(Producer.class) @ConditionalOnMissingBean(name = RocketMQConfigUtils.ROCKETMQ_TEMPLATE_DEFAULT_GLOBAL_NAME) public RocketMQTemplate rocketMQTemplate(Producer producer, ObjectMapper objectMapper) { RocketMQTemplate rocketMQTemplate = new RocketMQTemplate(); rocketMQTemplate.setProducer(producer); rocketMQTemplate.setObjectMapper(objectMapper); return rocketMQTemplate; } @Bean @ConditionalOnMissingBean(MessageSerializer.class) public MessageSerializer messageSerializer(ObjectMapper objectMapper) { return new JacksonMessageSerializer(objectMapper); } @Bean @ConditionalOnMissingBean(ObjectMapper.class) public ObjectMapper objectMapper() { ObjectMapper mapper = new ObjectMapper(); //忽略没有的属性 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); //允许没有双引号 mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); //允许转义字符 mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true); //允许单引号 mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); return mapper; } // @Profile(PROFILE_DEFAULT) @ConditionalOnClass(org.apache.rocketmq.client.MQAdmin.class) @ConditionalOnProperty(prefix = "rocketmq", value = {"name-server", "producer.group"}) @Import({DefaultListenerContainerConfiguration.class}) public class DefaultConfiguration { @Bean(initMethod = "start", destroyMethod = "stop") public Producer defaultMQProducer( RocketMQProperties rocketMQProperties, MessageSerializer serializer) { RocketMQProperties.Producer producerConfig = rocketMQProperties.getProducer(); String nameServer = rocketMQProperties.getNameServer(); String groupName = producerConfig.getGroup(); Assert.hasText(nameServer, "[rocketmq.name-server] must not be null"); Assert.hasText(groupName, "[rocketmq.producer.group] must not be null"); String accessChannel = rocketMQProperties.getAccessChannel(); DefaultMQProducer producer; String ak = rocketMQProperties.getProducer().getAccessKey(); String sk = rocketMQProperties.getProducer().getSecretKey(); if (!StringUtils.isEmpty(ak) && !StringUtils.isEmpty(sk)) { producer = new DefaultMQProducer(groupName, new AclClientRPCHook(new SessionCredentials(ak, sk)), rocketMQProperties.getProducer().isEnableMsgTrace(), rocketMQProperties.getProducer().getCustomizedTraceTopic()); producer.setVipChannelEnabled(false); } else { producer = new DefaultMQProducer(groupName, rocketMQProperties.getProducer().isEnableMsgTrace(), rocketMQProperties.getProducer().getCustomizedTraceTopic()); } producer.setNamesrvAddr(nameServer); if (!StringUtils.isEmpty(accessChannel)) { producer.setAccessChannel(AccessChannel.valueOf(accessChannel)); } producer.setSendMsgTimeout(producerConfig.getSendMessageTimeout()); producer.setRetryTimesWhenSendFailed(producerConfig.getRetryTimesWhenSendFailed()); producer.setRetryTimesWhenSendAsyncFailed(producerConfig.getRetryTimesWhenSendAsyncFailed()); producer.setMaxMessageSize(producerConfig.getMaxMessageSize()); producer.setCompressMsgBodyOverHowmuch(producerConfig.getCompressMessageBodyThreshold()); producer.setRetryAnotherBrokerWhenNotStoreOK(producerConfig.isRetryNextServer()); return new DefaultProducerAdapter(producer, serializer); } } // @Profile(PROFILE_ALIYUN) @ConditionalOnClass(MQAdmin.class) @ConditionalOnProperty(prefix = "rocketmq", value = {"name-server", "producer.group"}) @Import({AliyunListenerContainerConfiguration.class}) public class AliyunConfiguration { @Autowired private MessageSerializer serializer; @Bean(initMethod = "start", destroyMethod = "stop") public Producer defaultMQProducer(RocketMQProperties rocketMQProperties) { RocketMQProperties.Producer producerConfig = rocketMQProperties.getProducer(); String nameServer = rocketMQProperties.getNameServer(); String groupName = producerConfig.getGroup(); Assert.hasText(nameServer, "[rocketmq.name-server] must not be null"); Assert.hasText(groupName, "[rocketmq.producer.group] must not be null"); String ak = rocketMQProperties.getProducer().getAccessKey(); String sk = rocketMQProperties.getProducer().getSecretKey(); Properties properties = new Properties(); // properties.setProperty(PropertyKeyConst.GROUP_ID, groupName); properties.setProperty(PropertyKeyConst.AccessKey, ak); properties.setProperty(PropertyKeyConst.SecretKey, sk); properties.setProperty(PropertyKeyConst.NAMESRV_ADDR, nameServer); String appName = RocketMQAutoConfiguration.this.environment.resolvePlaceholders("${spring.application.name}"); properties.setProperty(PropertyKeyConst.InstanceName, appName + PREFIX + "defaultMQProducer"); properties.setProperty(PropertyKeyConst.SendMsgTimeoutMillis, String.valueOf(producerConfig.getSendMessageTimeout())); ProducerBean producerBean = new ProducerBean(); producerBean.setProperties(properties); return new AliProducerAdapter(producerBean, serializer); } } /** * Consumer Proxy */ class AliyunListenerContainerConfiguration extends AbstractListenerContainerConfiguration { public AliyunListenerContainerConfiguration(MessageSerializer serializer, StandardEnvironment environment, RocketMQProperties rocketMQProperties) { super(serializer, environment, rocketMQProperties); } @Override Class<? extends AbstractMQListenerContainer> getContainerClazz() { return AliRocketMQListenerContainer.class; } } class DefaultListenerContainerConfiguration extends AbstractListenerContainerConfiguration { public DefaultListenerContainerConfiguration( MessageSerializer serializer, StandardEnvironment environment, RocketMQProperties rocketMQProperties) { super(serializer, environment, rocketMQProperties); } @Override Class<? extends AbstractMQListenerContainer> getContainerClazz() { return DefaultRocketMQListenerContainer.class; } } }
10,340
0.732653
0.731293
223
45.143497
33.238464
135
false
false
0
0
0
0
0
0
0.659193
false
false
14
392fe40d0889e2d81c7851e06540137842a67ba8
32,409,823,227,269
74a9a90ee7064a1da77e1831f12f0485df0ed5a8
/src/NowCoder/Nowcoder/Nowcoder/code26_BSTConvertDoubleLinkedList.java
ec4f0b33c3b634b22e27d87140e76f8df303af66
[]
no_license
Lemon-362/NowCoder
https://github.com/Lemon-362/NowCoder
4191e83bc8d8f6a973e46a7537c43fa453f7477a
979fa190c2a06a0e84159646df21d2f2193deff2
refs/heads/master
2022-12-04T10:48:09.092000
2020-08-17T09:19:46
2020-08-17T09:19:46
261,641,899
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package NowCoder.Nowcoder.Nowcoder; import java.util.ArrayList; /* 搜索二叉树转换成双向链表: 输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。 要求不能创建任何新的结点,只能调整树中结点指针的指向。 */ public class code26_BSTConvertDoubleLinkedList { public static class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } public static TreeNode Convert(TreeNode head) { if (head == null) { return null; } ArrayList<TreeNode> list = new ArrayList<>(); inOrder(head, list); return method(list); } public static void inOrder(TreeNode head, ArrayList<TreeNode> list) { if (head == null) { return; } inOrder(head.left, list); list.add(head); inOrder(head.right, list); } public static TreeNode method(ArrayList<TreeNode> list) { for (int i = 0; i < list.size() - 1; i++) { list.get(i).right = list.get(i + 1); list.get(i + 1).left = list.get(i); } return list.get(0); } public static void main(String[] args) { TreeNode head = new TreeNode(4); head.left = new TreeNode(2); head.right = new TreeNode(5); head.left.left = new TreeNode(1); head.left.right = new TreeNode(3); TreeNode newHead = Convert(head); print(newHead); } public static void print(TreeNode head){ if (head == null){ return; } TreeNode cur = null; while (head != null){ System.out.print(head.val + " "); cur = head; head = head.right; } System.out.println(); while (cur != null){ System.out.print(cur.val + " "); cur = cur.left; } System.out.println(); } }
UTF-8
Java
2,048
java
code26_BSTConvertDoubleLinkedList.java
Java
[]
null
[]
package NowCoder.Nowcoder.Nowcoder; import java.util.ArrayList; /* 搜索二叉树转换成双向链表: 输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。 要求不能创建任何新的结点,只能调整树中结点指针的指向。 */ public class code26_BSTConvertDoubleLinkedList { public static class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } public static TreeNode Convert(TreeNode head) { if (head == null) { return null; } ArrayList<TreeNode> list = new ArrayList<>(); inOrder(head, list); return method(list); } public static void inOrder(TreeNode head, ArrayList<TreeNode> list) { if (head == null) { return; } inOrder(head.left, list); list.add(head); inOrder(head.right, list); } public static TreeNode method(ArrayList<TreeNode> list) { for (int i = 0; i < list.size() - 1; i++) { list.get(i).right = list.get(i + 1); list.get(i + 1).left = list.get(i); } return list.get(0); } public static void main(String[] args) { TreeNode head = new TreeNode(4); head.left = new TreeNode(2); head.right = new TreeNode(5); head.left.left = new TreeNode(1); head.left.right = new TreeNode(3); TreeNode newHead = Convert(head); print(newHead); } public static void print(TreeNode head){ if (head == null){ return; } TreeNode cur = null; while (head != null){ System.out.print(head.val + " "); cur = head; head = head.right; } System.out.println(); while (cur != null){ System.out.print(cur.val + " "); cur = cur.left; } System.out.println(); } }
2,048
0.523585
0.516771
76
24.105263
17.414135
73
false
false
0
0
0
0
0
0
0.513158
false
false
14
d386b794f52f997e5f30c85266c830172fb1fd80
20,598,663,207,670
ee2ce8393cc47a6c9cd2dc0394c6e4dcf88e3e38
/src/main/java/com/bridgeLabz/service/ICSVBuilder.java
5c5b65345e8037994705b26f5dc3b82564e8d858
[]
no_license
vampire16/IndianStatesCensusAnalyzer
https://github.com/vampire16/IndianStatesCensusAnalyzer
f65823f85e42c110e40746357abd343249a6b7fa
a3c8006062879c109e1c4ca8903befc0c932d016
refs/heads/master
2021-03-25T13:43:10.418000
2020-04-10T16:51:59
2020-04-10T16:51:59
247,623,726
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bridgeLabz.service; import com.bridgeLabz.Exception.CSVBuilderException; import java.io.Reader; import java.util.Iterator; import java.util.List; public interface ICSVBuilder { <E> Iterator getIterator(Reader reader, Class csvClass) throws CSVBuilderException; <E> List getList(Reader reader, Class csvClass); }
UTF-8
Java
347
java
ICSVBuilder.java
Java
[]
null
[]
package com.bridgeLabz.service; import com.bridgeLabz.Exception.CSVBuilderException; import java.io.Reader; import java.util.Iterator; import java.util.List; public interface ICSVBuilder { <E> Iterator getIterator(Reader reader, Class csvClass) throws CSVBuilderException; <E> List getList(Reader reader, Class csvClass); }
347
0.763689
0.763689
12
26.916666
25.476978
87
false
false
0
0
0
0
0
0
0.75
false
false
14
2875acf31fca0bca40831ff54e1687ce19f33b62
13,632,226,245,942
9a57eee0d899b3c1e4d15d946b2f0bf3e67ef0e5
/hard-paradise/src/main/java/urjc/hardParadise/repositories/UsuarioRepository.java
b045e06eff5641e13ffad4387e343e07e7b3577c
[ "Apache-2.0" ]
permissive
eroosan/Hard-Paradise
https://github.com/eroosan/Hard-Paradise
8a0a8050374233e59518ea993e472f9abb516413
fc8b4c32dd12f3496c398866c64e90182f5429b3
refs/heads/master
2020-04-24T23:06:44.154000
2019-03-23T12:26:13
2019-03-23T12:26:13
172,332,778
0
0
null
true
2019-02-24T12:07:04
2019-02-24T12:07:03
2018-04-26T00:34:05
2018-04-26T00:34:04
13,626
0
0
0
null
false
null
package urjc.hardParadise.repositories; import java.util.List; import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.CacheEvict; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.CrudRepository; import urjc.hardParadise.Montaje; import urjc.hardParadise.Usuario; @CacheConfig(cacheNames = "test") public interface UsuarioRepository extends CrudRepository<Usuario, String> { List<Usuario> findBySeguidos(Usuario usuario); Usuario findByNombre(String nombre); @CacheEvict(allEntries = true) Usuario save(Usuario usuario); }
UTF-8
Java
639
java
UsuarioRepository.java
Java
[]
null
[]
package urjc.hardParadise.repositories; import java.util.List; import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.CacheEvict; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.CrudRepository; import urjc.hardParadise.Montaje; import urjc.hardParadise.Usuario; @CacheConfig(cacheNames = "test") public interface UsuarioRepository extends CrudRepository<Usuario, String> { List<Usuario> findBySeguidos(Usuario usuario); Usuario findByNombre(String nombre); @CacheEvict(allEntries = true) Usuario save(Usuario usuario); }
639
0.823161
0.823161
22
28.045454
23.890806
76
false
false
0
0
0
0
0
0
0.863636
false
false
14
94b452fd536735b888b7a755e5182dc1a00e45cb
8,744,553,454,457
1c6c9b4941d66f76a7e32f7f8be3eab83e5a6f19
/src/main/java/com/mdj20/quickgraph/quickgraph/main/Edge.java
4add1e42d517f5123104e89cda5982cdafbdeec4
[ "MIT" ]
permissive
mdj20/quickgraph
https://github.com/mdj20/quickgraph
9c3862e7fdfa5340e6e9aedbca28c5319642a475
572a0d94bbe6258b577fec1b1bdea44d0f55e030
refs/heads/master
2021-05-05T01:33:12.934000
2018-03-13T12:47:38
2018-03-13T12:47:38
119,672,728
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mdj20.quickgraph.quickgraph.main; import java.util.List; /** A pair of type V vertex used in the BaseGraph hierarchy. Denotes a connection between to vertices. * * @author Matthew D. Jeffreys * * @param <V> Type of vertex that the edge connects. */ public interface Edge<V> { /** * Returns a unmodifiable list containing 2 vertices. * * * @return List<V> of vertices */ public List<V> getVertices(); /** Returns vertex specified by index. * * @param index must be either 0 or 1 * @return V one of 2 vertices, or null if caller passes int !(1 || 0) */ public V getVertex(int index); /** * Returns the vertex that opposes the vertex being passed. Returns null if edge doesn't contain vertex being passed. * * * * @param vertex * @return V opposite vertex */ public V getOpposingVertex(V vertex); /** * Returns index of vertex, returns -1 if vertex is not connected by this edge. * * @param vertex vertex to search for. * @return index of vertex or -1 if vertex isn't found. */ public int indexOf(V vertex); /** * Convenience method determines if the passed edge is the reciprocal of this edge. * <p> * Used to determine edge equivalence in an undirected graph, * i.e. edge0 connects A->B, if edge1 B->A is passed to isReciprical method it will return true, * this holds true even if the edges are directed. * @param edge reference to edge whose reciprocity is to be determined. * @return true if passed edge is reciprocal of object edge. */ public boolean isReciprocal(Edge<V> edge); /** * Convenience method determines if the passed edge is parallel to this edge. * * * @param edge reference to edge that is to be determined parallel. * @return true if passed edge is parallel to this edge. */ public boolean isParallel(Edge<V> edge); }
UTF-8
Java
1,956
java
Edge.java
Java
[ { "context": " connection between to vertices. \r\n * \r\n * @author Matthew D. Jeffreys\r\n *\r\n * @param <V> Type of vertex that the edge c", "end": 213, "score": 0.9998695850372314, "start": 194, "tag": "NAME", "value": "Matthew D. Jeffreys" } ]
null
[]
package com.mdj20.quickgraph.quickgraph.main; import java.util.List; /** A pair of type V vertex used in the BaseGraph hierarchy. Denotes a connection between to vertices. * * @author <NAME> * * @param <V> Type of vertex that the edge connects. */ public interface Edge<V> { /** * Returns a unmodifiable list containing 2 vertices. * * * @return List<V> of vertices */ public List<V> getVertices(); /** Returns vertex specified by index. * * @param index must be either 0 or 1 * @return V one of 2 vertices, or null if caller passes int !(1 || 0) */ public V getVertex(int index); /** * Returns the vertex that opposes the vertex being passed. Returns null if edge doesn't contain vertex being passed. * * * * @param vertex * @return V opposite vertex */ public V getOpposingVertex(V vertex); /** * Returns index of vertex, returns -1 if vertex is not connected by this edge. * * @param vertex vertex to search for. * @return index of vertex or -1 if vertex isn't found. */ public int indexOf(V vertex); /** * Convenience method determines if the passed edge is the reciprocal of this edge. * <p> * Used to determine edge equivalence in an undirected graph, * i.e. edge0 connects A->B, if edge1 B->A is passed to isReciprical method it will return true, * this holds true even if the edges are directed. * @param edge reference to edge whose reciprocity is to be determined. * @return true if passed edge is reciprocal of object edge. */ public boolean isReciprocal(Edge<V> edge); /** * Convenience method determines if the passed edge is parallel to this edge. * * * @param edge reference to edge that is to be determined parallel. * @return true if passed edge is parallel to this edge. */ public boolean isParallel(Edge<V> edge); }
1,943
0.65593
0.649795
73
24.794521
29.849834
118
false
false
0
0
0
0
0
0
1.027397
false
false
14
2278c0466c28eb9749ea68e0c078df0a5a48639e
23,476,291,278,288
6baf1fe00541560788e78de5244ae17a7a2b375a
/hollywood/com.oculus.gamingactivity-GamingActivity/sources/com/oculus/modules/codegen/DialogsModule.java
b286f415e89ba170c26aa77121f1b04b959cca1d
[]
no_license
phwd/quest-tracker
https://github.com/phwd/quest-tracker
286e605644fc05f00f4904e51f73d77444a78003
3d46fbb467ba11bee5827f7cae7dfeabeb1fd2ba
refs/heads/main
2023-03-29T20:33:10.959000
2021-04-10T22:14:11
2021-04-10T22:14:11
357,185,040
4
2
null
true
2021-04-12T12:28:09
2021-04-12T12:28:08
2021-04-10T22:15:44
2021-04-10T22:15:39
116,441
0
0
0
null
false
false
package com.oculus.modules.codegen; import android.util.Pair; import com.oculus.ocms.library.provider.contract.OCMSLibraryContract; import com.oculus.panellib.modules.RCTBaseJavaModule; import java.util.ArrayList; import java.util.List; import org.json.JSONException; import org.json.JSONObject; public abstract class DialogsModule extends RCTBaseJavaModule { protected static final String MODULE_NAME = DialogsModule.class.getSimpleName(); public enum CommonDialogID { common_system_dialog_app_launch_blocked_controller_required, common_system_dialog_app_launch_blocked_hands_required, common_system_dialog_guardian_adjust } public enum DialogIconButtonIcon { info, settings } public enum DialogInformationBoxIcon { check_alt, info, spinner } public enum DialogListType { multiSelect, noSelect, singleSelect } public enum DialogPrimaryButtonStyle { danger, primary, secondary } /* access modifiers changed from: protected */ public abstract void hideDialogImpl(String str, Resolver<Void> resolver); /* access modifiers changed from: protected */ public abstract void showCommonDialogImpl(CommonDialogID commonDialogID, JSONObject jSONObject, Resolver<Void> resolver); /* access modifiers changed from: protected */ public abstract void showDialogImpl(DialogConfig dialogConfig, Resolver<Void> resolver); /* access modifiers changed from: protected */ public final String getModuleName() { return MODULE_NAME; } protected static final List<Pair<String, String>> describe() { List<Pair<String, String>> list = new ArrayList<>(); list.add(new Pair<>("hideDialog", "+sii")); list.add(new Pair<>("showCommonDialog", "+sjii")); list.add(new Pair<>("showDialog", "+jii")); return list; } /* access modifiers changed from: protected */ public final String marshallJSConstants() { return null; } /* access modifiers changed from: protected */ public final void emitOnDialogResult(DialogResult data) { nativeEmitEventWithJsonData(this.RVRCtxTag, "DialogsModule_onDialogResult", String.valueOf(data.convertToJSONObject())); } /* access modifiers changed from: protected */ public final void hideDialog(String dialogId, int resolveID, int rejectID) { hideDialogImpl(dialogId, ResolverFactory.createVoidResolver(this, resolveID, rejectID)); } /* access modifiers changed from: protected */ public final void showCommonDialog(String commonDialogId, JSONObject config, int resolveID, int rejectID) { showCommonDialogImpl(CommonDialogID.valueOf(commonDialogId), config, ResolverFactory.createVoidResolver(this, resolveID, rejectID)); } /* access modifiers changed from: protected */ public final void showDialog(JSONObject config, int resolveID, int rejectID) { showDialogImpl(DialogConfig.makeFromJSONObject(config), ResolverFactory.createVoidResolver(this, resolveID, rejectID)); } public void shutdownModule() { } public static class DialogResult extends NativeModuleParcel { public String action; public String dialogId; @Override // com.oculus.modules.codegen.NativeModuleParcel public final JSONObject convertToJSONObject() { JSONObject parcel = new JSONObject(); try { parcel.put("action", this.action); parcel.put("dialogId", this.dialogId); } catch (JSONException e) { } return parcel; } @Override // com.oculus.modules.codegen.NativeModuleParcel public final void setFromJSONObject(JSONObject json) { this.action = json.optString("action"); this.dialogId = json.optString("dialogId"); } public static final DialogResult makeFromJSONObject(JSONObject json) { if (json == null) { return null; } DialogResult result = new DialogResult(); result.setFromJSONObject(json); return result; } } public static class DialogConfig extends NativeModuleParcel { public DialogButton backButton; public String body; public DialogButton controllerBackButton; public String dialogId; public DialogHeroSpace heroSpace; public DialogIconButton iconButton; public DialogInformationBox informationBox; public List<DialogInlineImage> inlineImages; public DialogList list; public DialogPrimaryButton primaryButton; public DialogTextButton secondaryButton; public DialogTextButton tertiaryButton; public String title; @Override // com.oculus.modules.codegen.NativeModuleParcel public final JSONObject convertToJSONObject() { JSONObject parcel = new JSONObject(); try { if (this.backButton != null) { parcel.put("backButton", this.backButton.convertToJSONObject()); } if (this.body != null) { parcel.put("body", this.body); } if (this.controllerBackButton != null) { parcel.put("controllerBackButton", this.controllerBackButton.convertToJSONObject()); } parcel.put("dialogId", this.dialogId); if (this.heroSpace != null) { parcel.put("heroSpace", this.heroSpace.convertToJSONObject()); } if (this.iconButton != null) { parcel.put("iconButton", this.iconButton.convertToJSONObject()); } if (this.informationBox != null) { parcel.put("informationBox", this.informationBox.convertToJSONObject()); } if (this.inlineImages != null) { parcel.put("inlineImages", NativeModuleParcel.convertParcelListToJSONArray(this.inlineImages)); } if (this.list != null) { parcel.put("list", this.list.convertToJSONObject()); } if (this.primaryButton != null) { parcel.put("primaryButton", this.primaryButton.convertToJSONObject()); } if (this.secondaryButton != null) { parcel.put("secondaryButton", this.secondaryButton.convertToJSONObject()); } if (this.tertiaryButton != null) { parcel.put("tertiaryButton", this.tertiaryButton.convertToJSONObject()); } if (this.title != null) { parcel.put("title", this.title); } } catch (JSONException e) { } return parcel; } @Override // com.oculus.modules.codegen.NativeModuleParcel public final void setFromJSONObject(JSONObject json) { String str = null; this.backButton = json.isNull("backButton") ? null : DialogButton.makeFromJSONObject(json.optJSONObject("backButton")); this.body = json.isNull("body") ? null : json.optString("body"); this.controllerBackButton = json.isNull("controllerBackButton") ? null : DialogButton.makeFromJSONObject(json.optJSONObject("controllerBackButton")); this.dialogId = json.optString("dialogId"); this.heroSpace = json.isNull("heroSpace") ? null : DialogHeroSpace.makeFromJSONObject(json.optJSONObject("heroSpace")); this.iconButton = json.isNull("iconButton") ? null : DialogIconButton.makeFromJSONObject(json.optJSONObject("iconButton")); this.informationBox = json.isNull("informationBox") ? null : DialogInformationBox.makeFromJSONObject(json.optJSONObject("informationBox")); this.inlineImages = json.isNull("inlineImages") ? null : NativeModuleParcel.convertJSONArrayToParcelList(json.optJSONArray("inlineImages"), DialogInlineImage.class); this.list = json.isNull("list") ? null : DialogList.makeFromJSONObject(json.optJSONObject("list")); this.primaryButton = json.isNull("primaryButton") ? null : DialogPrimaryButton.makeFromJSONObject(json.optJSONObject("primaryButton")); this.secondaryButton = json.isNull("secondaryButton") ? null : DialogTextButton.makeFromJSONObject(json.optJSONObject("secondaryButton")); this.tertiaryButton = json.isNull("tertiaryButton") ? null : DialogTextButton.makeFromJSONObject(json.optJSONObject("tertiaryButton")); if (!json.isNull("title")) { str = json.optString("title"); } this.title = str; } public static final DialogConfig makeFromJSONObject(JSONObject json) { if (json == null) { return null; } DialogConfig result = new DialogConfig(); result.setFromJSONObject(json); return result; } } public static class DialogButton extends NativeModuleParcel { public String action; public Boolean autoClose; @Override // com.oculus.modules.codegen.NativeModuleParcel public final JSONObject convertToJSONObject() { JSONObject parcel = new JSONObject(); try { parcel.put("action", this.action); if (this.autoClose != null) { parcel.put("autoClose", this.autoClose); } } catch (JSONException e) { } return parcel; } @Override // com.oculus.modules.codegen.NativeModuleParcel public final void setFromJSONObject(JSONObject json) { this.action = json.optString("action"); this.autoClose = json.isNull("autoClose") ? null : Boolean.valueOf(json.optBoolean("autoClose")); } public static final DialogButton makeFromJSONObject(JSONObject json) { if (json == null) { return null; } DialogButton result = new DialogButton(); result.setFromJSONObject(json); return result; } } public static class DialogHeroSpace extends NativeModuleParcel { public double aspectRatio; public String backgroundColor; public String imageSourceUrl; public String videoSourceUrl; @Override // com.oculus.modules.codegen.NativeModuleParcel public final JSONObject convertToJSONObject() { JSONObject parcel = new JSONObject(); try { parcel.put("aspectRatio", this.aspectRatio); if (this.backgroundColor != null) { parcel.put("backgroundColor", this.backgroundColor); } if (this.imageSourceUrl != null) { parcel.put("imageSourceUrl", this.imageSourceUrl); } if (this.videoSourceUrl != null) { parcel.put("videoSourceUrl", this.videoSourceUrl); } } catch (JSONException e) { } return parcel; } @Override // com.oculus.modules.codegen.NativeModuleParcel public final void setFromJSONObject(JSONObject json) { String str = null; this.aspectRatio = json.optDouble("aspectRatio", 0.0d); this.backgroundColor = json.isNull("backgroundColor") ? null : json.optString("backgroundColor"); this.imageSourceUrl = json.isNull("imageSourceUrl") ? null : json.optString("imageSourceUrl"); if (!json.isNull("videoSourceUrl")) { str = json.optString("videoSourceUrl"); } this.videoSourceUrl = str; } public static final DialogHeroSpace makeFromJSONObject(JSONObject json) { if (json == null) { return null; } DialogHeroSpace result = new DialogHeroSpace(); result.setFromJSONObject(json); return result; } } public static class DialogIconButton extends NativeModuleParcel { public String action; public Boolean autoClose; public DialogIconButtonIcon icon; @Override // com.oculus.modules.codegen.NativeModuleParcel public final JSONObject convertToJSONObject() { JSONObject parcel = new JSONObject(); try { parcel.put("action", this.action); if (this.autoClose != null) { parcel.put("autoClose", this.autoClose); } parcel.put("icon", this.icon.name()); } catch (JSONException e) { } return parcel; } @Override // com.oculus.modules.codegen.NativeModuleParcel public final void setFromJSONObject(JSONObject json) { this.action = json.optString("action"); this.autoClose = json.isNull("autoClose") ? null : Boolean.valueOf(json.optBoolean("autoClose")); this.icon = DialogIconButtonIcon.valueOf(json.optString("icon")); } public static final DialogIconButton makeFromJSONObject(JSONObject json) { if (json == null) { return null; } DialogIconButton result = new DialogIconButton(); result.setFromJSONObject(json); return result; } } public static class DialogInformationBox extends NativeModuleParcel { public DialogInformationBoxIcon icon; public String text; @Override // com.oculus.modules.codegen.NativeModuleParcel public final JSONObject convertToJSONObject() { JSONObject parcel = new JSONObject(); try { if (this.icon != null) { parcel.put("icon", this.icon.name()); } parcel.put("text", this.text); } catch (JSONException e) { } return parcel; } @Override // com.oculus.modules.codegen.NativeModuleParcel public final void setFromJSONObject(JSONObject json) { this.icon = json.isNull("icon") ? null : DialogInformationBoxIcon.valueOf(json.optString("icon")); this.text = json.optString("text"); } public static final DialogInformationBox makeFromJSONObject(JSONObject json) { if (json == null) { return null; } DialogInformationBox result = new DialogInformationBox(); result.setFromJSONObject(json); return result; } } public static class DialogInlineImage extends NativeModuleParcel { public String image; public String placeholder; @Override // com.oculus.modules.codegen.NativeModuleParcel public final JSONObject convertToJSONObject() { JSONObject parcel = new JSONObject(); try { parcel.put("image", this.image); parcel.put("placeholder", this.placeholder); } catch (JSONException e) { } return parcel; } @Override // com.oculus.modules.codegen.NativeModuleParcel public final void setFromJSONObject(JSONObject json) { this.image = json.optString("image"); this.placeholder = json.optString("placeholder"); } public static final DialogInlineImage makeFromJSONObject(JSONObject json) { if (json == null) { return null; } DialogInlineImage result = new DialogInlineImage(); result.setFromJSONObject(json); return result; } } public static class DialogList extends NativeModuleParcel { public List<DialogListItem> items; public DialogListType type; @Override // com.oculus.modules.codegen.NativeModuleParcel public final JSONObject convertToJSONObject() { JSONObject parcel = new JSONObject(); try { parcel.put("items", NativeModuleParcel.convertParcelListToJSONArray(this.items)); parcel.put("type", this.type.name()); } catch (JSONException e) { } return parcel; } @Override // com.oculus.modules.codegen.NativeModuleParcel public final void setFromJSONObject(JSONObject json) { this.items = NativeModuleParcel.convertJSONArrayToParcelList(json.optJSONArray("items"), DialogListItem.class); this.type = DialogListType.valueOf(json.optString("type")); } public static final DialogList makeFromJSONObject(JSONObject json) { if (json == null) { return null; } DialogList result = new DialogList(); result.setFromJSONObject(json); return result; } } public static class DialogListItem extends NativeModuleParcel { public String bodyText; public String id; public String image; public String titleText; @Override // com.oculus.modules.codegen.NativeModuleParcel public final JSONObject convertToJSONObject() { JSONObject parcel = new JSONObject(); try { if (this.bodyText != null) { parcel.put("bodyText", this.bodyText); } parcel.put(OCMSLibraryContract.ASSETS_PATH_BY_ID, this.id); if (this.image != null) { parcel.put("image", this.image); } parcel.put("titleText", this.titleText); } catch (JSONException e) { } return parcel; } @Override // com.oculus.modules.codegen.NativeModuleParcel public final void setFromJSONObject(JSONObject json) { String str = null; this.bodyText = json.isNull("bodyText") ? null : json.optString("bodyText"); this.id = json.optString(OCMSLibraryContract.ASSETS_PATH_BY_ID); if (!json.isNull("image")) { str = json.optString("image"); } this.image = str; this.titleText = json.optString("titleText"); } public static final DialogListItem makeFromJSONObject(JSONObject json) { if (json == null) { return null; } DialogListItem result = new DialogListItem(); result.setFromJSONObject(json); return result; } } public static class DialogPrimaryButton extends NativeModuleParcel { public String action; public Boolean autoClose; public Boolean disabled; public Boolean disabledUntilBodyScrolledToBottom; public DialogPrimaryButtonStyle style; public String text; @Override // com.oculus.modules.codegen.NativeModuleParcel public final JSONObject convertToJSONObject() { JSONObject parcel = new JSONObject(); try { parcel.put("action", this.action); if (this.autoClose != null) { parcel.put("autoClose", this.autoClose); } if (this.disabled != null) { parcel.put("disabled", this.disabled); } if (this.disabledUntilBodyScrolledToBottom != null) { parcel.put("disabledUntilBodyScrolledToBottom", this.disabledUntilBodyScrolledToBottom); } parcel.put("text", this.text); if (this.style != null) { parcel.put("style", this.style.name()); } } catch (JSONException e) { } return parcel; } @Override // com.oculus.modules.codegen.NativeModuleParcel public final void setFromJSONObject(JSONObject json) { DialogPrimaryButtonStyle dialogPrimaryButtonStyle = null; this.action = json.optString("action"); this.autoClose = json.isNull("autoClose") ? null : Boolean.valueOf(json.optBoolean("autoClose")); this.disabled = json.isNull("disabled") ? null : Boolean.valueOf(json.optBoolean("disabled")); this.disabledUntilBodyScrolledToBottom = json.isNull("disabledUntilBodyScrolledToBottom") ? null : Boolean.valueOf(json.optBoolean("disabledUntilBodyScrolledToBottom")); this.text = json.optString("text"); if (!json.isNull("style")) { dialogPrimaryButtonStyle = DialogPrimaryButtonStyle.valueOf(json.optString("style")); } this.style = dialogPrimaryButtonStyle; } public static final DialogPrimaryButton makeFromJSONObject(JSONObject json) { if (json == null) { return null; } DialogPrimaryButton result = new DialogPrimaryButton(); result.setFromJSONObject(json); return result; } } public static class DialogTextButton extends NativeModuleParcel { public String action; public Boolean autoClose; public Boolean disabled; public Boolean disabledUntilBodyScrolledToBottom; public String text; @Override // com.oculus.modules.codegen.NativeModuleParcel public final JSONObject convertToJSONObject() { JSONObject parcel = new JSONObject(); try { parcel.put("action", this.action); if (this.autoClose != null) { parcel.put("autoClose", this.autoClose); } if (this.disabled != null) { parcel.put("disabled", this.disabled); } if (this.disabledUntilBodyScrolledToBottom != null) { parcel.put("disabledUntilBodyScrolledToBottom", this.disabledUntilBodyScrolledToBottom); } parcel.put("text", this.text); } catch (JSONException e) { } return parcel; } @Override // com.oculus.modules.codegen.NativeModuleParcel public final void setFromJSONObject(JSONObject json) { Boolean bool = null; this.action = json.optString("action"); this.autoClose = json.isNull("autoClose") ? null : Boolean.valueOf(json.optBoolean("autoClose")); this.disabled = json.isNull("disabled") ? null : Boolean.valueOf(json.optBoolean("disabled")); if (!json.isNull("disabledUntilBodyScrolledToBottom")) { bool = Boolean.valueOf(json.optBoolean("disabledUntilBodyScrolledToBottom")); } this.disabledUntilBodyScrolledToBottom = bool; this.text = json.optString("text"); } public static final DialogTextButton makeFromJSONObject(JSONObject json) { if (json == null) { return null; } DialogTextButton result = new DialogTextButton(); result.setFromJSONObject(json); return result; } } }
UTF-8
Java
23,451
java
DialogsModule.java
Java
[]
null
[]
package com.oculus.modules.codegen; import android.util.Pair; import com.oculus.ocms.library.provider.contract.OCMSLibraryContract; import com.oculus.panellib.modules.RCTBaseJavaModule; import java.util.ArrayList; import java.util.List; import org.json.JSONException; import org.json.JSONObject; public abstract class DialogsModule extends RCTBaseJavaModule { protected static final String MODULE_NAME = DialogsModule.class.getSimpleName(); public enum CommonDialogID { common_system_dialog_app_launch_blocked_controller_required, common_system_dialog_app_launch_blocked_hands_required, common_system_dialog_guardian_adjust } public enum DialogIconButtonIcon { info, settings } public enum DialogInformationBoxIcon { check_alt, info, spinner } public enum DialogListType { multiSelect, noSelect, singleSelect } public enum DialogPrimaryButtonStyle { danger, primary, secondary } /* access modifiers changed from: protected */ public abstract void hideDialogImpl(String str, Resolver<Void> resolver); /* access modifiers changed from: protected */ public abstract void showCommonDialogImpl(CommonDialogID commonDialogID, JSONObject jSONObject, Resolver<Void> resolver); /* access modifiers changed from: protected */ public abstract void showDialogImpl(DialogConfig dialogConfig, Resolver<Void> resolver); /* access modifiers changed from: protected */ public final String getModuleName() { return MODULE_NAME; } protected static final List<Pair<String, String>> describe() { List<Pair<String, String>> list = new ArrayList<>(); list.add(new Pair<>("hideDialog", "+sii")); list.add(new Pair<>("showCommonDialog", "+sjii")); list.add(new Pair<>("showDialog", "+jii")); return list; } /* access modifiers changed from: protected */ public final String marshallJSConstants() { return null; } /* access modifiers changed from: protected */ public final void emitOnDialogResult(DialogResult data) { nativeEmitEventWithJsonData(this.RVRCtxTag, "DialogsModule_onDialogResult", String.valueOf(data.convertToJSONObject())); } /* access modifiers changed from: protected */ public final void hideDialog(String dialogId, int resolveID, int rejectID) { hideDialogImpl(dialogId, ResolverFactory.createVoidResolver(this, resolveID, rejectID)); } /* access modifiers changed from: protected */ public final void showCommonDialog(String commonDialogId, JSONObject config, int resolveID, int rejectID) { showCommonDialogImpl(CommonDialogID.valueOf(commonDialogId), config, ResolverFactory.createVoidResolver(this, resolveID, rejectID)); } /* access modifiers changed from: protected */ public final void showDialog(JSONObject config, int resolveID, int rejectID) { showDialogImpl(DialogConfig.makeFromJSONObject(config), ResolverFactory.createVoidResolver(this, resolveID, rejectID)); } public void shutdownModule() { } public static class DialogResult extends NativeModuleParcel { public String action; public String dialogId; @Override // com.oculus.modules.codegen.NativeModuleParcel public final JSONObject convertToJSONObject() { JSONObject parcel = new JSONObject(); try { parcel.put("action", this.action); parcel.put("dialogId", this.dialogId); } catch (JSONException e) { } return parcel; } @Override // com.oculus.modules.codegen.NativeModuleParcel public final void setFromJSONObject(JSONObject json) { this.action = json.optString("action"); this.dialogId = json.optString("dialogId"); } public static final DialogResult makeFromJSONObject(JSONObject json) { if (json == null) { return null; } DialogResult result = new DialogResult(); result.setFromJSONObject(json); return result; } } public static class DialogConfig extends NativeModuleParcel { public DialogButton backButton; public String body; public DialogButton controllerBackButton; public String dialogId; public DialogHeroSpace heroSpace; public DialogIconButton iconButton; public DialogInformationBox informationBox; public List<DialogInlineImage> inlineImages; public DialogList list; public DialogPrimaryButton primaryButton; public DialogTextButton secondaryButton; public DialogTextButton tertiaryButton; public String title; @Override // com.oculus.modules.codegen.NativeModuleParcel public final JSONObject convertToJSONObject() { JSONObject parcel = new JSONObject(); try { if (this.backButton != null) { parcel.put("backButton", this.backButton.convertToJSONObject()); } if (this.body != null) { parcel.put("body", this.body); } if (this.controllerBackButton != null) { parcel.put("controllerBackButton", this.controllerBackButton.convertToJSONObject()); } parcel.put("dialogId", this.dialogId); if (this.heroSpace != null) { parcel.put("heroSpace", this.heroSpace.convertToJSONObject()); } if (this.iconButton != null) { parcel.put("iconButton", this.iconButton.convertToJSONObject()); } if (this.informationBox != null) { parcel.put("informationBox", this.informationBox.convertToJSONObject()); } if (this.inlineImages != null) { parcel.put("inlineImages", NativeModuleParcel.convertParcelListToJSONArray(this.inlineImages)); } if (this.list != null) { parcel.put("list", this.list.convertToJSONObject()); } if (this.primaryButton != null) { parcel.put("primaryButton", this.primaryButton.convertToJSONObject()); } if (this.secondaryButton != null) { parcel.put("secondaryButton", this.secondaryButton.convertToJSONObject()); } if (this.tertiaryButton != null) { parcel.put("tertiaryButton", this.tertiaryButton.convertToJSONObject()); } if (this.title != null) { parcel.put("title", this.title); } } catch (JSONException e) { } return parcel; } @Override // com.oculus.modules.codegen.NativeModuleParcel public final void setFromJSONObject(JSONObject json) { String str = null; this.backButton = json.isNull("backButton") ? null : DialogButton.makeFromJSONObject(json.optJSONObject("backButton")); this.body = json.isNull("body") ? null : json.optString("body"); this.controllerBackButton = json.isNull("controllerBackButton") ? null : DialogButton.makeFromJSONObject(json.optJSONObject("controllerBackButton")); this.dialogId = json.optString("dialogId"); this.heroSpace = json.isNull("heroSpace") ? null : DialogHeroSpace.makeFromJSONObject(json.optJSONObject("heroSpace")); this.iconButton = json.isNull("iconButton") ? null : DialogIconButton.makeFromJSONObject(json.optJSONObject("iconButton")); this.informationBox = json.isNull("informationBox") ? null : DialogInformationBox.makeFromJSONObject(json.optJSONObject("informationBox")); this.inlineImages = json.isNull("inlineImages") ? null : NativeModuleParcel.convertJSONArrayToParcelList(json.optJSONArray("inlineImages"), DialogInlineImage.class); this.list = json.isNull("list") ? null : DialogList.makeFromJSONObject(json.optJSONObject("list")); this.primaryButton = json.isNull("primaryButton") ? null : DialogPrimaryButton.makeFromJSONObject(json.optJSONObject("primaryButton")); this.secondaryButton = json.isNull("secondaryButton") ? null : DialogTextButton.makeFromJSONObject(json.optJSONObject("secondaryButton")); this.tertiaryButton = json.isNull("tertiaryButton") ? null : DialogTextButton.makeFromJSONObject(json.optJSONObject("tertiaryButton")); if (!json.isNull("title")) { str = json.optString("title"); } this.title = str; } public static final DialogConfig makeFromJSONObject(JSONObject json) { if (json == null) { return null; } DialogConfig result = new DialogConfig(); result.setFromJSONObject(json); return result; } } public static class DialogButton extends NativeModuleParcel { public String action; public Boolean autoClose; @Override // com.oculus.modules.codegen.NativeModuleParcel public final JSONObject convertToJSONObject() { JSONObject parcel = new JSONObject(); try { parcel.put("action", this.action); if (this.autoClose != null) { parcel.put("autoClose", this.autoClose); } } catch (JSONException e) { } return parcel; } @Override // com.oculus.modules.codegen.NativeModuleParcel public final void setFromJSONObject(JSONObject json) { this.action = json.optString("action"); this.autoClose = json.isNull("autoClose") ? null : Boolean.valueOf(json.optBoolean("autoClose")); } public static final DialogButton makeFromJSONObject(JSONObject json) { if (json == null) { return null; } DialogButton result = new DialogButton(); result.setFromJSONObject(json); return result; } } public static class DialogHeroSpace extends NativeModuleParcel { public double aspectRatio; public String backgroundColor; public String imageSourceUrl; public String videoSourceUrl; @Override // com.oculus.modules.codegen.NativeModuleParcel public final JSONObject convertToJSONObject() { JSONObject parcel = new JSONObject(); try { parcel.put("aspectRatio", this.aspectRatio); if (this.backgroundColor != null) { parcel.put("backgroundColor", this.backgroundColor); } if (this.imageSourceUrl != null) { parcel.put("imageSourceUrl", this.imageSourceUrl); } if (this.videoSourceUrl != null) { parcel.put("videoSourceUrl", this.videoSourceUrl); } } catch (JSONException e) { } return parcel; } @Override // com.oculus.modules.codegen.NativeModuleParcel public final void setFromJSONObject(JSONObject json) { String str = null; this.aspectRatio = json.optDouble("aspectRatio", 0.0d); this.backgroundColor = json.isNull("backgroundColor") ? null : json.optString("backgroundColor"); this.imageSourceUrl = json.isNull("imageSourceUrl") ? null : json.optString("imageSourceUrl"); if (!json.isNull("videoSourceUrl")) { str = json.optString("videoSourceUrl"); } this.videoSourceUrl = str; } public static final DialogHeroSpace makeFromJSONObject(JSONObject json) { if (json == null) { return null; } DialogHeroSpace result = new DialogHeroSpace(); result.setFromJSONObject(json); return result; } } public static class DialogIconButton extends NativeModuleParcel { public String action; public Boolean autoClose; public DialogIconButtonIcon icon; @Override // com.oculus.modules.codegen.NativeModuleParcel public final JSONObject convertToJSONObject() { JSONObject parcel = new JSONObject(); try { parcel.put("action", this.action); if (this.autoClose != null) { parcel.put("autoClose", this.autoClose); } parcel.put("icon", this.icon.name()); } catch (JSONException e) { } return parcel; } @Override // com.oculus.modules.codegen.NativeModuleParcel public final void setFromJSONObject(JSONObject json) { this.action = json.optString("action"); this.autoClose = json.isNull("autoClose") ? null : Boolean.valueOf(json.optBoolean("autoClose")); this.icon = DialogIconButtonIcon.valueOf(json.optString("icon")); } public static final DialogIconButton makeFromJSONObject(JSONObject json) { if (json == null) { return null; } DialogIconButton result = new DialogIconButton(); result.setFromJSONObject(json); return result; } } public static class DialogInformationBox extends NativeModuleParcel { public DialogInformationBoxIcon icon; public String text; @Override // com.oculus.modules.codegen.NativeModuleParcel public final JSONObject convertToJSONObject() { JSONObject parcel = new JSONObject(); try { if (this.icon != null) { parcel.put("icon", this.icon.name()); } parcel.put("text", this.text); } catch (JSONException e) { } return parcel; } @Override // com.oculus.modules.codegen.NativeModuleParcel public final void setFromJSONObject(JSONObject json) { this.icon = json.isNull("icon") ? null : DialogInformationBoxIcon.valueOf(json.optString("icon")); this.text = json.optString("text"); } public static final DialogInformationBox makeFromJSONObject(JSONObject json) { if (json == null) { return null; } DialogInformationBox result = new DialogInformationBox(); result.setFromJSONObject(json); return result; } } public static class DialogInlineImage extends NativeModuleParcel { public String image; public String placeholder; @Override // com.oculus.modules.codegen.NativeModuleParcel public final JSONObject convertToJSONObject() { JSONObject parcel = new JSONObject(); try { parcel.put("image", this.image); parcel.put("placeholder", this.placeholder); } catch (JSONException e) { } return parcel; } @Override // com.oculus.modules.codegen.NativeModuleParcel public final void setFromJSONObject(JSONObject json) { this.image = json.optString("image"); this.placeholder = json.optString("placeholder"); } public static final DialogInlineImage makeFromJSONObject(JSONObject json) { if (json == null) { return null; } DialogInlineImage result = new DialogInlineImage(); result.setFromJSONObject(json); return result; } } public static class DialogList extends NativeModuleParcel { public List<DialogListItem> items; public DialogListType type; @Override // com.oculus.modules.codegen.NativeModuleParcel public final JSONObject convertToJSONObject() { JSONObject parcel = new JSONObject(); try { parcel.put("items", NativeModuleParcel.convertParcelListToJSONArray(this.items)); parcel.put("type", this.type.name()); } catch (JSONException e) { } return parcel; } @Override // com.oculus.modules.codegen.NativeModuleParcel public final void setFromJSONObject(JSONObject json) { this.items = NativeModuleParcel.convertJSONArrayToParcelList(json.optJSONArray("items"), DialogListItem.class); this.type = DialogListType.valueOf(json.optString("type")); } public static final DialogList makeFromJSONObject(JSONObject json) { if (json == null) { return null; } DialogList result = new DialogList(); result.setFromJSONObject(json); return result; } } public static class DialogListItem extends NativeModuleParcel { public String bodyText; public String id; public String image; public String titleText; @Override // com.oculus.modules.codegen.NativeModuleParcel public final JSONObject convertToJSONObject() { JSONObject parcel = new JSONObject(); try { if (this.bodyText != null) { parcel.put("bodyText", this.bodyText); } parcel.put(OCMSLibraryContract.ASSETS_PATH_BY_ID, this.id); if (this.image != null) { parcel.put("image", this.image); } parcel.put("titleText", this.titleText); } catch (JSONException e) { } return parcel; } @Override // com.oculus.modules.codegen.NativeModuleParcel public final void setFromJSONObject(JSONObject json) { String str = null; this.bodyText = json.isNull("bodyText") ? null : json.optString("bodyText"); this.id = json.optString(OCMSLibraryContract.ASSETS_PATH_BY_ID); if (!json.isNull("image")) { str = json.optString("image"); } this.image = str; this.titleText = json.optString("titleText"); } public static final DialogListItem makeFromJSONObject(JSONObject json) { if (json == null) { return null; } DialogListItem result = new DialogListItem(); result.setFromJSONObject(json); return result; } } public static class DialogPrimaryButton extends NativeModuleParcel { public String action; public Boolean autoClose; public Boolean disabled; public Boolean disabledUntilBodyScrolledToBottom; public DialogPrimaryButtonStyle style; public String text; @Override // com.oculus.modules.codegen.NativeModuleParcel public final JSONObject convertToJSONObject() { JSONObject parcel = new JSONObject(); try { parcel.put("action", this.action); if (this.autoClose != null) { parcel.put("autoClose", this.autoClose); } if (this.disabled != null) { parcel.put("disabled", this.disabled); } if (this.disabledUntilBodyScrolledToBottom != null) { parcel.put("disabledUntilBodyScrolledToBottom", this.disabledUntilBodyScrolledToBottom); } parcel.put("text", this.text); if (this.style != null) { parcel.put("style", this.style.name()); } } catch (JSONException e) { } return parcel; } @Override // com.oculus.modules.codegen.NativeModuleParcel public final void setFromJSONObject(JSONObject json) { DialogPrimaryButtonStyle dialogPrimaryButtonStyle = null; this.action = json.optString("action"); this.autoClose = json.isNull("autoClose") ? null : Boolean.valueOf(json.optBoolean("autoClose")); this.disabled = json.isNull("disabled") ? null : Boolean.valueOf(json.optBoolean("disabled")); this.disabledUntilBodyScrolledToBottom = json.isNull("disabledUntilBodyScrolledToBottom") ? null : Boolean.valueOf(json.optBoolean("disabledUntilBodyScrolledToBottom")); this.text = json.optString("text"); if (!json.isNull("style")) { dialogPrimaryButtonStyle = DialogPrimaryButtonStyle.valueOf(json.optString("style")); } this.style = dialogPrimaryButtonStyle; } public static final DialogPrimaryButton makeFromJSONObject(JSONObject json) { if (json == null) { return null; } DialogPrimaryButton result = new DialogPrimaryButton(); result.setFromJSONObject(json); return result; } } public static class DialogTextButton extends NativeModuleParcel { public String action; public Boolean autoClose; public Boolean disabled; public Boolean disabledUntilBodyScrolledToBottom; public String text; @Override // com.oculus.modules.codegen.NativeModuleParcel public final JSONObject convertToJSONObject() { JSONObject parcel = new JSONObject(); try { parcel.put("action", this.action); if (this.autoClose != null) { parcel.put("autoClose", this.autoClose); } if (this.disabled != null) { parcel.put("disabled", this.disabled); } if (this.disabledUntilBodyScrolledToBottom != null) { parcel.put("disabledUntilBodyScrolledToBottom", this.disabledUntilBodyScrolledToBottom); } parcel.put("text", this.text); } catch (JSONException e) { } return parcel; } @Override // com.oculus.modules.codegen.NativeModuleParcel public final void setFromJSONObject(JSONObject json) { Boolean bool = null; this.action = json.optString("action"); this.autoClose = json.isNull("autoClose") ? null : Boolean.valueOf(json.optBoolean("autoClose")); this.disabled = json.isNull("disabled") ? null : Boolean.valueOf(json.optBoolean("disabled")); if (!json.isNull("disabledUntilBodyScrolledToBottom")) { bool = Boolean.valueOf(json.optBoolean("disabledUntilBodyScrolledToBottom")); } this.disabledUntilBodyScrolledToBottom = bool; this.text = json.optString("text"); } public static final DialogTextButton makeFromJSONObject(JSONObject json) { if (json == null) { return null; } DialogTextButton result = new DialogTextButton(); result.setFromJSONObject(json); return result; } } }
23,451
0.598525
0.598439
576
39.713543
31.836926
181
false
false
0
0
0
0
0
0
0.553819
false
false
14
0639ffdd895c1396ac4e681f9c611ecbebdf8244
20,375,324,862,811
c3aa1125807052af55ac51c2b4114ec2749e1ac5
/brouilles-service/src/main/java/com/les/brouilles/planner/service/constraint/DevisJsonConstraintValidator.java
adcd9e55b0bd96c0002174d3ab3e76c488a25ae2
[]
no_license
Rouliboy/brouilles
https://github.com/Rouliboy/brouilles
a6807b888e6a88bf6dc6f9533eda4d143df98e33
ab11662b4983e6dfa509168aea910b6c6187f691
refs/heads/master
2018-09-30T10:04:11.409000
2018-07-21T17:38:09
2018-07-21T17:38:09
121,974,328
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.les.brouilles.planner.service.constraint; import java.text.MessageFormat; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import org.springframework.beans.factory.annotation.Autowired; import com.les.brouilles.planner.service.dto.DevisDTO; import lombok.extern.slf4j.Slf4j; @Slf4j public class DevisJsonConstraintValidator implements ConstraintValidator<DevisJsonValide, DevisDTO> { private static final String MESSAGE = "Le devis {0} avec pour type {1} a le json suivant invalide : {2}"; private DevisJsonContentValidator devisJsonValidator; @Autowired public DevisJsonConstraintValidator(final DevisJsonContentValidator jsonValidator) { this.devisJsonValidator = jsonValidator; } @Override public void initialize(final DevisJsonValide constraintAnnotation) { } @Override public boolean isValid(final DevisDTO devis, final ConstraintValidatorContext context) { overrideMessage(devis, context); return devisJsonValidator.validate(devis); } private void overrideMessage(final DevisDTO devis, final ConstraintValidatorContext context) { final String message = MessageFormat.format(MESSAGE, devis.getNumeroDevis(), devis.getTypeDevis(), devis.getJson()); // disable existing violation message context.disableDefaultConstraintViolation(); // build new violation message and add it context.buildConstraintViolationWithTemplate(message).addConstraintViolation(); } }
UTF-8
Java
1,471
java
DevisJsonConstraintValidator.java
Java
[]
null
[]
package com.les.brouilles.planner.service.constraint; import java.text.MessageFormat; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import org.springframework.beans.factory.annotation.Autowired; import com.les.brouilles.planner.service.dto.DevisDTO; import lombok.extern.slf4j.Slf4j; @Slf4j public class DevisJsonConstraintValidator implements ConstraintValidator<DevisJsonValide, DevisDTO> { private static final String MESSAGE = "Le devis {0} avec pour type {1} a le json suivant invalide : {2}"; private DevisJsonContentValidator devisJsonValidator; @Autowired public DevisJsonConstraintValidator(final DevisJsonContentValidator jsonValidator) { this.devisJsonValidator = jsonValidator; } @Override public void initialize(final DevisJsonValide constraintAnnotation) { } @Override public boolean isValid(final DevisDTO devis, final ConstraintValidatorContext context) { overrideMessage(devis, context); return devisJsonValidator.validate(devis); } private void overrideMessage(final DevisDTO devis, final ConstraintValidatorContext context) { final String message = MessageFormat.format(MESSAGE, devis.getNumeroDevis(), devis.getTypeDevis(), devis.getJson()); // disable existing violation message context.disableDefaultConstraintViolation(); // build new violation message and add it context.buildConstraintViolationWithTemplate(message).addConstraintViolation(); } }
1,471
0.813052
0.808973
49
29.040817
33.756004
106
false
false
0
0
0
0
0
0
1.122449
false
false
14
c7d00f886ecf26c2206f4168884414ad4dc1ad9b
3,040,836,883,426
bc66e9d72116f35f7d18a93a01035a7ca99e7898
/Lesson14/src/ZooObservable/Main.java
d716062789edf6b88d5c8533edb9020e7abbdbab
[]
no_license
DjDyXx/hillelJava-IgorMarinich-
https://github.com/DjDyXx/hillelJava-IgorMarinich-
dd2952478a07ab1354563fe0c31ea8dc737bedcc
66441718bc10886fadb477312da65bbb0bf9769d
refs/heads/master
2021-01-23T07:30:04.833000
2017-04-13T13:50:49
2017-04-13T13:50:49
80,374,752
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ZooObservable; import ZooObservable.Animal.Animal; import ZooObservable.Animal.Domestic; import ZooObservable.Animal.Wild; import ZooObservable.Workers.*; public class Main { public static void main(String[] args) { Animal Wolf = new Wild(1 , "Wolfik"); Animal Cat = new Domestic(2, "Marsik"); Worker feeder = new Feeder("Fedorenko"); Worker director = new Director("Ivanovich"); Worker hairdresser = new Groomer("Selvertorov"); Worker veterinarian = new Veterinarian("Petrov"); Cat.subscribe(feeder); Cat.subscribe(director); Cat.subscribe(hairdresser); Cat.subscribe(veterinarian); Wolf.subscribe(hairdresser); Cat.hungry(); Cat.getGroom(); Cat.getIll(); } }
UTF-8
Java
798
java
Main.java
Java
[ { "context": "ing[] args) {\n Animal Wolf = new Wild(1 , \"Wolfik\");\n Animal Cat = new Domestic(2, \"Marsik\")", "end": 273, "score": 0.9995368123054504, "start": 267, "tag": "NAME", "value": "Wolfik" }, { "context": " \"Wolfik\");\n Animal Cat = new Domestic(2, \"Marsik\");\n\n\n Worker feeder = new Feeder(\"Fedorenk", "end": 321, "score": 0.9995740056037903, "start": 315, "tag": "NAME", "value": "Marsik" }, { "context": " \"Marsik\");\n\n\n Worker feeder = new Feeder(\"Fedorenko\");\n Worker director = new Director(\"Ivanov", "end": 372, "score": 0.9998302459716797, "start": 363, "tag": "NAME", "value": "Fedorenko" }, { "context": "orenko\");\n Worker director = new Director(\"Ivanovich\");\n Worker hairdresser = new Groomer(\"Selv", "end": 425, "score": 0.9998267889022827, "start": 416, "tag": "NAME", "value": "Ivanovich" }, { "context": "vich\");\n Worker hairdresser = new Groomer(\"Selvertorov\");\n Worker veterinarian = new Veterinarian", "end": 482, "score": 0.9997866749763489, "start": 471, "tag": "NAME", "value": "Selvertorov" }, { "context": ";\n Worker veterinarian = new Veterinarian(\"Petrov\");\n\n Cat.subscribe(feeder);\n Cat.su", "end": 540, "score": 0.9997855424880981, "start": 534, "tag": "NAME", "value": "Petrov" } ]
null
[]
package ZooObservable; import ZooObservable.Animal.Animal; import ZooObservable.Animal.Domestic; import ZooObservable.Animal.Wild; import ZooObservable.Workers.*; public class Main { public static void main(String[] args) { Animal Wolf = new Wild(1 , "Wolfik"); Animal Cat = new Domestic(2, "Marsik"); Worker feeder = new Feeder("Fedorenko"); Worker director = new Director("Ivanovich"); Worker hairdresser = new Groomer("Selvertorov"); Worker veterinarian = new Veterinarian("Petrov"); Cat.subscribe(feeder); Cat.subscribe(director); Cat.subscribe(hairdresser); Cat.subscribe(veterinarian); Wolf.subscribe(hairdresser); Cat.hungry(); Cat.getGroom(); Cat.getIll(); } }
798
0.64411
0.641604
32
23.9375
19.279097
57
false
false
0
0
0
0
0
0
0.65625
false
false
14
97f1512a15049a2c22bb6b0a7c8104d776c29c94
17,128,329,602,608
d7d2f3ea63497da293df4e27d8bae2825e8a9576
/FractalGrammars.java
c3945c2bdeedd8fec056ae7c4b71309ecd0add2b
[]
no_license
hemanthsivaramg/javaFractals
https://github.com/hemanthsivaramg/javaFractals
95b04f93960ab30d35c52033f8bbcb727b433d39
097db42c4925fc2830a8c5a13ecaf8c7a9f53e6f
refs/heads/master
2021-01-17T20:07:15.511000
2016-07-12T22:42:08
2016-07-12T22:42:08
63,197,074
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// FractalGrammars.java // Copied from Section 8.3 of // Ammeraal, L. and K. Zhang (2007). Computer Graphics for Java Programmers, 2nd Edition, // Chichester: John Wiley. import java.awt.*; import java.awt.event.*; public class FractalGrammars extends Frame { public static final double MAX_RADIUS=256; public static void main(String[] args) { if (args.length == 0) System.out.println("Use filename as program argument."); else new FractalGrammars(args[0]); } FractalGrammars(String fileName) { super("Click left or right mouse button to change the level"); addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e){System.exit(0);}}); setSize(800, 600); add("Center", new CvFractalGrammars(fileName)); show(); } } class CvFractalGrammars extends Canvas { String fileName, axiom, strF, strf, strX, strY; int maxX, maxY, level = 1; double xLast, yLast, dir, dirLast, rotation, dirStart, fxStart, fyStart, lengthFract, reductFact; //double maxRadius=256; int radius=(int)FractalGrammars.MAX_RADIUS ; int lineId=0; void error(String str) { System.out.println(str); System.exit(1); } CvFractalGrammars(String fileName) { Input inp = new Input(fileName); if (inp.fails()) error("Cannot open input file."); axiom = inp.readString(); inp.skipRest(); strF = inp.readString(); inp.skipRest(); strf = inp.readString(); inp.skipRest(); strX = inp.readString(); inp.skipRest(); strY = inp.readString(); inp.skipRest(); rotation = inp.readFloat(); inp.skipRest(); dirStart = inp.readFloat(); inp.skipRest(); fxStart = inp.readFloat(); inp.skipRest(); fyStart = inp.readFloat(); inp.skipRest(); lengthFract = inp.readFloat(); inp.skipRest(); reductFact = inp.readFloat(); if (inp.fails()) error("Input file incorrect."); addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent evt) { if ((evt.getModifiers() & InputEvent.BUTTON3_MASK) != 0) { level--; // Right mouse button decreases level if (level < 1) level = 1; } else{ level++; radius/=Math.pow(2, level-1);//decreases radius as level increases }// Left mouse button increases level repaint(); } }); } Graphics g; int iX(double x){return (int)Math.round(x);} int iY(double y){return (int)Math.round(maxY-y);} void drawTo(Graphics g, double x, double y) { lineId++; if(lineId>1) drawingArc(g, x, y); //g.drawLine(iX(xLast), iY(yLast), iX(x), iY(y)); //drawingArc(g, x, y); else g.drawLine(iX(xLast), iY(yLast), iX(x), iY(y)); xLast = x; yLast = y; dirLast = dir; } private void drawingArc(Graphics g, double x, double y) { int positiveDirection=(int)(dir%360)+360; int positiveDirectionLast=(int)(dirLast%360)+360; if(positiveDirection==360) positiveDirection=0; if(positiveDirectionLast==360) positiveDirectionLast=0; switch(positiveDirectionLast) { case 0: if(positiveDirection==90){ g.setColor(Color.white); g.drawLine(iX(xLast)-(radius/2), iY(yLast), iX(xLast), iY(yLast)); g.drawLine(iX(xLast), iY(yLast)-(radius/2), iX(xLast), iY(yLast)); g.setColor(Color.black); g.drawArc(iX(xLast)-radius, iY(yLast)-radius , radius, radius, positiveDirectionLast,-90); g.drawLine(iX(xLast), iY(yLast)-(radius/2), iX(x), iY(y)); } else{ g.setColor(Color.white); g.drawLine(iX(xLast)-(radius/2), iY(yLast), iX(xLast), iY(yLast)); g.drawLine(iX(xLast), iY(yLast)+(radius/2), iX(xLast), iY(yLast)); g.setColor(Color.black); g.drawArc(iX(xLast)-radius,iY(yLast) , radius, radius, positiveDirectionLast,90); g.drawLine(iX(xLast), iY(yLast)+(radius/2), iX(x), iY(y)); } break; case 90: if(positiveDirection==180){ g.setColor(Color.white); g.drawLine(iX(xLast), iY(yLast)+(radius/2), iX(xLast), iY(yLast)); g.drawLine(iX(xLast)-(radius/2), iY(yLast), iX(xLast), iY(yLast)); g.setColor(Color.black); g.drawArc(iX(xLast)-radius,iY(yLast) , radius, radius, positiveDirectionLast,-90); g.drawLine(iX(xLast)-(radius/2), iY(yLast), iX(x), iY(y)); } else{ g.setColor(Color.white); g.drawLine(iX(xLast), iY(yLast)+(radius/2), iX(xLast), iY(yLast)); g.drawLine(iX(xLast)+(radius/2), iY(yLast), iX(xLast), iY(yLast)); g.setColor(Color.black); g.drawArc(iX(xLast),iY(yLast) , radius, radius, positiveDirectionLast,90); g.drawLine(iX(xLast)+(radius/2), iY(yLast), iX(x), iY(y)); } break; case 180: if(positiveDirection==270){ g.setColor(Color.white); g.drawLine(iX(xLast), iY(yLast)+(radius/2), iX(xLast), iY(yLast)); g.drawLine(iX(xLast)+(radius/2), iY(yLast), iX(xLast), iY(yLast)); g.setColor(Color.black); g.drawArc(iX(xLast),iY(yLast) , radius, radius, positiveDirectionLast,-90); g.drawLine(iX(xLast), iY(yLast)+(radius/2), iX(x), iY(y)); } else{ g.setColor(Color.white); g.drawLine(iX(xLast), iY(yLast)-(radius/2), iX(xLast), iY(yLast)); g.drawLine(iX(xLast)+(radius/2), iY(yLast), iX(xLast), iY(yLast)); g.setColor(Color.black); g.drawArc(iX(xLast),iY(yLast)-radius , radius, radius, positiveDirectionLast,90); g.drawLine(iX(xLast), iY(yLast)-(radius/2), iX(x), iY(y)); } break; case 270: if(positiveDirection==0) { g.setColor(Color.white); g.drawLine(iX(xLast), iY(yLast)-(radius/2), iX(xLast), iY(yLast)); g.drawLine(iX(xLast)+(radius/2), iY(yLast), iX(xLast), iY(yLast)); g.setColor(Color.black); g.drawArc(iX(xLast),iY(yLast)-radius , radius, radius, positiveDirectionLast,-90); g.drawLine(iX(xLast)+(radius/2), iY(yLast), iX(x), iY(y)); } else { g.setColor(Color.white); g.drawLine(iX(xLast)-(radius/2), iY(yLast), iX(xLast), iY(yLast)); g.drawLine(iX(xLast), iY(yLast)-(radius/2), iX(xLast), iY(yLast)); g.setColor(Color.black); g.drawArc(iX(xLast)-radius,iY(yLast)-radius , radius, radius, positiveDirectionLast,90); g.drawLine(iX(xLast)-(radius/2), iY(yLast), iX(x), iY(y)); } break; } } void moveTo(Graphics g, double x, double y) { xLast = x; yLast = y; } public void paint(Graphics g) { Dimension d = getSize(); maxX = d.width - 1; maxY = d.height - 1; xLast = fxStart * maxX; yLast = fyStart * maxY; dir = dirStart; // Initial direction in degrees turtleGraphics(g, axiom, level, lengthFract * maxY); lineId=0; radius=(int)FractalGrammars.MAX_RADIUS; } public void turtleGraphics(Graphics g, String instruction, int depth, double len) { double xMark=0, yMark=0, dirMark=0; for (int i=0;i<instruction.length();i++) { char ch = instruction.charAt(i); switch(ch) { case 'F': // Step forward and draw // Start: (xLast, yLast), direction: dir, steplength: len if (depth == 0) { double rad = Math.PI/180 * dir, // Degrees -> radians dx = len * Math.cos(rad), dy = len * Math.sin(rad); drawTo(g, xLast + dx, yLast + dy); } else turtleGraphics(g, strF, depth - 1, reductFact * len); break; case 'f': // Step forward without drawing // Start: (xLast, yLast), direction: dir, steplength: len if (depth == 0) { double rad = Math.PI/180 * dir, // Degrees -> radians dx = len * Math.cos(rad), dy = len * Math.sin(rad); moveTo(g, xLast + dx, yLast + dy); } else turtleGraphics(g, strf, depth - 1, reductFact * len); break; case 'X': if (depth > 0) turtleGraphics(g, strX, depth - 1, reductFact * len); break; case 'Y': if (depth > 0) turtleGraphics(g, strY, depth - 1, reductFact * len); break; case '+': // Turn right dir -= rotation; break; case '-': // Turn left dir += rotation; break; case '[': // Save position and direction xMark = xLast; yMark = yLast; dirMark = dir; break; case ']': // Back to saved position and direction xLast = xMark; yLast = yMark; dir = dirMark; break; } } } }
UTF-8
Java
8,643
java
FractalGrammars.java
Java
[ { "context": "Grammars.java\n\n// Copied from Section 8.3 of\n// Ammeraal, L. and K. Zhang (2007). Computer Graphics for Java P", "end": 72, "score": 0.9995666146278381, "start": 61, "tag": "NAME", "value": "Ammeraal, L" }, { "context": " Copied from Section 8.3 of\n// Ammeraal, L. and K. Zhang (2007). Computer Graphics for Java Programmers, 2", "end": 86, "score": 0.9995619058609009, "start": 78, "tag": "NAME", "value": "K. Zhang" }, { "context": "ava Programmers, 2nd Edition,\n// Chichester: John Wiley.\n\nimport java.awt.*;\nimport java.awt.event.*;\n\n\np", "end": 179, "score": 0.9997642636299133, "start": 169, "tag": "NAME", "value": "John Wiley" } ]
null
[]
// FractalGrammars.java // Copied from Section 8.3 of // <NAME>. and <NAME> (2007). Computer Graphics for Java Programmers, 2nd Edition, // Chichester: <NAME>. import java.awt.*; import java.awt.event.*; public class FractalGrammars extends Frame { public static final double MAX_RADIUS=256; public static void main(String[] args) { if (args.length == 0) System.out.println("Use filename as program argument."); else new FractalGrammars(args[0]); } FractalGrammars(String fileName) { super("Click left or right mouse button to change the level"); addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e){System.exit(0);}}); setSize(800, 600); add("Center", new CvFractalGrammars(fileName)); show(); } } class CvFractalGrammars extends Canvas { String fileName, axiom, strF, strf, strX, strY; int maxX, maxY, level = 1; double xLast, yLast, dir, dirLast, rotation, dirStart, fxStart, fyStart, lengthFract, reductFact; //double maxRadius=256; int radius=(int)FractalGrammars.MAX_RADIUS ; int lineId=0; void error(String str) { System.out.println(str); System.exit(1); } CvFractalGrammars(String fileName) { Input inp = new Input(fileName); if (inp.fails()) error("Cannot open input file."); axiom = inp.readString(); inp.skipRest(); strF = inp.readString(); inp.skipRest(); strf = inp.readString(); inp.skipRest(); strX = inp.readString(); inp.skipRest(); strY = inp.readString(); inp.skipRest(); rotation = inp.readFloat(); inp.skipRest(); dirStart = inp.readFloat(); inp.skipRest(); fxStart = inp.readFloat(); inp.skipRest(); fyStart = inp.readFloat(); inp.skipRest(); lengthFract = inp.readFloat(); inp.skipRest(); reductFact = inp.readFloat(); if (inp.fails()) error("Input file incorrect."); addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent evt) { if ((evt.getModifiers() & InputEvent.BUTTON3_MASK) != 0) { level--; // Right mouse button decreases level if (level < 1) level = 1; } else{ level++; radius/=Math.pow(2, level-1);//decreases radius as level increases }// Left mouse button increases level repaint(); } }); } Graphics g; int iX(double x){return (int)Math.round(x);} int iY(double y){return (int)Math.round(maxY-y);} void drawTo(Graphics g, double x, double y) { lineId++; if(lineId>1) drawingArc(g, x, y); //g.drawLine(iX(xLast), iY(yLast), iX(x), iY(y)); //drawingArc(g, x, y); else g.drawLine(iX(xLast), iY(yLast), iX(x), iY(y)); xLast = x; yLast = y; dirLast = dir; } private void drawingArc(Graphics g, double x, double y) { int positiveDirection=(int)(dir%360)+360; int positiveDirectionLast=(int)(dirLast%360)+360; if(positiveDirection==360) positiveDirection=0; if(positiveDirectionLast==360) positiveDirectionLast=0; switch(positiveDirectionLast) { case 0: if(positiveDirection==90){ g.setColor(Color.white); g.drawLine(iX(xLast)-(radius/2), iY(yLast), iX(xLast), iY(yLast)); g.drawLine(iX(xLast), iY(yLast)-(radius/2), iX(xLast), iY(yLast)); g.setColor(Color.black); g.drawArc(iX(xLast)-radius, iY(yLast)-radius , radius, radius, positiveDirectionLast,-90); g.drawLine(iX(xLast), iY(yLast)-(radius/2), iX(x), iY(y)); } else{ g.setColor(Color.white); g.drawLine(iX(xLast)-(radius/2), iY(yLast), iX(xLast), iY(yLast)); g.drawLine(iX(xLast), iY(yLast)+(radius/2), iX(xLast), iY(yLast)); g.setColor(Color.black); g.drawArc(iX(xLast)-radius,iY(yLast) , radius, radius, positiveDirectionLast,90); g.drawLine(iX(xLast), iY(yLast)+(radius/2), iX(x), iY(y)); } break; case 90: if(positiveDirection==180){ g.setColor(Color.white); g.drawLine(iX(xLast), iY(yLast)+(radius/2), iX(xLast), iY(yLast)); g.drawLine(iX(xLast)-(radius/2), iY(yLast), iX(xLast), iY(yLast)); g.setColor(Color.black); g.drawArc(iX(xLast)-radius,iY(yLast) , radius, radius, positiveDirectionLast,-90); g.drawLine(iX(xLast)-(radius/2), iY(yLast), iX(x), iY(y)); } else{ g.setColor(Color.white); g.drawLine(iX(xLast), iY(yLast)+(radius/2), iX(xLast), iY(yLast)); g.drawLine(iX(xLast)+(radius/2), iY(yLast), iX(xLast), iY(yLast)); g.setColor(Color.black); g.drawArc(iX(xLast),iY(yLast) , radius, radius, positiveDirectionLast,90); g.drawLine(iX(xLast)+(radius/2), iY(yLast), iX(x), iY(y)); } break; case 180: if(positiveDirection==270){ g.setColor(Color.white); g.drawLine(iX(xLast), iY(yLast)+(radius/2), iX(xLast), iY(yLast)); g.drawLine(iX(xLast)+(radius/2), iY(yLast), iX(xLast), iY(yLast)); g.setColor(Color.black); g.drawArc(iX(xLast),iY(yLast) , radius, radius, positiveDirectionLast,-90); g.drawLine(iX(xLast), iY(yLast)+(radius/2), iX(x), iY(y)); } else{ g.setColor(Color.white); g.drawLine(iX(xLast), iY(yLast)-(radius/2), iX(xLast), iY(yLast)); g.drawLine(iX(xLast)+(radius/2), iY(yLast), iX(xLast), iY(yLast)); g.setColor(Color.black); g.drawArc(iX(xLast),iY(yLast)-radius , radius, radius, positiveDirectionLast,90); g.drawLine(iX(xLast), iY(yLast)-(radius/2), iX(x), iY(y)); } break; case 270: if(positiveDirection==0) { g.setColor(Color.white); g.drawLine(iX(xLast), iY(yLast)-(radius/2), iX(xLast), iY(yLast)); g.drawLine(iX(xLast)+(radius/2), iY(yLast), iX(xLast), iY(yLast)); g.setColor(Color.black); g.drawArc(iX(xLast),iY(yLast)-radius , radius, radius, positiveDirectionLast,-90); g.drawLine(iX(xLast)+(radius/2), iY(yLast), iX(x), iY(y)); } else { g.setColor(Color.white); g.drawLine(iX(xLast)-(radius/2), iY(yLast), iX(xLast), iY(yLast)); g.drawLine(iX(xLast), iY(yLast)-(radius/2), iX(xLast), iY(yLast)); g.setColor(Color.black); g.drawArc(iX(xLast)-radius,iY(yLast)-radius , radius, radius, positiveDirectionLast,90); g.drawLine(iX(xLast)-(radius/2), iY(yLast), iX(x), iY(y)); } break; } } void moveTo(Graphics g, double x, double y) { xLast = x; yLast = y; } public void paint(Graphics g) { Dimension d = getSize(); maxX = d.width - 1; maxY = d.height - 1; xLast = fxStart * maxX; yLast = fyStart * maxY; dir = dirStart; // Initial direction in degrees turtleGraphics(g, axiom, level, lengthFract * maxY); lineId=0; radius=(int)FractalGrammars.MAX_RADIUS; } public void turtleGraphics(Graphics g, String instruction, int depth, double len) { double xMark=0, yMark=0, dirMark=0; for (int i=0;i<instruction.length();i++) { char ch = instruction.charAt(i); switch(ch) { case 'F': // Step forward and draw // Start: (xLast, yLast), direction: dir, steplength: len if (depth == 0) { double rad = Math.PI/180 * dir, // Degrees -> radians dx = len * Math.cos(rad), dy = len * Math.sin(rad); drawTo(g, xLast + dx, yLast + dy); } else turtleGraphics(g, strF, depth - 1, reductFact * len); break; case 'f': // Step forward without drawing // Start: (xLast, yLast), direction: dir, steplength: len if (depth == 0) { double rad = Math.PI/180 * dir, // Degrees -> radians dx = len * Math.cos(rad), dy = len * Math.sin(rad); moveTo(g, xLast + dx, yLast + dy); } else turtleGraphics(g, strf, depth - 1, reductFact * len); break; case 'X': if (depth > 0) turtleGraphics(g, strX, depth - 1, reductFact * len); break; case 'Y': if (depth > 0) turtleGraphics(g, strY, depth - 1, reductFact * len); break; case '+': // Turn right dir -= rotation; break; case '-': // Turn left dir += rotation; break; case '[': // Save position and direction xMark = xLast; yMark = yLast; dirMark = dir; break; case ']': // Back to saved position and direction xLast = xMark; yLast = yMark; dir = dirMark; break; } } } }
8,632
0.584982
0.569825
256
32.761719
24.86137
94
false
false
0
0
0
0
0
0
2.660156
false
false
14
fc68838633f4d34d2d3bb1d57c07fddc618aceca
6,579,889,935,732
8fc6fbc0bf858fcc815007a3aa42b8a189953b9f
/test/com/raphael/lc/p567/CheckInclusionTest.java
e27d508480295c5f96d9e69f8d43e6495fa332c2
[]
no_license
wangchao0502/lc-weekly-contest
https://github.com/wangchao0502/lc-weekly-contest
79f01eadb118a92c79006285cb320b4bf316c1f9
0ebcd48e816d257ed454e489e9166fbd732ff528
refs/heads/main
2023-05-07T06:32:10.541000
2021-05-30T02:30:05
2021-05-30T02:30:05
327,791,058
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.raphael.lc.p567; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * @author raphael * @date 2021-02-10 10:08:45 */ class CheckInclusionTest { private final CheckInclusion solution = new CheckInclusion(); @Test void t1() { Assertions.assertTrue(solution.checkInclusion("ab", "eidbaooo")); } @Test void t2() { Assertions.assertFalse(solution.checkInclusion("ab", "eidboaoo")); } }
UTF-8
Java
474
java
CheckInclusionTest.java
Java
[ { "context": "import org.junit.jupiter.api.Test;\n\n/**\n * @author raphael\n * @date 2021-02-10 10:08:45\n */\nclass CheckInclu", "end": 129, "score": 0.9971358180046082, "start": 122, "tag": "USERNAME", "value": "raphael" } ]
null
[]
package com.raphael.lc.p567; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * @author raphael * @date 2021-02-10 10:08:45 */ class CheckInclusionTest { private final CheckInclusion solution = new CheckInclusion(); @Test void t1() { Assertions.assertTrue(solution.checkInclusion("ab", "eidbaooo")); } @Test void t2() { Assertions.assertFalse(solution.checkInclusion("ab", "eidboaoo")); } }
474
0.664557
0.624473
23
19.608696
23.023125
74
false
false
0
0
0
0
0
0
0.347826
false
false
14
56a041f7de134c3fe0ff2bee6af0578b6794a357
22,333,829,987,789
6c69998676e9df8be55e28f6d63942b9f7cef913
/src/com/insigma/siis/local/pagemodel/amain/CYMINGDANPageModel.java
44b96a5431df727338b0204043ffeee71fd8f0ae
[]
no_license
HuangHL92/ZHGBSYS
https://github.com/HuangHL92/ZHGBSYS
9dea4de5931edf5c93a6fbcf6a4655c020395554
f2ff875eddd569dca52930d09ebc22c4dcb47baf
refs/heads/master
2023-08-04T04:37:08.995000
2021-09-15T07:35:53
2021-09-15T07:35:53
406,219,162
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.insigma.siis.local.pagemodel.amain; import java.io.BufferedReader; import java.io.IOException; import java.sql.Clob; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import com.insigma.odin.framework.AppException; import com.insigma.odin.framework.persistence.HBSession; import com.insigma.odin.framework.persistence.HBUtil; import com.insigma.odin.framework.privilege.PrivilegeManager; import com.insigma.odin.framework.privilege.vo.UserVO; import com.insigma.odin.framework.radow.PageModel; import com.insigma.odin.framework.radow.RadowException; import com.insigma.odin.framework.radow.annotation.AutoNoMask; import com.insigma.odin.framework.radow.annotation.GridDataRange; import com.insigma.odin.framework.radow.annotation.NoRequiredValidate; import com.insigma.odin.framework.radow.annotation.PageEvent; import com.insigma.odin.framework.radow.annotation.Synchronous; import com.insigma.odin.framework.radow.annotation.Transaction; import com.insigma.odin.framework.radow.annotation.GridDataRange.GridData; import com.insigma.odin.framework.radow.element.Grid; import com.insigma.odin.framework.radow.event.EventRtnType; public class CYMINGDANPageModel extends PageModel{ @Override public int doInit() throws RadowException { return EventRtnType.NORMAL_SUCCESS; } }
UTF-8
Java
1,336
java
CYMINGDANPageModel.java
Java
[]
null
[]
package com.insigma.siis.local.pagemodel.amain; import java.io.BufferedReader; import java.io.IOException; import java.sql.Clob; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import com.insigma.odin.framework.AppException; import com.insigma.odin.framework.persistence.HBSession; import com.insigma.odin.framework.persistence.HBUtil; import com.insigma.odin.framework.privilege.PrivilegeManager; import com.insigma.odin.framework.privilege.vo.UserVO; import com.insigma.odin.framework.radow.PageModel; import com.insigma.odin.framework.radow.RadowException; import com.insigma.odin.framework.radow.annotation.AutoNoMask; import com.insigma.odin.framework.radow.annotation.GridDataRange; import com.insigma.odin.framework.radow.annotation.NoRequiredValidate; import com.insigma.odin.framework.radow.annotation.PageEvent; import com.insigma.odin.framework.radow.annotation.Synchronous; import com.insigma.odin.framework.radow.annotation.Transaction; import com.insigma.odin.framework.radow.annotation.GridDataRange.GridData; import com.insigma.odin.framework.radow.element.Grid; import com.insigma.odin.framework.radow.event.EventRtnType; public class CYMINGDANPageModel extends PageModel{ @Override public int doInit() throws RadowException { return EventRtnType.NORMAL_SUCCESS; } }
1,336
0.833084
0.833084
39
33.256409
25.682198
74
false
false
0
0
0
0
0
0
0.897436
false
false
14
1be030067c4bea0a5127b51890508f5e9245776c
33,500,744,909,406
e78ddca48e73361ba0c25bac9a514aa502faba92
/phase1/Bank System/src/main/java/ATM/ItAccount.java
7bc4bc6ad345a666567b1abae008b18c6cea70de
[]
no_license
Kevintjy/Java-beginner
https://github.com/Kevintjy/Java-beginner
8c25a7e22a694ca017e13dbd265f0f93159230a9
c9ba437d0dc9f6c31a56cc8484b333580d3495be
refs/heads/master
2020-04-17T01:13:58.988000
2019-10-04T02:45:37
2019-10-04T02:45:37
166,082,677
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package main.java.ATM; import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; import java.util.NoSuchElementException; public class ItAccount implements Iterable<Account>, Serializable { // the list storing all current Accounts of a User private ArrayList<Account> accounts = new ArrayList<>(); Account defaultAccount = null; /* Add Account to the ArrayList. */ public void addAccounts(Account a) { accounts.add(a); } public void removeAccount(Account a){accounts.remove(a);} /* Get total balance of a user's accounts. */ public double getTotalBalance() { double total = 0; for (Account a: this){ total += a.getBalance(); } return total; } public ArrayList<Account> getAccounts() { return accounts; } @Override public Iterator<Account> iterator() { return new accountIterator(); } private class accountIterator implements Iterator<Account> { private int next; @Override public boolean hasNext() { return next < accounts.size(); } @Override public Account next() { if (hasNext()) { return accounts.get(next++); } throw new NoSuchElementException(); } } }
UTF-8
Java
1,377
java
ItAccount.java
Java
[]
null
[]
package main.java.ATM; import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; import java.util.NoSuchElementException; public class ItAccount implements Iterable<Account>, Serializable { // the list storing all current Accounts of a User private ArrayList<Account> accounts = new ArrayList<>(); Account defaultAccount = null; /* Add Account to the ArrayList. */ public void addAccounts(Account a) { accounts.add(a); } public void removeAccount(Account a){accounts.remove(a);} /* Get total balance of a user's accounts. */ public double getTotalBalance() { double total = 0; for (Account a: this){ total += a.getBalance(); } return total; } public ArrayList<Account> getAccounts() { return accounts; } @Override public Iterator<Account> iterator() { return new accountIterator(); } private class accountIterator implements Iterator<Account> { private int next; @Override public boolean hasNext() { return next < accounts.size(); } @Override public Account next() { if (hasNext()) { return accounts.get(next++); } throw new NoSuchElementException(); } } }
1,377
0.594771
0.594045
68
19.25
19.303593
67
false
false
0
0
0
0
0
0
0.279412
false
false
14
0d32df7f6089fac3dac0572a1781c3ccf8b610e5
23,940,147,759,817
94c9b76dfd2599eabebf473afa5b1a72d4591284
/src/NewExceptions/EncomendaInexistenteException.java
f61f435df9f730cfd00cde95fa757d2be97907f4
[]
no_license
80Hefner/POO-Project
https://github.com/80Hefner/POO-Project
e0dece029bb057aab7c0fca02a6c9f1211afee55
73b8c042a059fcc3ebba8d1afe954fa077ae75d1
refs/heads/master
2023-04-01T00:08:39.657000
2021-04-02T05:50:42
2021-04-02T05:50:42
258,696,098
2
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package NewExceptions; /** * Classe com Uma Excepetion de Encomenda Não existir */ public class EncomendaInexistenteException extends Exception { /** * Função que emite a Exception de que Encomenda Não Existe */ public EncomendaInexistenteException() { super(); } /** * Função que transforma a Exception feita numa String * @return String resultante da função */ public String toString() { return "Encomenda Inexistente"; } }
UTF-8
Java
522
java
EncomendaInexistenteException.java
Java
[]
null
[]
package NewExceptions; /** * Classe com Uma Excepetion de Encomenda Não existir */ public class EncomendaInexistenteException extends Exception { /** * Função que emite a Exception de que Encomenda Não Existe */ public EncomendaInexistenteException() { super(); } /** * Função que transforma a Exception feita numa String * @return String resultante da função */ public String toString() { return "Encomenda Inexistente"; } }
522
0.634241
0.634241
24
20.375
21.992067
63
false
false
0
0
0
0
0
0
0.125
false
false
14
8ad2797d471d73fade5e76907eefc7844bd4ced5
32,203,664,834,394
33c5d534439d38712c70a878c83ff06745eb27cc
/app/src/main/java/pro/book/ar/Activity/LoginActivity.java
679bdd9fd9574110cf249ffeb299ee764be07c99
[]
no_license
sobhan-zp/bookpro
https://github.com/sobhan-zp/bookpro
ecce576aa97ceedea60eefaefb832b47241b50f6
8d0bd576f85be7b18b27bf5b9e2f33a4818e9796
refs/heads/master
2020-03-22T09:26:24.939000
2018-08-16T06:29:49
2018-08-16T06:29:49
139,837,277
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pro.book.ar.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.annotation.IdRes; import android.text.Editable; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; import com.android.volley.toolbox.JsonArrayRequest; import com.google.android.gms.common.api.GoogleApiClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; import pro.book.ar.Classes.BaseToolBarActivity; import pro.book.ar.Classes.ImageUtil; import pro.book.ar.Classes.MyCountDownTimer; import pro.book.ar.Model.Target; import pro.book.ar.Network.AppController; import pro.book.ar.R; import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper; import za.co.riggaroo.materialhelptutorial.TutorialItem; import za.co.riggaroo.materialhelptutorial.tutorial.MaterialTutorialActivity; public class LoginActivity extends BaseToolBarActivity { private static final int REQUEST_CODE = 1234; SharedPreferences prefs; @BindView(R.id.password_field) EditText passwordField; @BindView(R.id.t9_key_1) TextView t9Key1; @BindView(R.id.t9_key_2) TextView t9Key2; @BindView(R.id.t9_key_3) TextView t9Key3; @BindView(R.id.t9_key_4) TextView t9Key4; @BindView(R.id.t9_key_5) TextView t9Key5; @BindView(R.id.t9_key_6) TextView t9Key6; @BindView(R.id.t9_key_7) TextView t9Key7; @BindView(R.id.t9_key_8) TextView t9Key8; @BindView(R.id.t9_key_9) TextView t9Key9; @BindView(R.id.t9_key_clear) TextView t9KeyClear; @BindView(R.id.t9_key_0) TextView t9Key0; @BindView(R.id.t9_key_backspace) TextView t9KeyBackspace; @BindView(R.id.tv_resms_login) TextView tvResmsLogin; @BindView(R.id.tv_changeNum_login) TextView tvChangeNumLogin; private GoogleApiClient client; @Override protected int getLayoutId() { return R.layout.activity_login; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); ButterKnife.bind(this); AppController.context = this; loadTarget(); //swipe startActivity(LockscreenActivity.class); //Send Verify Code tvResmsLogin.setEnabled(false); } public void onCountDownTimerFinishEvent() { this.tvResmsLogin.setEnabled(true); } public void onCountDownTimerTickEvent(long millisUntilFinished) { long leftSeconds = millisUntilFinished / 1000; String sendButtonText = "ثانیه " + (leftSeconds -1) ; if((leftSeconds -1 )==0) { sendButtonText = "ارسال مجدد کد"; tvResmsLogin.setEnabled(true); LockscreenActivity.myCountDownTimer.onFinish(); } this.tvResmsLogin.setText(sendButtonText); } public void tvOnClickLogin(View v) { switch (v.getId()) { case R.id.t9_key_0: passwordField.append("0"); break; case R.id.t9_key_1: passwordField.append("1"); break; case R.id.t9_key_2: passwordField.append("2"); break; case R.id.t9_key_3: passwordField.append("3"); break; case R.id.t9_key_4: passwordField.append("4"); break; case R.id.t9_key_5: passwordField.append("5"); break; case R.id.t9_key_6: passwordField.append("6"); break; case R.id.t9_key_7: passwordField.append("7"); break; case R.id.t9_key_8: passwordField.append("8"); break; case R.id.t9_key_9: passwordField.append("9"); break; case R.id.t9_key_clear: { // handle clear button passwordField.setText(null); } break; case R.id.t9_key_backspace: { // handle backspace button // delete one character Editable editable = passwordField.getText(); int charCount = editable.length(); if (charCount > 0) { editable.delete(charCount - 1, charCount); } } break; case R.id.tv_resms_login:{ LockscreenActivity.myCountDownTimer = new MyCountDownTimer(60 * 1000, 1000); LockscreenActivity.myCountDownTimer.setSourceActivity((LoginActivity) AppController.context); LockscreenActivity.myCountDownTimer.start(); } break; case R.id.tv_changeNum_login:{ Intent i = new Intent(LoginActivity.this , LockscreenActivity.class); startActivity(i); } break; } if (passwordField.getText().toString().equals("00000000")) { startActivity(new Intent(LoginActivity.this, MainActivity.class)); } } // Swipe public void startActivity(Class<?> clazz) { startActivity(new Intent(LoginActivity.this, clazz)); } protected <T extends View> T $(@IdRes int id) { return (T) super.findViewById(id); } @Override protected void attachBaseContext(Context newBase) { super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase)); } private void loadTarget() { JsonArrayRequest req = new JsonArrayRequest(AppController.URL_TARGET, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { //Log.e("TAG---------OK", response.toString()); try { for (int i = 0; i < response.length(); i++) { JSONObject object = response.getJSONObject(i); String url = object.getString("url"); Target target = new Target( String.valueOf(i), url.substring( url.lastIndexOf('/')+1, url.length() ), object.getString("url"), object.getString("value") ); new ImageUtil(LoginActivity.this, target.getUrl(), target.getName()); AppController.TARGET.add(target); } AppController.TARGET_NUMBERS = response.length(); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d("TAG------------Error", "Error: " + error.getMessage()); } }); req.setShouldCache(false); AppController.getInstance().addToRequestQueue(req, "loadTarget"); } }
UTF-8
Java
7,872
java
LoginActivity.java
Java
[ { "context": "Controller;\nimport pro.book.ar.R;\nimport uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;\nimport", "end": 1096, "score": 0.5303115844726562, "start": 1094, "tag": "USERNAME", "value": "is" } ]
null
[]
package pro.book.ar.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.annotation.IdRes; import android.text.Editable; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; import com.android.volley.toolbox.JsonArrayRequest; import com.google.android.gms.common.api.GoogleApiClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; import pro.book.ar.Classes.BaseToolBarActivity; import pro.book.ar.Classes.ImageUtil; import pro.book.ar.Classes.MyCountDownTimer; import pro.book.ar.Model.Target; import pro.book.ar.Network.AppController; import pro.book.ar.R; import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper; import za.co.riggaroo.materialhelptutorial.TutorialItem; import za.co.riggaroo.materialhelptutorial.tutorial.MaterialTutorialActivity; public class LoginActivity extends BaseToolBarActivity { private static final int REQUEST_CODE = 1234; SharedPreferences prefs; @BindView(R.id.password_field) EditText passwordField; @BindView(R.id.t9_key_1) TextView t9Key1; @BindView(R.id.t9_key_2) TextView t9Key2; @BindView(R.id.t9_key_3) TextView t9Key3; @BindView(R.id.t9_key_4) TextView t9Key4; @BindView(R.id.t9_key_5) TextView t9Key5; @BindView(R.id.t9_key_6) TextView t9Key6; @BindView(R.id.t9_key_7) TextView t9Key7; @BindView(R.id.t9_key_8) TextView t9Key8; @BindView(R.id.t9_key_9) TextView t9Key9; @BindView(R.id.t9_key_clear) TextView t9KeyClear; @BindView(R.id.t9_key_0) TextView t9Key0; @BindView(R.id.t9_key_backspace) TextView t9KeyBackspace; @BindView(R.id.tv_resms_login) TextView tvResmsLogin; @BindView(R.id.tv_changeNum_login) TextView tvChangeNumLogin; private GoogleApiClient client; @Override protected int getLayoutId() { return R.layout.activity_login; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); ButterKnife.bind(this); AppController.context = this; loadTarget(); //swipe startActivity(LockscreenActivity.class); //Send Verify Code tvResmsLogin.setEnabled(false); } public void onCountDownTimerFinishEvent() { this.tvResmsLogin.setEnabled(true); } public void onCountDownTimerTickEvent(long millisUntilFinished) { long leftSeconds = millisUntilFinished / 1000; String sendButtonText = "ثانیه " + (leftSeconds -1) ; if((leftSeconds -1 )==0) { sendButtonText = "ارسال مجدد کد"; tvResmsLogin.setEnabled(true); LockscreenActivity.myCountDownTimer.onFinish(); } this.tvResmsLogin.setText(sendButtonText); } public void tvOnClickLogin(View v) { switch (v.getId()) { case R.id.t9_key_0: passwordField.append("0"); break; case R.id.t9_key_1: passwordField.append("1"); break; case R.id.t9_key_2: passwordField.append("2"); break; case R.id.t9_key_3: passwordField.append("3"); break; case R.id.t9_key_4: passwordField.append("4"); break; case R.id.t9_key_5: passwordField.append("5"); break; case R.id.t9_key_6: passwordField.append("6"); break; case R.id.t9_key_7: passwordField.append("7"); break; case R.id.t9_key_8: passwordField.append("8"); break; case R.id.t9_key_9: passwordField.append("9"); break; case R.id.t9_key_clear: { // handle clear button passwordField.setText(null); } break; case R.id.t9_key_backspace: { // handle backspace button // delete one character Editable editable = passwordField.getText(); int charCount = editable.length(); if (charCount > 0) { editable.delete(charCount - 1, charCount); } } break; case R.id.tv_resms_login:{ LockscreenActivity.myCountDownTimer = new MyCountDownTimer(60 * 1000, 1000); LockscreenActivity.myCountDownTimer.setSourceActivity((LoginActivity) AppController.context); LockscreenActivity.myCountDownTimer.start(); } break; case R.id.tv_changeNum_login:{ Intent i = new Intent(LoginActivity.this , LockscreenActivity.class); startActivity(i); } break; } if (passwordField.getText().toString().equals("00000000")) { startActivity(new Intent(LoginActivity.this, MainActivity.class)); } } // Swipe public void startActivity(Class<?> clazz) { startActivity(new Intent(LoginActivity.this, clazz)); } protected <T extends View> T $(@IdRes int id) { return (T) super.findViewById(id); } @Override protected void attachBaseContext(Context newBase) { super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase)); } private void loadTarget() { JsonArrayRequest req = new JsonArrayRequest(AppController.URL_TARGET, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { //Log.e("TAG---------OK", response.toString()); try { for (int i = 0; i < response.length(); i++) { JSONObject object = response.getJSONObject(i); String url = object.getString("url"); Target target = new Target( String.valueOf(i), url.substring( url.lastIndexOf('/')+1, url.length() ), object.getString("url"), object.getString("value") ); new ImageUtil(LoginActivity.this, target.getUrl(), target.getName()); AppController.TARGET.add(target); } AppController.TARGET_NUMBERS = response.length(); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d("TAG------------Error", "Error: " + error.getMessage()); } }); req.setShouldCache(false); AppController.getInstance().addToRequestQueue(req, "loadTarget"); } }
7,872
0.576884
0.563009
249
30.550201
23.561388
117
false
false
0
0
0
0
0
0
0.546185
false
false
14
2e71cd0278caa55182b7794a32e89331cdd6f053
3,917,010,213,803
0c30da0583a79b010eb594b6a8c995cf905184de
/spath/rup/rusrc/ExportToHTML.java
80944b54d7bcaacd01184e35e55fbf1e2e1d6177
[]
no_license
calvinjgs/rank-up
https://github.com/calvinjgs/rank-up
94e167318ed8b89ac37b97d0e59db954812339c4
ddf62dd674f8f9c7a8d3f552a1d6b5b51d9b6caf
refs/heads/master
2020-03-29T14:30:16.273000
2018-09-26T01:22:47
2018-09-26T01:22:47
150,020,981
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package rup.rusrc; import java.util.*; import java.io.*; import rup.datasrc.*; import rup.tools.*; public class ExportToHTML { public static boolean includeSpecialDescriptions; public static void exportArmy(ArmyElement[][] army, ArmyRequirements armyReqs) { String fn = army[0][0].force().name() + " " + armyReqs.pointsMax(); fn = RUData.ARMY_LIST_PATH + RWFile.fs + fn + ".htm"; exportArmy(army, armyReqs, fn); } public static void exportArmy(ArmyElement[][] army, ArmyRequirements armyReqs, String filename) { String a = "<html>"; //head a += "<head>"; //browser title a += "<title>" + army[0][0].force().name() + " " + armyReqs.pointsMax() + " Point Army List — RankUp</title>"; a += RWFile.nl; //style stuff a += "<style>" + RWFile.nl; a += "* {" + RWFile.nl; a += "\tfont-family: verdana;" + RWFile.nl; a += "\tfont-size: 12px;" + RWFile.nl; a += "}" + RWFile.nl; a += ".stat {" + RWFile.nl; a += "\ttext-align: center;" + RWFile.nl; a += "\twidth: 5%;" + RWFile.nl; a += "}" + RWFile.nl; a += ".stathead {" + RWFile.nl; a += "\ttext-align: center;" + RWFile.nl; a += "\tfont-weight: bold;" + RWFile.nl; a += "\twidth: 10%;" + RWFile.nl; a += "}" + RWFile.nl; a += ".namehead {" + RWFile.nl; a += "\tbackground-color: #dddddd;" + RWFile.nl; a += "\ttext-align: center;" + RWFile.nl; a += "\tfont-weight: bold;" + RWFile.nl; a += "}" + RWFile.nl; a += "h1 {" + RWFile.nl; a += "\tfont-size: 16px;" + RWFile.nl; a += "\ttext-align: center;" + RWFile.nl; a += "\tfont-weight: bold;" + RWFile.nl; a += "}" + RWFile.nl; a += "</style>" + RWFile.nl; a += "</head>" + RWFile.nl; //body a += "<body>" + RWFile.nl; //page title a += "<h1>" + army[0][0].force().name() + " " + armyReqs.pointsMax() + " Point Army List</h1>" + RWFile.nl; a += "<br><br><br>" + RWFile.nl; //unit stat tables for (int i = 0; i < army.length; i++) { for (int j = 0; j < army[i].length; j++) { if (army[i][j] instanceof SelectedUnit) { SelectedUnit su = (SelectedUnit) army[i][j]; a += unitTable(su); } else if (army[i][j] instanceof Formation) { Formation f = (Formation) army[i][j]; a += formationTable(f); } if (!((i == army.length - 1) && (j == army[i].length - 1))) a += "<br><br>" + RWFile.nl; } } a += RWFile.nl; if (includeSpecialDescriptions) a += specialDescriptions(army); a += "</body>"; a += "</html>"; RWFile.printToFile(filename, a); } public static String unitTable(SelectedUnit su) { String s = "<table cellSpacing=\"0\" cellPadding=\"2\" width=\"100%\" border=\"1\" style=\"display: inline-table; page-break-after: avoid; page-break-before: auto;\">"; s += "<tr>"; s += "<th class=\"namehead\" colspan=\"3\">" + su.name() + "</td>"; s += "<th class=\"namehead\" colspan=\"3\">" + capitalize(su.type().toString()) + "</td>"; s += "<th class=\"namehead\" colspan=\"3\">" + su.sizeName() + "</td>"; s += "</tr>"; s += "<tr>"; s += "<th class=\"stathead\">Sp</td>"; s += "<th class=\"stathead\">Me</td>"; s += "<th class=\"stathead\">Ra</td>"; s += "<th class=\"stathead\">De</td>"; s += "<th class=\"stathead\">Att</td>"; s += "<th class=\"stathead\" colspan=\"2\">Ne</td>"; s += "<th class=\"stathead\">Pts</td>"; s += "</tr>"; s += "<tr>"; s += "<th class=\"stat\">" + RUData.displayStat(su.sp()) + "</td>"; s += "<th class=\"stat\">" + RUData.displayStatPlus(su.me()) + "</td>"; s += "<th class=\"stat\">" + RUData.displayStatPlus(su.ra()) + "</td>"; s += "<th class=\"stat\">" + RUData.displayStatPlus(su.de()) + "</td>"; s += "<th class=\"stat\">" + RUData.displayStat(su.att()) + "</td>"; s += "<th class=\"stat\">" + RUData.displayStat(su.neW()) + "</td>"; s += "<th class=\"stat\">" + RUData.displayStat(su.neR()) + "</td>"; s += "<th class=\"stat\">" + RUData.displayStat(su.pts()) + "</td>"; s += "</tr>"; s += "<tr>"; s += "<td class=\"stathead\"> Specials:</td>"; s += "<td colspan=\"7\">"; if (su.specials().length > 0) { for (int i = 0; i < su.specials().length - 1; i++) { s += su.specials(i).toStringNoPkg(); s += ", "; } s += su.specials(su.specials().length - 1).toStringNoPkg(); } s += "</td>"; s += "</tr>"; s += "</table>"; return s; } public static String formationTable(Formation f) { String s = "<table cellSpacing=\"0\" cellPadding=\"2\" width=\"100%\" border=\"1\" style=\"display: inline-table; page-break-after: avoid; page-break-before: auto;\">"; s += "<tr>"; s += "<th class=\"namehead\" colspan=\"1\">" + f.name() + "</td>"; s += "<th class=\"namehead\" colspan=\"1\">" + "Formation" + "</td>"; s += "</tr>"; s += "<tr>"; s += "<td colspan=\"1\" rowspan=\"2\">"; s += f.description(); s += "</td>"; s += "<th class=\"stathead\">Pts</td>"; s += "</tr>"; s += "<tr>"; s += "<th class=\"stat\">" + RUData.displayStat(f.pts()) + "</td>"; s += "</tr>"; s += "</table>"; return s; } public static String capitalize(String s) { String[] sarr = s.split("\\b"); s = ""; for (int i = 0; i < sarr.length; i++) { char[] charr = sarr[i].toCharArray(); if (charr[0] >= 'a' && charr[0] <= 'z') charr[0] = (char) (('A' - 'a') + charr[0]); s += s.copyValueOf(charr); } return s; } public static String specialDescriptions(ArmyElement[][] army) { String s = ""; //gather all specials used in this army. DynamicArray<Special> includedSpecs = new DynamicArray(new Special[0]); for (int i = 0; i < army.length; i++) { for (int j = 0; j < army[i].length; j++) { if (!(army[i][j] instanceof SelectedUnit)) continue; SelectedUnit unit = (SelectedUnit) army[i][j]; for (int k = 0; k < unit.specials().length; k++) { Special spec = unit.specials(k).special(RUData.WORKINGPACKAGE.specials()); boolean specIn = false; for (int m = 0; m < includedSpecs.size(); m++) { if (spec.equals(includedSpecs.storage(m))) specIn = true; } if (!specIn) includedSpecs.add(spec); } } } //print descriptions s += "<br><br><br>"; for (int m = 0; m < includedSpecs.size(); m++) { Special spec = includedSpecs.storage(m); s += "<b>" + spec.name() + "</b><br>" + RWFile.nl; s += spec.description(); if (m != includedSpecs.size() - 1) s += "<br><br>" + RWFile.nl; } return s; } public static String pageBreak() { return ""; } }
WINDOWS-1252
Java
6,409
java
ExportToHTML.java
Java
[]
null
[]
package rup.rusrc; import java.util.*; import java.io.*; import rup.datasrc.*; import rup.tools.*; public class ExportToHTML { public static boolean includeSpecialDescriptions; public static void exportArmy(ArmyElement[][] army, ArmyRequirements armyReqs) { String fn = army[0][0].force().name() + " " + armyReqs.pointsMax(); fn = RUData.ARMY_LIST_PATH + RWFile.fs + fn + ".htm"; exportArmy(army, armyReqs, fn); } public static void exportArmy(ArmyElement[][] army, ArmyRequirements armyReqs, String filename) { String a = "<html>"; //head a += "<head>"; //browser title a += "<title>" + army[0][0].force().name() + " " + armyReqs.pointsMax() + " Point Army List — RankUp</title>"; a += RWFile.nl; //style stuff a += "<style>" + RWFile.nl; a += "* {" + RWFile.nl; a += "\tfont-family: verdana;" + RWFile.nl; a += "\tfont-size: 12px;" + RWFile.nl; a += "}" + RWFile.nl; a += ".stat {" + RWFile.nl; a += "\ttext-align: center;" + RWFile.nl; a += "\twidth: 5%;" + RWFile.nl; a += "}" + RWFile.nl; a += ".stathead {" + RWFile.nl; a += "\ttext-align: center;" + RWFile.nl; a += "\tfont-weight: bold;" + RWFile.nl; a += "\twidth: 10%;" + RWFile.nl; a += "}" + RWFile.nl; a += ".namehead {" + RWFile.nl; a += "\tbackground-color: #dddddd;" + RWFile.nl; a += "\ttext-align: center;" + RWFile.nl; a += "\tfont-weight: bold;" + RWFile.nl; a += "}" + RWFile.nl; a += "h1 {" + RWFile.nl; a += "\tfont-size: 16px;" + RWFile.nl; a += "\ttext-align: center;" + RWFile.nl; a += "\tfont-weight: bold;" + RWFile.nl; a += "}" + RWFile.nl; a += "</style>" + RWFile.nl; a += "</head>" + RWFile.nl; //body a += "<body>" + RWFile.nl; //page title a += "<h1>" + army[0][0].force().name() + " " + armyReqs.pointsMax() + " Point Army List</h1>" + RWFile.nl; a += "<br><br><br>" + RWFile.nl; //unit stat tables for (int i = 0; i < army.length; i++) { for (int j = 0; j < army[i].length; j++) { if (army[i][j] instanceof SelectedUnit) { SelectedUnit su = (SelectedUnit) army[i][j]; a += unitTable(su); } else if (army[i][j] instanceof Formation) { Formation f = (Formation) army[i][j]; a += formationTable(f); } if (!((i == army.length - 1) && (j == army[i].length - 1))) a += "<br><br>" + RWFile.nl; } } a += RWFile.nl; if (includeSpecialDescriptions) a += specialDescriptions(army); a += "</body>"; a += "</html>"; RWFile.printToFile(filename, a); } public static String unitTable(SelectedUnit su) { String s = "<table cellSpacing=\"0\" cellPadding=\"2\" width=\"100%\" border=\"1\" style=\"display: inline-table; page-break-after: avoid; page-break-before: auto;\">"; s += "<tr>"; s += "<th class=\"namehead\" colspan=\"3\">" + su.name() + "</td>"; s += "<th class=\"namehead\" colspan=\"3\">" + capitalize(su.type().toString()) + "</td>"; s += "<th class=\"namehead\" colspan=\"3\">" + su.sizeName() + "</td>"; s += "</tr>"; s += "<tr>"; s += "<th class=\"stathead\">Sp</td>"; s += "<th class=\"stathead\">Me</td>"; s += "<th class=\"stathead\">Ra</td>"; s += "<th class=\"stathead\">De</td>"; s += "<th class=\"stathead\">Att</td>"; s += "<th class=\"stathead\" colspan=\"2\">Ne</td>"; s += "<th class=\"stathead\">Pts</td>"; s += "</tr>"; s += "<tr>"; s += "<th class=\"stat\">" + RUData.displayStat(su.sp()) + "</td>"; s += "<th class=\"stat\">" + RUData.displayStatPlus(su.me()) + "</td>"; s += "<th class=\"stat\">" + RUData.displayStatPlus(su.ra()) + "</td>"; s += "<th class=\"stat\">" + RUData.displayStatPlus(su.de()) + "</td>"; s += "<th class=\"stat\">" + RUData.displayStat(su.att()) + "</td>"; s += "<th class=\"stat\">" + RUData.displayStat(su.neW()) + "</td>"; s += "<th class=\"stat\">" + RUData.displayStat(su.neR()) + "</td>"; s += "<th class=\"stat\">" + RUData.displayStat(su.pts()) + "</td>"; s += "</tr>"; s += "<tr>"; s += "<td class=\"stathead\"> Specials:</td>"; s += "<td colspan=\"7\">"; if (su.specials().length > 0) { for (int i = 0; i < su.specials().length - 1; i++) { s += su.specials(i).toStringNoPkg(); s += ", "; } s += su.specials(su.specials().length - 1).toStringNoPkg(); } s += "</td>"; s += "</tr>"; s += "</table>"; return s; } public static String formationTable(Formation f) { String s = "<table cellSpacing=\"0\" cellPadding=\"2\" width=\"100%\" border=\"1\" style=\"display: inline-table; page-break-after: avoid; page-break-before: auto;\">"; s += "<tr>"; s += "<th class=\"namehead\" colspan=\"1\">" + f.name() + "</td>"; s += "<th class=\"namehead\" colspan=\"1\">" + "Formation" + "</td>"; s += "</tr>"; s += "<tr>"; s += "<td colspan=\"1\" rowspan=\"2\">"; s += f.description(); s += "</td>"; s += "<th class=\"stathead\">Pts</td>"; s += "</tr>"; s += "<tr>"; s += "<th class=\"stat\">" + RUData.displayStat(f.pts()) + "</td>"; s += "</tr>"; s += "</table>"; return s; } public static String capitalize(String s) { String[] sarr = s.split("\\b"); s = ""; for (int i = 0; i < sarr.length; i++) { char[] charr = sarr[i].toCharArray(); if (charr[0] >= 'a' && charr[0] <= 'z') charr[0] = (char) (('A' - 'a') + charr[0]); s += s.copyValueOf(charr); } return s; } public static String specialDescriptions(ArmyElement[][] army) { String s = ""; //gather all specials used in this army. DynamicArray<Special> includedSpecs = new DynamicArray(new Special[0]); for (int i = 0; i < army.length; i++) { for (int j = 0; j < army[i].length; j++) { if (!(army[i][j] instanceof SelectedUnit)) continue; SelectedUnit unit = (SelectedUnit) army[i][j]; for (int k = 0; k < unit.specials().length; k++) { Special spec = unit.specials(k).special(RUData.WORKINGPACKAGE.specials()); boolean specIn = false; for (int m = 0; m < includedSpecs.size(); m++) { if (spec.equals(includedSpecs.storage(m))) specIn = true; } if (!specIn) includedSpecs.add(spec); } } } //print descriptions s += "<br><br><br>"; for (int m = 0; m < includedSpecs.size(); m++) { Special spec = includedSpecs.storage(m); s += "<b>" + spec.name() + "</b><br>" + RWFile.nl; s += spec.description(); if (m != includedSpecs.size() - 1) s += "<br><br>" + RWFile.nl; } return s; } public static String pageBreak() { return ""; } }
6,409
0.539098
0.530201
199
31.201006
28.598763
170
false
false
0
0
0
0
0
0
2.763819
false
false
14
a83cac664db8ffa3856afcab272310be7a8a64c9
24,000,277,319,725
3addd799bbbc0c612b1975484f7a2ee2ea3f1efb
/src/main/java/com/ferret/bean/staticBean/PersonInfo.java
93c1a6e3f890370c4b7df0ecde34f647418cc1c7
[]
no_license
yinshuaibin/weby2
https://github.com/yinshuaibin/weby2
5d27e08b6da85fcbac1a3f70210cb31584cd3378
dfe674433a177fa89b3ea76225fd13dd45b9bf89
refs/heads/master
2020-04-22T10:01:24.153000
2019-02-13T01:31:50
2019-02-13T01:31:50
170,291,352
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ferret.bean.staticBean; import lombok.Data; @Data public class PersonInfo { private String ID; //id private String name; //姓名 private String sex; //姓别 private String imagepath; //图片的相对路径 private String birthday; //出生日期 private Float threshold; //对比值 private String record; //人物备注信息 private String idcard;//身份证号 }
UTF-8
Java
393
java
PersonInfo.java
Java
[]
null
[]
package com.ferret.bean.staticBean; import lombok.Data; @Data public class PersonInfo { private String ID; //id private String name; //姓名 private String sex; //姓别 private String imagepath; //图片的相对路径 private String birthday; //出生日期 private Float threshold; //对比值 private String record; //人物备注信息 private String idcard;//身份证号 }
393
0.744807
0.744807
16
20.0625
13.278125
36
false
false
0
0
0
0
0
0
1.5
false
false
14
433e44a240b3bda864be907a5d962da78b03b5cd
28,887,950,100,853
39ac9df84ad4baa3c2c85e4181c09ec2f8ecf2f4
/sources/com/syu/jni/SerialNative.java
d56d1ded1388d658f680a51b9f7659fe5c996787
[]
no_license
Itay9263/bt-app
https://github.com/Itay9263/bt-app
05669edbb595d1da34fde31c077d4c68a0639d52
1994dc69bcc3533d9db886a329eaa607fe794ab6
refs/heads/main
2023-06-06T00:26:07.724000
2021-06-26T15:20:16
2021-06-26T15:20:16
380,532,385
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.syu.jni; public class SerialNative { static { try { System.loadLibrary("sqlserial"); } catch (Throwable th) { } } public static native void native_close(int i); public static native int native_open(String str); public static native int native_open_mbx(); public static native byte[] native_read(int i, int i2, int i3); public static native int native_setup(int i, int i2, int i3, int i4, int i5); public static native void native_write(int i, byte[] bArr, int i2); }
UTF-8
Java
554
java
SerialNative.java
Java
[]
null
[]
package com.syu.jni; public class SerialNative { static { try { System.loadLibrary("sqlserial"); } catch (Throwable th) { } } public static native void native_close(int i); public static native int native_open(String str); public static native int native_open_mbx(); public static native byte[] native_read(int i, int i2, int i3); public static native int native_setup(int i, int i2, int i3, int i4, int i5); public static native void native_write(int i, byte[] bArr, int i2); }
554
0.637184
0.624549
22
24.181818
26.331171
81
false
false
0
0
0
0
0
0
0.727273
false
false
14
35a1b62688f39f8ccc2b9638eb332746a017474a
5,841,155,548,822
b0ec84882dfd349eeec328d1572cb4fb34acaa57
/offline/app/src/main/java/com/example/offline/backend/goal/GoalManager.java
6effdd6e45603f6e72d401ee3807af0a581e1703
[]
no_license
devesmee/offline
https://github.com/devesmee/offline
61e4ec9929c92337d50e4877474c9639760d38e1
4e372856efa0a3a9f55d2985c7fa480af6970434
refs/heads/main
2023-04-18T00:28:54.388000
2021-05-05T12:14:39
2021-05-05T12:14:39
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.offline.backend.goal; import android.content.Context; import com.example.offline.backend.rewards.RewardManager; import com.example.offline.backend.storage.Key; import com.example.offline.backend.storage.Storage; import java.util.ArrayList; public class GoalManager { private ArrayList<Goal> goals; private Goal activeGoal; private int nrOfGoalsCompleted; private Storage storage; private static GoalManager goalManagerInstance; private static RewardManager rewardManager; private GoalManager(Context context) { this.storage = new Storage(context); this.activeGoal = getActiveGoal(); this.goals = getAllGoals(); this.nrOfGoalsCompleted = getNrOfGoalsCompleted(); rewardManager = RewardManager.getInstance(context); } /** * Get singleton instance of the GoalManager * * @param context * @return singletone instance */ public static GoalManager getInstance(Context context) { if (goalManagerInstance == null) { goalManagerInstance = new GoalManager(context); } return goalManagerInstance; } /** * Gets the current active goal from local storage * * @return the current active */ public Goal getActiveGoal() { this.activeGoal = storage.getObject(Key.ACTIVE_GOAL, Goal.class); return this.activeGoal; } /** * Sets the active goal in local storage * * @param goal to be set */ public void setActiveGoal(Goal goal) { this.activeGoal = goal; this.storage.saveObject(Key.ACTIVE_GOAL, goal); } /** * Adds a goal to the list and saves it in the local storage * * @param goal added to the list */ public void addGoalToList(Goal goal) { this.goals.add(goal); this.storage.saveListObject(Key.ALL_GOALS, goals); } /** * Get all goals from local storage * * @return list of all goals */ public ArrayList<Goal> getAllGoals() { this.goals = new ArrayList<>(); ArrayList<Object> goalObjects = storage.getListObject(Key.ALL_GOALS, Goal.class); for (Object object : goalObjects) { this.goals.add((Goal) object); } return this.goals; } /** * Check if a goal is accomplished * * @param goal to be checked * @return true or false */ public boolean isGoalAccomplished(Goal goal) { return goal.getProgress() >= 100; } /** * Gets number of goals completed from local storage * * @return number of goals completed */ public int getNrOfGoalsCompleted() { this.nrOfGoalsCompleted = storage.getInt(Key.NR_OF_GOALS); return nrOfGoalsCompleted; } /** * Save total number of goals completed in the local storage * * @param nrOfGoalsCompleted to be saved */ public void setNrOfGoalsCompleted(int nrOfGoalsCompleted) { this.storage.saveInt(Key.NR_OF_GOALS, nrOfGoalsCompleted); } }
UTF-8
Java
3,088
java
GoalManager.java
Java
[]
null
[]
package com.example.offline.backend.goal; import android.content.Context; import com.example.offline.backend.rewards.RewardManager; import com.example.offline.backend.storage.Key; import com.example.offline.backend.storage.Storage; import java.util.ArrayList; public class GoalManager { private ArrayList<Goal> goals; private Goal activeGoal; private int nrOfGoalsCompleted; private Storage storage; private static GoalManager goalManagerInstance; private static RewardManager rewardManager; private GoalManager(Context context) { this.storage = new Storage(context); this.activeGoal = getActiveGoal(); this.goals = getAllGoals(); this.nrOfGoalsCompleted = getNrOfGoalsCompleted(); rewardManager = RewardManager.getInstance(context); } /** * Get singleton instance of the GoalManager * * @param context * @return singletone instance */ public static GoalManager getInstance(Context context) { if (goalManagerInstance == null) { goalManagerInstance = new GoalManager(context); } return goalManagerInstance; } /** * Gets the current active goal from local storage * * @return the current active */ public Goal getActiveGoal() { this.activeGoal = storage.getObject(Key.ACTIVE_GOAL, Goal.class); return this.activeGoal; } /** * Sets the active goal in local storage * * @param goal to be set */ public void setActiveGoal(Goal goal) { this.activeGoal = goal; this.storage.saveObject(Key.ACTIVE_GOAL, goal); } /** * Adds a goal to the list and saves it in the local storage * * @param goal added to the list */ public void addGoalToList(Goal goal) { this.goals.add(goal); this.storage.saveListObject(Key.ALL_GOALS, goals); } /** * Get all goals from local storage * * @return list of all goals */ public ArrayList<Goal> getAllGoals() { this.goals = new ArrayList<>(); ArrayList<Object> goalObjects = storage.getListObject(Key.ALL_GOALS, Goal.class); for (Object object : goalObjects) { this.goals.add((Goal) object); } return this.goals; } /** * Check if a goal is accomplished * * @param goal to be checked * @return true or false */ public boolean isGoalAccomplished(Goal goal) { return goal.getProgress() >= 100; } /** * Gets number of goals completed from local storage * * @return number of goals completed */ public int getNrOfGoalsCompleted() { this.nrOfGoalsCompleted = storage.getInt(Key.NR_OF_GOALS); return nrOfGoalsCompleted; } /** * Save total number of goals completed in the local storage * * @param nrOfGoalsCompleted to be saved */ public void setNrOfGoalsCompleted(int nrOfGoalsCompleted) { this.storage.saveInt(Key.NR_OF_GOALS, nrOfGoalsCompleted); } }
3,088
0.638925
0.637953
114
26.078947
22.002848
89
false
false
0
0
0
0
0
0
0.333333
false
false
14
81403fc324c0909a8e7914190304223f3821a501
575,525,676,160
d6ab38714f7a5f0dc6d7446ec20626f8f539406a
/backend/collecting/dsfj/Java/edited/UVa.Newspaper.java
05520b16c872faa87ed2b10afe7662b0fffb016e
[]
no_license
haditabatabaei/webproject
https://github.com/haditabatabaei/webproject
8db7178affaca835b5d66daa7d47c28443b53c3d
86b3f253e894f4368a517711bbfbe257be0259fd
refs/heads/master
2020-04-10T09:26:25.819000
2018-12-08T12:21:52
2018-12-08T12:21:52
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.text.DecimalFormat; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class Newspaper { public static void main(String[] args) { Scanner input = new Scanner(System.in); int numberOfTestCases = input.nextInt(); while (numberOfTestCases != 0) { Map<String, Integer> values = new HashMap<String, Integer>(); int numberOfValuableCharacters = input.nextInt(); while (numberOfValuableCharacters != 0) { values.put(input.next(), input.nextInt()); numberOfValuableCharacters--; } int numberOfLines = input.nextInt(); input.nextLine(); double sum = 0; while (numberOfLines != 0) { String textAsString = input.nextLine(); for (int i = 0; i < textAsString.length(); i++) { String c = textAsString.charAt(i) + ""; if (values.containsKey(c)) { sum = sum + values.get(c); } } numberOfLines--; } sum = sum / 100; DecimalFormat formatter = new DecimalFormat("0.00"); String sumFormatted = formatter.format(sum); System.out.println(sumFormatted + "$"); numberOfTestCases--; } } }
UTF-8
Java
1,108
java
UVa.Newspaper.java
Java
[]
null
[]
import java.text.DecimalFormat; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class Newspaper { public static void main(String[] args) { Scanner input = new Scanner(System.in); int numberOfTestCases = input.nextInt(); while (numberOfTestCases != 0) { Map<String, Integer> values = new HashMap<String, Integer>(); int numberOfValuableCharacters = input.nextInt(); while (numberOfValuableCharacters != 0) { values.put(input.next(), input.nextInt()); numberOfValuableCharacters--; } int numberOfLines = input.nextInt(); input.nextLine(); double sum = 0; while (numberOfLines != 0) { String textAsString = input.nextLine(); for (int i = 0; i < textAsString.length(); i++) { String c = textAsString.charAt(i) + ""; if (values.containsKey(c)) { sum = sum + values.get(c); } } numberOfLines--; } sum = sum / 100; DecimalFormat formatter = new DecimalFormat("0.00"); String sumFormatted = formatter.format(sum); System.out.println(sumFormatted + "$"); numberOfTestCases--; } } }
1,108
0.658845
0.648917
39
27.358974
17.950769
64
false
false
0
0
0
0
0
0
3.179487
false
false
14
e79c39f7e89a2a810e2cb0c4ab960719e8c275f0
27,109,833,575,560
a4e2fcf2da52f479c2c25164599bbdb2628a1ffa
/soft/bindings/gvsig_bindings/src/es/unex/sextante/gvsig/gui/GenericDialog.java
d47729a935bbb5267798ec8b822fa4d4d6d03402
[]
no_license
GRSEB9S/sextante
https://github.com/GRSEB9S/sextante
126ffc222a2bed9918bae3b59f87f30158b9bbfe
8ea12c6c40712df01e2e87b02d722d51adb912ea
refs/heads/master
2021-05-28T19:24:23.306000
2013-03-04T15:21:30
2013-03-04T15:21:30
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package es.unex.sextante.gvsig.gui; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import javax.swing.JPanel; import com.iver.andami.ui.mdiManager.IWindow; import com.iver.andami.ui.mdiManager.IWindowListener; import com.iver.andami.ui.mdiManager.WindowInfo; public class GenericDialog extends JPanel implements IWindow, IWindowListener { private WindowInfo viewInfo; private final Component m_Component; private final String m_sName; public GenericDialog(final String sName, final Component component) { super(); m_sName = sName; m_Component = component; initGUI(); } private void initGUI() { final BorderLayout thisLayout = new BorderLayout(); this.setLayout(thisLayout); this.setSize(new Dimension(m_Component.getWidth(), m_Component.getHeight())); this.add(m_Component); } public WindowInfo getWindowInfo() { if (viewInfo == null) { viewInfo = new WindowInfo(WindowInfo.MAXIMIZABLE | WindowInfo.RESIZABLE | WindowInfo.MODELESSDIALOG); viewInfo.setTitle(m_sName); } return viewInfo; } public Object getWindowProfile() { return WindowInfo.DIALOG_PROFILE; } public void windowActivated() {} public void windowClosed() {} }
UTF-8
Java
1,475
java
GenericDialog.java
Java
[]
null
[]
package es.unex.sextante.gvsig.gui; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import javax.swing.JPanel; import com.iver.andami.ui.mdiManager.IWindow; import com.iver.andami.ui.mdiManager.IWindowListener; import com.iver.andami.ui.mdiManager.WindowInfo; public class GenericDialog extends JPanel implements IWindow, IWindowListener { private WindowInfo viewInfo; private final Component m_Component; private final String m_sName; public GenericDialog(final String sName, final Component component) { super(); m_sName = sName; m_Component = component; initGUI(); } private void initGUI() { final BorderLayout thisLayout = new BorderLayout(); this.setLayout(thisLayout); this.setSize(new Dimension(m_Component.getWidth(), m_Component.getHeight())); this.add(m_Component); } public WindowInfo getWindowInfo() { if (viewInfo == null) { viewInfo = new WindowInfo(WindowInfo.MAXIMIZABLE | WindowInfo.RESIZABLE | WindowInfo.MODELESSDIALOG); viewInfo.setTitle(m_sName); } return viewInfo; } public Object getWindowProfile() { return WindowInfo.DIALOG_PROFILE; } public void windowActivated() {} public void windowClosed() {} }
1,475
0.625085
0.625085
71
18.774649
21.771021
110
false
false
0
0
0
0
0
0
0.394366
false
false
14
3d519e7ddc66924958f6fa6bd8a4cf0fd1d50824
953,482,789,315
9d8346bfd19915f7e297aa955564848f5b467828
/031902333/src/main/java/com/zwj/Words.java
b1fd6d75af9958927b19b8ae4c2e28b87fe773a0
[]
no_license
loveTrain444/031902333
https://github.com/loveTrain444/031902333
6a7731a9e6fcf7c3f5bf500502d8cb7c42af4ba4
442200d44f166f3d407d59e16df373379074b29f
refs/heads/main
2023-07-29T03:58:46.089000
2021-09-16T12:21:10
2021-09-16T12:21:10
405,356,915
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zwj; import net.sourceforge.pinyin4j.PinyinHelper; import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType; import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat; import net.sourceforge.pinyin4j.format.HanyuPinyinToneType; import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType; import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination; import java.util.HashMap; import java.util.List; import java.util.Map; public class Words{ public static String illegalString = "0123456789[\"`~!@#$%^&*()+=|{}':;',\\.<>/?~!@#¥%……&*()——+| {}【】‘;:”“’。,、?_]"; //汉语拼音的格式 public static HanyuPinyinOutputFormat format= new HanyuPinyinOutputFormat(); //查找部首拆分的字典 public static Map<Character,String> dictionaryOfBreak = new HashMap<>(); static { format.setCaseType(HanyuPinyinCaseType.LOWERCASE); format.setToneType(HanyuPinyinToneType.WITHOUT_TONE); format.setVCharType(HanyuPinyinVCharType.WITH_V); //读取文件里的拆分词库 List<String> breakList = new Recourse().getResource(); for(String str:breakList){ char word = str.charAt(3); int i=8; while(str.charAt(i)!='\"'){ i++; } String breakUP = str.substring(8,i); dictionaryOfBreak.put(word,breakUP); } } //判断是否是非法字符 public static boolean isIllegal(char c){ String str = illegalString; return str.contains(String.valueOf(c)); } //递归进行敏感词所有分支的组合 private static void com(int step,int len,String[][] matrix,String str,HashMap<String,String> dictionaryOfKeyword){ if(step == len){ StringBuilder keyword = new StringBuilder(); for(int i=0;i<len;i++){ keyword.append(matrix[i][0]); } dictionaryOfKeyword.put(str, keyword.toString()); } else { for (int k=1;k<matrix[step].length;k++){ com(step+1,len,matrix,str+matrix[step][k], dictionaryOfKeyword); } } } public static HashMap<String,String> createDictionaryOfKeyword(List<String> list){ HashMap<String,String> dictionaryOfKeyword = new HashMap<>(); for(String keyWord:list){ String [][] matrix ; matrix = new String[keyWord.length()][]; //获取敏感词的扩展矩阵 for(int i=0;i<keyWord.length();i++){ try { String key = String.valueOf(keyWord.charAt(i)); String[] Spelling ; Spelling = PinyinHelper.toHanyuPinyinStringArray(keyWord.charAt(i),Words.format); //Spelling返回null代表该敏感词字符是不是汉字,则有一个分支;是汉字有五个分支 //比如功有五种情况:功,gong.{gong},g,工力 if(Spelling!=null){ matrix[i] = new String[5]; matrix[i][0] = key; matrix[i][1] = Spelling[0]; matrix[i][2] = "{"+Spelling[0]+"}"; matrix[i][3] = String.valueOf(Spelling[0].charAt(0)); matrix[i][4] = Words.dictionaryOfBreak.get(keyWord.charAt(i)); }else { matrix[i] = new String[2]; matrix[i][0] = key; matrix[i][1] = key; } } catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) { badHanyuPinyinOutputFormatCombination.printStackTrace(); } } /* 根据分支组合出所有情况 */ Words.com(0, keyWord.length(), matrix, "",dictionaryOfKeyword); } return dictionaryOfKeyword; } //判断字符串是否含中文 public static boolean isNotContainChinese(String p) { byte[] bytes = p.getBytes(); int i = bytes.length;//i为字节长度 int j = p.length();//j为字符长度 return i == j; } }
UTF-8
Java
4,318
java
Words.java
Java
[]
null
[]
package com.zwj; import net.sourceforge.pinyin4j.PinyinHelper; import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType; import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat; import net.sourceforge.pinyin4j.format.HanyuPinyinToneType; import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType; import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination; import java.util.HashMap; import java.util.List; import java.util.Map; public class Words{ public static String illegalString = "0123456789[\"`~!@#$%^&*()+=|{}':;',\\.<>/?~!@#¥%……&*()——+| {}【】‘;:”“’。,、?_]"; //汉语拼音的格式 public static HanyuPinyinOutputFormat format= new HanyuPinyinOutputFormat(); //查找部首拆分的字典 public static Map<Character,String> dictionaryOfBreak = new HashMap<>(); static { format.setCaseType(HanyuPinyinCaseType.LOWERCASE); format.setToneType(HanyuPinyinToneType.WITHOUT_TONE); format.setVCharType(HanyuPinyinVCharType.WITH_V); //读取文件里的拆分词库 List<String> breakList = new Recourse().getResource(); for(String str:breakList){ char word = str.charAt(3); int i=8; while(str.charAt(i)!='\"'){ i++; } String breakUP = str.substring(8,i); dictionaryOfBreak.put(word,breakUP); } } //判断是否是非法字符 public static boolean isIllegal(char c){ String str = illegalString; return str.contains(String.valueOf(c)); } //递归进行敏感词所有分支的组合 private static void com(int step,int len,String[][] matrix,String str,HashMap<String,String> dictionaryOfKeyword){ if(step == len){ StringBuilder keyword = new StringBuilder(); for(int i=0;i<len;i++){ keyword.append(matrix[i][0]); } dictionaryOfKeyword.put(str, keyword.toString()); } else { for (int k=1;k<matrix[step].length;k++){ com(step+1,len,matrix,str+matrix[step][k], dictionaryOfKeyword); } } } public static HashMap<String,String> createDictionaryOfKeyword(List<String> list){ HashMap<String,String> dictionaryOfKeyword = new HashMap<>(); for(String keyWord:list){ String [][] matrix ; matrix = new String[keyWord.length()][]; //获取敏感词的扩展矩阵 for(int i=0;i<keyWord.length();i++){ try { String key = String.valueOf(keyWord.charAt(i)); String[] Spelling ; Spelling = PinyinHelper.toHanyuPinyinStringArray(keyWord.charAt(i),Words.format); //Spelling返回null代表该敏感词字符是不是汉字,则有一个分支;是汉字有五个分支 //比如功有五种情况:功,gong.{gong},g,工力 if(Spelling!=null){ matrix[i] = new String[5]; matrix[i][0] = key; matrix[i][1] = Spelling[0]; matrix[i][2] = "{"+Spelling[0]+"}"; matrix[i][3] = String.valueOf(Spelling[0].charAt(0)); matrix[i][4] = Words.dictionaryOfBreak.get(keyWord.charAt(i)); }else { matrix[i] = new String[2]; matrix[i][0] = key; matrix[i][1] = key; } } catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) { badHanyuPinyinOutputFormatCombination.printStackTrace(); } } /* 根据分支组合出所有情况 */ Words.com(0, keyWord.length(), matrix, "",dictionaryOfKeyword); } return dictionaryOfKeyword; } //判断字符串是否含中文 public static boolean isNotContainChinese(String p) { byte[] bytes = p.getBytes(); int i = bytes.length;//i为字节长度 int j = p.length();//j为字符长度 return i == j; } }
4,318
0.559352
0.549875
98
39.918365
27.303911
119
false
false
0
0
0
0
0
0
0.836735
false
false
14
8063d7916ba5c265e469bb5add2def6fe5adce2a
25,237,227,881,180
8f8fd8e4a84f88726b12a446261d41d811474fd0
/app/src/main/java/com/archirayan/starmakerapp/utils/Util.java
5db93ad8d7904091f53e9bc69fb7c2fc516b076a
[]
no_license
iamrahulyadav/StarMakerApp
https://github.com/iamrahulyadav/StarMakerApp
6adb35482ac1ae3fa6293a232d034fa41d92ca55
ba63dfe4314b42a56dc9e3d5fd998f46cc44eeb2
refs/heads/master
2020-03-27T21:04:14.285000
2018-03-16T07:42:11
2018-03-16T07:42:11
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.archirayan.starmakerapp.utils; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.Signature; import android.content.res.TypedArray; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Typeface; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Build; import android.provider.MediaStore; import android.support.v7.app.AppCompatActivity; import android.support.v7.app.AppCompatDelegate; import android.util.Base64; import android.util.Log; import android.view.inputmethod.InputMethodManager; import android.widget.TextView; import com.archirayan.starmakerapp.R; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.InputStreamReader; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import retrofit.mime.TypedFile; @SuppressLint("SimpleDateFormat") public class Util { private static final String TAG = Util.class.getSimpleName(); public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); public static SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); static { AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); } public static void setRegularFace(Context context, TextView textView) { Typeface mFontRegular = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Regular.ttf"); textView.setTypeface(mFontRegular); } public static void setMediumFace(Context context, TextView textView) { Typeface mFont = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Medium.ttf"); textView.setTypeface(mFont); } public static void setLightFace(Context context, TextView textView) { Typeface mFontLight = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Light.ttf"); textView.setTypeface(mFontLight); } public static String getCurrentDate() { Calendar c = Calendar.getInstance(); System.out.println("Current time => " + c.getTime()); SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy"); return df.format(c.getTime()); } public static int getToolbarHeight(Context context) { final TypedArray styledAttributes = context.getTheme().obtainStyledAttributes( new int[]{R.attr.actionBarSize}); int toolbarHeight = (int) styledAttributes.getDimension(0, 0); styledAttributes.recycle(); return toolbarHeight; } public static void hideSoftKeyboard(Activity activity) { InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService( Activity.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow( activity.getCurrentFocus().getWindowToken(), 0); } public static String locatToUTC(String dtStart) { String newDate = ""; SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); try { Date localTime = format.parse(dtStart); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); Date gmtTime = new Date(sdf.format(localTime)); newDate = format.format(gmtTime); return newDate; } catch (Exception e) { e.printStackTrace(); } return newDate; } public static String changeDOBFormate(String time) { String inputPattern = "yyyy-MM-dd"; String outputPattern = " d" + " MMM" + "," + " yyyy"; SimpleDateFormat inputFormat = new SimpleDateFormat(inputPattern); SimpleDateFormat outputFormat = new SimpleDateFormat(outputPattern); Date date = null; String str = null; try { date = inputFormat.parse(time); str = outputFormat.format(date); } catch (ParseException e) { e.printStackTrace(); } return str; } public static String locatToUTCForLocalMsg(String dtStart) { String newDate = ""; SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { Date localTime = format.parse(dtStart); sdf2.setTimeZone(TimeZone.getTimeZone("UTC")); Date gmtTime = new Date(sdf2.format(localTime)); newDate = format.format(gmtTime); return newDate; } catch (Exception e) { e.printStackTrace(); } return newDate; } public static void makeAlertSingleButtons(final AppCompatActivity appCompatActivity, String title) { final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(appCompatActivity); alertDialogBuilder.setMessage(title); alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { arg0.dismiss(); } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } public static void makeAlertTwoButtons(final AppCompatActivity appCompatActivity, String yesButton, String noButton) { final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(appCompatActivity); alertDialogBuilder.setMessage("Kindly grant all permission, we respect your privacy and data!"); alertDialogBuilder.setPositiveButton(yesButton, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) { appCompatActivity.startActivity(new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.fromParts("package", appCompatActivity.getPackageName(), null))); } } }); alertDialogBuilder.setNegativeButton(noButton, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } private static String capitalize(String s) { if (s == null || s.length() == 0) { return ""; } char first = s.charAt(0); if (Character.isUpperCase(first)) { return s; } else { return Character.toUpperCase(first) + s.substring(1); } } public static String capitalFirstLatter(String text) { return text.substring(0, 1).toUpperCase() + text.substring(1); } public static Bitmap decodeFile(File f) { try { // decode image size BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; BitmapFactory.decodeStream(new FileInputStream(f), null, o); // Find the correct scale value. It should be the power of 2. final int REQUIRED_SIZE = 512; int width_tmp = o.outWidth, height_tmp = o.outHeight; int scale = 1; while (true) { if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE) break; width_tmp /= 2; height_tmp /= 2; scale *= 2; } // decode with inSampleSize BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = scale; return BitmapFactory.decodeStream(new FileInputStream(f), null, o2); } catch (FileNotFoundException e) { } return null; } public static String diffBetweenTwoDates(Date startDate, Date endDate) { //milliseconds long different = endDate.getTime() - startDate.getTime(); System.out.println("startDate : " + startDate); System.out.println("endDate : " + endDate); System.out.println("different : " + different); long secondsInMilli = 1000; long minutesInMilli = secondsInMilli * 60; long hoursInMilli = minutesInMilli * 60; long daysInMilli = hoursInMilli * 24; long elapsedDays = different / daysInMilli; different = different % daysInMilli; long elapsedHours = different / hoursInMilli; different = different % hoursInMilli; long elapsedMinutes = different / minutesInMilli; different = different % minutesInMilli; long elapsedSeconds = different / secondsInMilli; String returnDate; if (elapsedDays == 0) { SimpleDateFormat spf = new SimpleDateFormat("hh:mm aaa"); String retunString = spf.format(startDate); returnDate = retunString; } else { SimpleDateFormat spf = new SimpleDateFormat("dd/MM/yy"); String retunString = spf.format(startDate); returnDate = retunString; } System.out.printf("%d days, %d hours, %d minutes, %d seconds%n", elapsedDays, elapsedHours, elapsedMinutes, elapsedSeconds); return returnDate; } public static String getDeviceName() { String manufacturer = Build.MANUFACTURER; String model = Build.MODEL; if (model.startsWith(manufacturer)) { return capitalize(model); } else { return capitalize(manufacturer) + " " + model; } } public static boolean isOnline(Context ctx) { ConnectivityManager cm = (ConnectivityManager) ctx .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnectedOrConnecting()) { return true; } return false; } public static String getRealPathFromURI(Context context, Uri contentUri) { Cursor cursor = null; try { String[] proj = {MediaStore.Images.Media.DATA}; cursor = context.getContentResolver().query(contentUri, proj, null, null, null); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } finally { if (cursor != null) { cursor.close(); } } } public static boolean checkFileSize(String filePath) { TypedFile file = new TypedFile("image/*", new File(filePath)); long fileSizeInBytes = file.length(); // Convert the bytes to Kilobytes (1 KB = 1024 Bytes) long fileSizeInKB = fileSizeInBytes / 1024; // Convert the KB to MegaBytes (1 MB = 1024 KBytes) long fileSizeInMB = fileSizeInKB / 1024; Log.e("fileSizeInMB", "::" + fileSizeInMB); if (fileSizeInMB >= 1) { return false; } return true; } public static String utcToLocalTime1(String dtStart) { if (dtStart != null && dtStart.length() > 5) { String newDate = ""; SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat sdf = new SimpleDateFormat(" d" + " MMM" + "," + " yyyy hh:mm a"); format.setTimeZone(TimeZone.getTimeZone("UTC")); try { Date localTime = format.parse(dtStart); newDate = sdf.format(localTime); return newDate; } catch (Exception e) { e.printStackTrace(); } return newDate; } return ""; } public static String utcToLocalTime2(String dtStart) { if (dtStart != null && dtStart.length() > 5) { String newDate = ""; SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); format.setTimeZone(TimeZone.getTimeZone("UTC")); try { Date localTime = format.parse(dtStart); newDate = sdf.format(localTime); return newDate; } catch (Exception e) { e.printStackTrace(); } return newDate; } return ""; } public static String utcToLocalNewTime(String dtStart) { if (dtStart != null && dtStart.length() > 5) { String newDate = ""; SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat sdf = new SimpleDateFormat(" d" + " MMM" + "," + " hh:mm a"); format.setTimeZone(TimeZone.getTimeZone("UTC")); try { Date localTime = format.parse(dtStart); newDate = sdf.format(localTime); return newDate; } catch (Exception e) { e.printStackTrace(); } return newDate; } return ""; } public static boolean checkPermission(String permission, Context context) { int res = context.checkCallingOrSelfPermission(permission); return (res == PackageManager.PERMISSION_GRANTED); } //Getting lat long public static String ReadSharePrefrence(Context context, String key) { @SuppressWarnings("static-access") SharedPreferences read_data = null; try { read_data = context.getSharedPreferences( Constant.SHRED_PR.SHARE_PREF, context.MODE_PRIVATE); } catch (Exception e) { e.printStackTrace(); } return read_data.getString(key, ""); } public static void WriteSharePrefrence(Context context, String key, String values) { @SuppressWarnings("static-access") SharedPreferences write_Data = context.getSharedPreferences( Constant.SHRED_PR.SHARE_PREF, context.MODE_PRIVATE); SharedPreferences.Editor editor = write_Data.edit(); editor.putString(key, values); editor.commit(); editor.apply(); } public static void printHashKey(Context pContext) { try { PackageInfo info = pContext.getPackageManager().getPackageInfo(pContext.getPackageName(), PackageManager.GET_SIGNATURES); for (Signature signature : info.signatures) { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(signature.toByteArray()); String hashKey = new String(Base64.encode(md.digest(), 0)); Log.i(TAG, "printHashKey() Hash Key: " + hashKey); } } catch (NoSuchAlgorithmException e) { Log.e(TAG, "printHashKey()", e); } catch (Exception e) { Log.e(TAG, "printHashKey()", e); } } // // public static String ReadSharePrefrenceFCM(Context context, String key) { // @SuppressWarnings("static-access") // SharedPreferences read_data = context.getSharedPreferences( // Constant.SHRED_PR.SHARE_PREF_FCM, context.MODE_PRIVATE); // // return read_data.getString(key, ""); // } // public static void WriteSharePrefrenceFCM(Context context, String key, // String values) // { // @SuppressWarnings("static-access") // SharedPreferences write_Data = context.getSharedPreferences( // Constant.SHRED_PR.SHARE_PREF_FCM, context.MODE_PRIVATE); // SharedPreferences.Editor editor = write_Data.edit(); // editor.putString(key, values); // editor.commit(); // editor.apply(); // } public static boolean isValidEmail(CharSequence target) { if (target == null) { return false; } else { return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches(); } } public static String getString(InputStream in) { InputStreamReader is = new InputStreamReader(in); StringBuilder sb = new StringBuilder(); BufferedReader br = new BufferedReader(is); try { String read = br.readLine(); while (read != null) { sb.append(read); read = br.readLine(); } } catch (Exception e) { Log.e(TAG, "ERROR WHILE PARSING RESPONSE TO STRING :: " + e.getMessage()); } finally { try { if (is != null) is.close(); if (br != null) br.close(); } catch (Exception e) { } } return sb.toString(); } }
UTF-8
Java
18,245
java
Util.java
Java
[]
null
[]
package com.archirayan.starmakerapp.utils; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.Signature; import android.content.res.TypedArray; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Typeface; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Build; import android.provider.MediaStore; import android.support.v7.app.AppCompatActivity; import android.support.v7.app.AppCompatDelegate; import android.util.Base64; import android.util.Log; import android.view.inputmethod.InputMethodManager; import android.widget.TextView; import com.archirayan.starmakerapp.R; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.InputStreamReader; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import retrofit.mime.TypedFile; @SuppressLint("SimpleDateFormat") public class Util { private static final String TAG = Util.class.getSimpleName(); public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); public static SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); static { AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); } public static void setRegularFace(Context context, TextView textView) { Typeface mFontRegular = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Regular.ttf"); textView.setTypeface(mFontRegular); } public static void setMediumFace(Context context, TextView textView) { Typeface mFont = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Medium.ttf"); textView.setTypeface(mFont); } public static void setLightFace(Context context, TextView textView) { Typeface mFontLight = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Light.ttf"); textView.setTypeface(mFontLight); } public static String getCurrentDate() { Calendar c = Calendar.getInstance(); System.out.println("Current time => " + c.getTime()); SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy"); return df.format(c.getTime()); } public static int getToolbarHeight(Context context) { final TypedArray styledAttributes = context.getTheme().obtainStyledAttributes( new int[]{R.attr.actionBarSize}); int toolbarHeight = (int) styledAttributes.getDimension(0, 0); styledAttributes.recycle(); return toolbarHeight; } public static void hideSoftKeyboard(Activity activity) { InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService( Activity.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow( activity.getCurrentFocus().getWindowToken(), 0); } public static String locatToUTC(String dtStart) { String newDate = ""; SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); try { Date localTime = format.parse(dtStart); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); Date gmtTime = new Date(sdf.format(localTime)); newDate = format.format(gmtTime); return newDate; } catch (Exception e) { e.printStackTrace(); } return newDate; } public static String changeDOBFormate(String time) { String inputPattern = "yyyy-MM-dd"; String outputPattern = " d" + " MMM" + "," + " yyyy"; SimpleDateFormat inputFormat = new SimpleDateFormat(inputPattern); SimpleDateFormat outputFormat = new SimpleDateFormat(outputPattern); Date date = null; String str = null; try { date = inputFormat.parse(time); str = outputFormat.format(date); } catch (ParseException e) { e.printStackTrace(); } return str; } public static String locatToUTCForLocalMsg(String dtStart) { String newDate = ""; SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { Date localTime = format.parse(dtStart); sdf2.setTimeZone(TimeZone.getTimeZone("UTC")); Date gmtTime = new Date(sdf2.format(localTime)); newDate = format.format(gmtTime); return newDate; } catch (Exception e) { e.printStackTrace(); } return newDate; } public static void makeAlertSingleButtons(final AppCompatActivity appCompatActivity, String title) { final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(appCompatActivity); alertDialogBuilder.setMessage(title); alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { arg0.dismiss(); } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } public static void makeAlertTwoButtons(final AppCompatActivity appCompatActivity, String yesButton, String noButton) { final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(appCompatActivity); alertDialogBuilder.setMessage("Kindly grant all permission, we respect your privacy and data!"); alertDialogBuilder.setPositiveButton(yesButton, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) { appCompatActivity.startActivity(new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.fromParts("package", appCompatActivity.getPackageName(), null))); } } }); alertDialogBuilder.setNegativeButton(noButton, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } private static String capitalize(String s) { if (s == null || s.length() == 0) { return ""; } char first = s.charAt(0); if (Character.isUpperCase(first)) { return s; } else { return Character.toUpperCase(first) + s.substring(1); } } public static String capitalFirstLatter(String text) { return text.substring(0, 1).toUpperCase() + text.substring(1); } public static Bitmap decodeFile(File f) { try { // decode image size BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; BitmapFactory.decodeStream(new FileInputStream(f), null, o); // Find the correct scale value. It should be the power of 2. final int REQUIRED_SIZE = 512; int width_tmp = o.outWidth, height_tmp = o.outHeight; int scale = 1; while (true) { if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE) break; width_tmp /= 2; height_tmp /= 2; scale *= 2; } // decode with inSampleSize BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = scale; return BitmapFactory.decodeStream(new FileInputStream(f), null, o2); } catch (FileNotFoundException e) { } return null; } public static String diffBetweenTwoDates(Date startDate, Date endDate) { //milliseconds long different = endDate.getTime() - startDate.getTime(); System.out.println("startDate : " + startDate); System.out.println("endDate : " + endDate); System.out.println("different : " + different); long secondsInMilli = 1000; long minutesInMilli = secondsInMilli * 60; long hoursInMilli = minutesInMilli * 60; long daysInMilli = hoursInMilli * 24; long elapsedDays = different / daysInMilli; different = different % daysInMilli; long elapsedHours = different / hoursInMilli; different = different % hoursInMilli; long elapsedMinutes = different / minutesInMilli; different = different % minutesInMilli; long elapsedSeconds = different / secondsInMilli; String returnDate; if (elapsedDays == 0) { SimpleDateFormat spf = new SimpleDateFormat("hh:mm aaa"); String retunString = spf.format(startDate); returnDate = retunString; } else { SimpleDateFormat spf = new SimpleDateFormat("dd/MM/yy"); String retunString = spf.format(startDate); returnDate = retunString; } System.out.printf("%d days, %d hours, %d minutes, %d seconds%n", elapsedDays, elapsedHours, elapsedMinutes, elapsedSeconds); return returnDate; } public static String getDeviceName() { String manufacturer = Build.MANUFACTURER; String model = Build.MODEL; if (model.startsWith(manufacturer)) { return capitalize(model); } else { return capitalize(manufacturer) + " " + model; } } public static boolean isOnline(Context ctx) { ConnectivityManager cm = (ConnectivityManager) ctx .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnectedOrConnecting()) { return true; } return false; } public static String getRealPathFromURI(Context context, Uri contentUri) { Cursor cursor = null; try { String[] proj = {MediaStore.Images.Media.DATA}; cursor = context.getContentResolver().query(contentUri, proj, null, null, null); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } finally { if (cursor != null) { cursor.close(); } } } public static boolean checkFileSize(String filePath) { TypedFile file = new TypedFile("image/*", new File(filePath)); long fileSizeInBytes = file.length(); // Convert the bytes to Kilobytes (1 KB = 1024 Bytes) long fileSizeInKB = fileSizeInBytes / 1024; // Convert the KB to MegaBytes (1 MB = 1024 KBytes) long fileSizeInMB = fileSizeInKB / 1024; Log.e("fileSizeInMB", "::" + fileSizeInMB); if (fileSizeInMB >= 1) { return false; } return true; } public static String utcToLocalTime1(String dtStart) { if (dtStart != null && dtStart.length() > 5) { String newDate = ""; SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat sdf = new SimpleDateFormat(" d" + " MMM" + "," + " yyyy hh:mm a"); format.setTimeZone(TimeZone.getTimeZone("UTC")); try { Date localTime = format.parse(dtStart); newDate = sdf.format(localTime); return newDate; } catch (Exception e) { e.printStackTrace(); } return newDate; } return ""; } public static String utcToLocalTime2(String dtStart) { if (dtStart != null && dtStart.length() > 5) { String newDate = ""; SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); format.setTimeZone(TimeZone.getTimeZone("UTC")); try { Date localTime = format.parse(dtStart); newDate = sdf.format(localTime); return newDate; } catch (Exception e) { e.printStackTrace(); } return newDate; } return ""; } public static String utcToLocalNewTime(String dtStart) { if (dtStart != null && dtStart.length() > 5) { String newDate = ""; SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat sdf = new SimpleDateFormat(" d" + " MMM" + "," + " hh:mm a"); format.setTimeZone(TimeZone.getTimeZone("UTC")); try { Date localTime = format.parse(dtStart); newDate = sdf.format(localTime); return newDate; } catch (Exception e) { e.printStackTrace(); } return newDate; } return ""; } public static boolean checkPermission(String permission, Context context) { int res = context.checkCallingOrSelfPermission(permission); return (res == PackageManager.PERMISSION_GRANTED); } //Getting lat long public static String ReadSharePrefrence(Context context, String key) { @SuppressWarnings("static-access") SharedPreferences read_data = null; try { read_data = context.getSharedPreferences( Constant.SHRED_PR.SHARE_PREF, context.MODE_PRIVATE); } catch (Exception e) { e.printStackTrace(); } return read_data.getString(key, ""); } public static void WriteSharePrefrence(Context context, String key, String values) { @SuppressWarnings("static-access") SharedPreferences write_Data = context.getSharedPreferences( Constant.SHRED_PR.SHARE_PREF, context.MODE_PRIVATE); SharedPreferences.Editor editor = write_Data.edit(); editor.putString(key, values); editor.commit(); editor.apply(); } public static void printHashKey(Context pContext) { try { PackageInfo info = pContext.getPackageManager().getPackageInfo(pContext.getPackageName(), PackageManager.GET_SIGNATURES); for (Signature signature : info.signatures) { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(signature.toByteArray()); String hashKey = new String(Base64.encode(md.digest(), 0)); Log.i(TAG, "printHashKey() Hash Key: " + hashKey); } } catch (NoSuchAlgorithmException e) { Log.e(TAG, "printHashKey()", e); } catch (Exception e) { Log.e(TAG, "printHashKey()", e); } } // // public static String ReadSharePrefrenceFCM(Context context, String key) { // @SuppressWarnings("static-access") // SharedPreferences read_data = context.getSharedPreferences( // Constant.SHRED_PR.SHARE_PREF_FCM, context.MODE_PRIVATE); // // return read_data.getString(key, ""); // } // public static void WriteSharePrefrenceFCM(Context context, String key, // String values) // { // @SuppressWarnings("static-access") // SharedPreferences write_Data = context.getSharedPreferences( // Constant.SHRED_PR.SHARE_PREF_FCM, context.MODE_PRIVATE); // SharedPreferences.Editor editor = write_Data.edit(); // editor.putString(key, values); // editor.commit(); // editor.apply(); // } public static boolean isValidEmail(CharSequence target) { if (target == null) { return false; } else { return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches(); } } public static String getString(InputStream in) { InputStreamReader is = new InputStreamReader(in); StringBuilder sb = new StringBuilder(); BufferedReader br = new BufferedReader(is); try { String read = br.readLine(); while (read != null) { sb.append(read); read = br.readLine(); } } catch (Exception e) { Log.e(TAG, "ERROR WHILE PARSING RESPONSE TO STRING :: " + e.getMessage()); } finally { try { if (is != null) is.close(); if (br != null) br.close(); } catch (Exception e) { } } return sb.toString(); } }
18,245
0.590244
0.586188
498
34.640564
26.94836
133
false
false
0
0
0
0
0
0
0.620482
false
false
14
36dd84d2045dee38d31aafe2216ef0f9b7734eb3
18,786,187,019,911
7cd41a760dcac165db5cfdc8af03a1452a6e55d5
/src/main/java/com/springbootshirorestful/SpringbootShiroRestfulApplication.java
7e6681f5d29a8ee657f5ca5aa270884955b3aecf
[]
no_license
qq616023844/springboot-jpa-paging
https://github.com/qq616023844/springboot-jpa-paging
3c66e39832e3d627ca686927435a68f3996a2d19
0f734974c949f5369399fbaa580f7a1c2d144719
refs/heads/master
2022-07-11T05:16:39.202000
2019-07-02T07:55:25
2019-07-02T07:55:25
194,697,463
0
0
null
false
2022-06-21T01:23:24
2019-07-01T15:18:24
2019-07-02T07:55:37
2022-06-21T01:23:20
67
0
0
2
Java
false
false
package com.springbootshirorestful; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @SpringBootApplication public class SpringbootShiroRestfulApplication { public static void main(String[] args) { SpringApplication.run(SpringbootShiroRestfulApplication.class, args); } }
UTF-8
Java
568
java
SpringbootShiroRestfulApplication.java
Java
[]
null
[]
package com.springbootshirorestful; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @SpringBootApplication public class SpringbootShiroRestfulApplication { public static void main(String[] args) { SpringApplication.run(SpringbootShiroRestfulApplication.class, args); } }
568
0.838028
0.838028
16
34.5
29.261749
77
false
false
0
0
0
0
0
0
0.5
false
false
14
fd57ab06672e965b3e89c08690cb9813540dba73
16,724,602,717,012
7fee4aca87253705ecbd16c93c2bd396e2d1cd06
/src/main/java/bephit/dao/UserDAO.java
bce8f91942f3e8482866790ee7361ab360e08651
[]
no_license
storagerepo/WPR103V1.3
https://github.com/storagerepo/WPR103V1.3
2997e5790a57f60249a9da29102f673c64348406
bc601fecd3bd471f74487f2dbf4bb055f7aca599
refs/heads/master
2021-01-15T18:14:20.920000
2014-05-20T07:01:41
2014-05-20T07:01:41
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package bephit.dao; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.sql.DataSource; import bephit.model.ParticipantGroups; import bephit.model.ParticipantsDetails; import bephit.model.UserProfile;; public class UserDAO { private DataSource dataSource; public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } public int checkUsername(String user) { Connection con = null; Statement statement = null; ResultSet resultSet = null; try { con = dataSource.getConnection(); statement = con.createStatement(); } catch (SQLException e1) { e1.printStackTrace(); } try{ int enabled=1; int updateemail=1; String cmd_userlist="Select count(*) as counting from `deemsyspro_deem`.`users` where username='"+user+"'"; System.out.println(cmd_userlist); resultSet=statement.executeQuery(cmd_userlist); resultSet.next(); int count=Integer.parseInt(resultSet.getString("counting")); System.out.println(count); if(count>0) { return 0; } else { return 1; } } catch(Exception e){ System.out.println(e.toString()); releaseStatement(statement); releaseConnection(con); return 0; }finally{ releaseStatement(statement); releaseConnection(con); } } public int setUser(UserProfile user) { Connection con = null; Statement statement = null; ResultSet resultSet = null; int flag=0; try { con = dataSource.getConnection(); statement = con.createStatement(); } catch (SQLException e1) { e1.printStackTrace(); } //List<ParticipantsDetails> participants = new ArrayList<ParticipantsDetails>(); try{ int enabled=1; int updateemail=1; //System.out.println(dateFormat.format(date)); String cmd="INSERT INTO users(`FULLNAME`,`USERNAME`,`PASSWORD`,`ENABLED`,`EMAIL`,`PROFILE_IMAGE`,`UPDATEBYEMAIL`) VALUES('"+user.getFullName()+"','"+user.getUsername()+"','"+user.getPassword()+"','"+enabled+"','"+user.getEmail()+"','empty','"+updateemail+"')"; statement.execute(cmd); resultSet=statement.executeQuery("select max(user_id) as maxuser from users"); resultSet.next(); String cmd_roles="INSERT INTO `deemspro_deem`.`user_roles`(`USER_ID`,`AUTHORITY`) VALUES('"+resultSet.getString("maxuser")+"','ROLE_USER')"; System.out.println(cmd); System.out.println(cmd_roles); statement.execute(cmd_roles); flag=1; } catch(Exception e){ System.out.println(e.toString()); releaseStatement(statement); releaseConnection(con); flag=0; //return 0; }finally{ releaseStatement(statement); releaseConnection(con); releaseResultSet(resultSet); } if(flag==1) return 1; else return 0; } public void releaseConnection(Connection con){ try{if(con != null) con.close(); }catch(Exception e){} } public void releaseResultSet(ResultSet rs){ try{if(rs != null) rs.close(); }catch(Exception e){} } public void releaseStatement(Statement stmt){ try{if(stmt != null) stmt.close(); }catch(Exception e){} } }
UTF-8
Java
3,723
java
UserDAO.java
Java
[ { "context": "\r\n\t \tString cmd=\"INSERT INTO users(`FULLNAME`,`USERNAME`,`PASSWORD`,`ENABLED`,`EMAIL`,`PROFILE_IMAGE`,`UP", "end": 2317, "score": 0.9978424310684204, "start": 2309, "tag": "USERNAME", "value": "USERNAME" }, { "context": "BYEMAIL`) VALUES('\"+user.getFullName()+\"','\"+user.getUsername()+\"','\"+user.getPassword()+\"','\"+enabled+\"','\"+us", "end": 2432, "score": 0.8765377402305603, "start": 2421, "tag": "USERNAME", "value": "getUsername" } ]
null
[]
package bephit.dao; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.sql.DataSource; import bephit.model.ParticipantGroups; import bephit.model.ParticipantsDetails; import bephit.model.UserProfile;; public class UserDAO { private DataSource dataSource; public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } public int checkUsername(String user) { Connection con = null; Statement statement = null; ResultSet resultSet = null; try { con = dataSource.getConnection(); statement = con.createStatement(); } catch (SQLException e1) { e1.printStackTrace(); } try{ int enabled=1; int updateemail=1; String cmd_userlist="Select count(*) as counting from `deemsyspro_deem`.`users` where username='"+user+"'"; System.out.println(cmd_userlist); resultSet=statement.executeQuery(cmd_userlist); resultSet.next(); int count=Integer.parseInt(resultSet.getString("counting")); System.out.println(count); if(count>0) { return 0; } else { return 1; } } catch(Exception e){ System.out.println(e.toString()); releaseStatement(statement); releaseConnection(con); return 0; }finally{ releaseStatement(statement); releaseConnection(con); } } public int setUser(UserProfile user) { Connection con = null; Statement statement = null; ResultSet resultSet = null; int flag=0; try { con = dataSource.getConnection(); statement = con.createStatement(); } catch (SQLException e1) { e1.printStackTrace(); } //List<ParticipantsDetails> participants = new ArrayList<ParticipantsDetails>(); try{ int enabled=1; int updateemail=1; //System.out.println(dateFormat.format(date)); String cmd="INSERT INTO users(`FULLNAME`,`USERNAME`,`PASSWORD`,`ENABLED`,`EMAIL`,`PROFILE_IMAGE`,`UPDATEBYEMAIL`) VALUES('"+user.getFullName()+"','"+user.getUsername()+"','"+user.getPassword()+"','"+enabled+"','"+user.getEmail()+"','empty','"+updateemail+"')"; statement.execute(cmd); resultSet=statement.executeQuery("select max(user_id) as maxuser from users"); resultSet.next(); String cmd_roles="INSERT INTO `deemspro_deem`.`user_roles`(`USER_ID`,`AUTHORITY`) VALUES('"+resultSet.getString("maxuser")+"','ROLE_USER')"; System.out.println(cmd); System.out.println(cmd_roles); statement.execute(cmd_roles); flag=1; } catch(Exception e){ System.out.println(e.toString()); releaseStatement(statement); releaseConnection(con); flag=0; //return 0; }finally{ releaseStatement(statement); releaseConnection(con); releaseResultSet(resultSet); } if(flag==1) return 1; else return 0; } public void releaseConnection(Connection con){ try{if(con != null) con.close(); }catch(Exception e){} } public void releaseResultSet(ResultSet rs){ try{if(rs != null) rs.close(); }catch(Exception e){} } public void releaseStatement(Statement stmt){ try{if(stmt != null) stmt.close(); }catch(Exception e){} } }
3,723
0.603814
0.598711
140
24.592857
29.343019
266
false
false
0
0
0
0
0
0
2.328571
false
false
14
ce492028428d7565e636b87f7ed629c269520d6b
25,082,609,010,236
f69633cd42ca34da11dbdcc1ed29329bf8ed2335
/src/main/java/com/example/demo/base/security/UserService.java
d12d7094445e7e6c49150e0205f1e9b888a433ee
[]
no_license
sw373740570/base-management-project
https://github.com/sw373740570/base-management-project
544c8eff806c08cbdb2aef1fec033b870288dcd8
bdec08e62723541b744fd88955a33e38e361f0b8
refs/heads/master
2020-03-19T10:54:02.565000
2018-06-13T02:26:37
2018-06-13T02:26:37
136,410,625
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.demo.base.security; import com.example.demo.entity.User; import com.example.demo.mapper.UserMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; public class UserService implements UserDetailsService { @Autowired UserMapper userMapper; @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { User user = userMapper.findByUsername(s); if (user == null) { throw new UsernameNotFoundException("用户名不存在"); } return user; } }
UTF-8
Java
795
java
UserService.java
Java
[]
null
[]
package com.example.demo.base.security; import com.example.demo.entity.User; import com.example.demo.mapper.UserMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; public class UserService implements UserDetailsService { @Autowired UserMapper userMapper; @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { User user = userMapper.findByUsername(s); if (user == null) { throw new UsernameNotFoundException("用户名不存在"); } return user; } }
795
0.767561
0.767561
24
31.625
27.872944
86
false
false
0
0
0
0
0
0
0.458333
false
false
14
ba760a1e70d7497c2091a04bf1e9e31fed3e06bf
27,676,769,320,369
2695c6f27e40fbabd3d1e1569a5916ad4dc33e8f
/resttemplae/src/main/java/com/rest/resttemplae/ForexRepro.java
30d7a72b2a684a34246b1e0a738a338fa0940c0a
[]
no_license
speedyjones/java-rest-mysql
https://github.com/speedyjones/java-rest-mysql
f371c6f5d8a8b9a1a352783b03bacf8d7f890387
b7840229b353a90e888198f28c4f9d58ded24bb1
refs/heads/master
2023-09-01T02:01:55.524000
2021-10-28T11:34:32
2021-10-28T11:34:32
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.rest.resttemplae; import com.rest.resttemplae.models.ForexDao; import org.springframework.data.jpa.repository.JpaRepository; public interface ForexRepro extends JpaRepository<ForexDao,Integer>{ }
UTF-8
Java
220
java
ForexRepro.java
Java
[]
null
[]
package com.rest.resttemplae; import com.rest.resttemplae.models.ForexDao; import org.springframework.data.jpa.repository.JpaRepository; public interface ForexRepro extends JpaRepository<ForexDao,Integer>{ }
220
0.804545
0.804545
8
25.5
27.518175
69
false
false
0
0
0
0
0
0
0.5
false
false
14
01bda32345c237f667a6275dd2b59a00ba974040
32,031,866,151,163
d048299a63913ceb7551519e2cab357f4cfd1a1d
/src/main/java/com/itechart/rest/resource/BuyResource.java
724e69965c9e4cdd3eb4badfe25e4755069de6ff
[]
no_license
kiksebegolovy/the-rest
https://github.com/kiksebegolovy/the-rest
ba45eaf4043f2c01949f2039f69d5a386661cfc5
bbab55b533345744c4d36755ec294d73175f29ab
refs/heads/master
2020-02-06T07:20:00.378000
2015-06-21T05:50:55
2015-06-21T05:50:55
37,762,128
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.itechart.rest.resource; import com.itechart.rest.domain.Action; import com.itechart.rest.domain.BuyCoupon; import com.itechart.rest.domain.Company; import com.itechart.rest.domain.Point; import com.itechart.rest.domain.User; import com.itechart.rest.dto.ActiveCouponDTO; import com.itechart.rest.dto.DTO; import com.itechart.rest.dto.ListDTO; import com.itechart.rest.repository.ActionRepository; import com.itechart.rest.repository.BuyRepository; import com.itechart.rest.repository.PointRepository; import com.itechart.rest.repository.UserRepository; import com.itechart.rest.utils.GenerateNumberUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; import java.util.ArrayList; import java.util.List; /** * @author aliaksandr.marozau */ @Component @Path("buy") @Transactional public class BuyResource extends BaseResource<BuyCoupon> { @Autowired private ActionRepository actionRepository; @Autowired private PointRepository pointRepository; @Autowired private BuyRepository buyRepository; @Autowired private UserRepository userRepository; @POST @Path("/coupon") public BuyCoupon buy(BuyCoupon buyCoupon) { Action action = actionRepository.findOne(buyCoupon.getCouponId()); action.setCount(action.getCount() - 1); actionRepository.save(action); Point point = pointRepository.findTopByUserIdAndActionId(buyCoupon.getUserId(), buyCoupon.getCouponId()); point.setCount(point.getCount() - action.getPoints()); pointRepository.save(point); buyCoupon.setUuid(GenerateNumberUtils.generateRandomNumber()); return buyRepository.save(buyCoupon); } @GET @Path("/get") public Response get(@QueryParam("user_id") Long userId) { ListDTO<DTO> result = new ListDTO<>(); List<BuyCoupon> list = buyRepository.findByUserId(userId); result.setSize(list.size()); result.setCurrent(0); List<DTO> actions = new ArrayList<>(); for (BuyCoupon buyCoupon: list) { Action action = actionRepository.findOne(buyCoupon.getCouponId()); DTO dto = new DTO(); dto.setCompanyName(action.getCompany().getName()); dto.setName(action.getName()); dto.setPercent(action.getPercent()); dto.setUuid(buyCoupon.getUuid()); actions.add(dto); } addDataToList(actions, result); return Response.ok(result).build(); } @GET @Path("active_coupon") public Response getActiveCoupon(@QueryParam("user_id") Long userId, @QueryParam("page") int page, @QueryParam("size") int size) { User user = userRepository.findOne(userId); List<Action> actions = actionRepository.findByCompanyId(user.getCompanyId()); List<ActiveCouponDTO> activeCouponDTOs = new ArrayList<>(); ListDTO<ActiveCouponDTO> result = new ListDTO<>(); result.setSize(size); result.setCurrent(page); for (Action action: actions) { List<BuyCoupon> l = buyRepository.findByCouponId(action.getId()); for (BuyCoupon b : l) { ActiveCouponDTO activeCouponDTO = new ActiveCouponDTO(); activeCouponDTO.setUser(user.getName() + " " + user.getSurname()); activeCouponDTO.setName(action.getName()); activeCouponDTO.setUuid(b.getUuid()); activeCouponDTOs.add(activeCouponDTO); } } addDataToList(activeCouponDTOs, result); return Response.ok(result).build(); } }
UTF-8
Java
3,848
java
BuyResource.java
Java
[ { "context": ".ArrayList;\nimport java.util.List;\n\n/**\n * @author aliaksandr.marozau\n */\n@Component\n@Path(\"buy\")\n@Transactional\npublic", "end": 1020, "score": 0.99750816822052, "start": 1002, "tag": "NAME", "value": "aliaksandr.marozau" } ]
null
[]
package com.itechart.rest.resource; import com.itechart.rest.domain.Action; import com.itechart.rest.domain.BuyCoupon; import com.itechart.rest.domain.Company; import com.itechart.rest.domain.Point; import com.itechart.rest.domain.User; import com.itechart.rest.dto.ActiveCouponDTO; import com.itechart.rest.dto.DTO; import com.itechart.rest.dto.ListDTO; import com.itechart.rest.repository.ActionRepository; import com.itechart.rest.repository.BuyRepository; import com.itechart.rest.repository.PointRepository; import com.itechart.rest.repository.UserRepository; import com.itechart.rest.utils.GenerateNumberUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; import java.util.ArrayList; import java.util.List; /** * @author aliaksandr.marozau */ @Component @Path("buy") @Transactional public class BuyResource extends BaseResource<BuyCoupon> { @Autowired private ActionRepository actionRepository; @Autowired private PointRepository pointRepository; @Autowired private BuyRepository buyRepository; @Autowired private UserRepository userRepository; @POST @Path("/coupon") public BuyCoupon buy(BuyCoupon buyCoupon) { Action action = actionRepository.findOne(buyCoupon.getCouponId()); action.setCount(action.getCount() - 1); actionRepository.save(action); Point point = pointRepository.findTopByUserIdAndActionId(buyCoupon.getUserId(), buyCoupon.getCouponId()); point.setCount(point.getCount() - action.getPoints()); pointRepository.save(point); buyCoupon.setUuid(GenerateNumberUtils.generateRandomNumber()); return buyRepository.save(buyCoupon); } @GET @Path("/get") public Response get(@QueryParam("user_id") Long userId) { ListDTO<DTO> result = new ListDTO<>(); List<BuyCoupon> list = buyRepository.findByUserId(userId); result.setSize(list.size()); result.setCurrent(0); List<DTO> actions = new ArrayList<>(); for (BuyCoupon buyCoupon: list) { Action action = actionRepository.findOne(buyCoupon.getCouponId()); DTO dto = new DTO(); dto.setCompanyName(action.getCompany().getName()); dto.setName(action.getName()); dto.setPercent(action.getPercent()); dto.setUuid(buyCoupon.getUuid()); actions.add(dto); } addDataToList(actions, result); return Response.ok(result).build(); } @GET @Path("active_coupon") public Response getActiveCoupon(@QueryParam("user_id") Long userId, @QueryParam("page") int page, @QueryParam("size") int size) { User user = userRepository.findOne(userId); List<Action> actions = actionRepository.findByCompanyId(user.getCompanyId()); List<ActiveCouponDTO> activeCouponDTOs = new ArrayList<>(); ListDTO<ActiveCouponDTO> result = new ListDTO<>(); result.setSize(size); result.setCurrent(page); for (Action action: actions) { List<BuyCoupon> l = buyRepository.findByCouponId(action.getId()); for (BuyCoupon b : l) { ActiveCouponDTO activeCouponDTO = new ActiveCouponDTO(); activeCouponDTO.setUser(user.getName() + " " + user.getSurname()); activeCouponDTO.setName(action.getName()); activeCouponDTO.setUuid(b.getUuid()); activeCouponDTOs.add(activeCouponDTO); } } addDataToList(activeCouponDTOs, result); return Response.ok(result).build(); } }
3,848
0.690229
0.689709
106
35.301888
25.518831
133
false
false
0
0
0
0
0
0
0.650943
false
false
14
4f6ea7d04ccfa447a3acfddcf8a0f00533c231de
10,634,339,059,235
e54888e956d99aff22ba666e269f5c456e5d50ac
/src/com/Generic/Autoconst.java
80064f5d023815f115484a10588b609c83cdcba3
[]
no_license
Dinesh-BM/Selenium_Framework
https://github.com/Dinesh-BM/Selenium_Framework
5b57719535fec48d0b32c9be6e20684c96ce9243
a60fc0e35b8438929b2ea05a31ccc5340ec4c059
refs/heads/master
2020-04-07T22:33:53.299000
2018-11-23T03:23:31
2018-11-23T03:23:31
158,775,572
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.Generic; public interface Autoconst { String chrkey="webdriver.chrome.driver"; String chrval="./driver/chromedriver.exe"; String geckey="webdriver.gecko.driver"; String gecrval="./driver/geckodriver.exe"; String Expath="./input/Input01.xlsx"; }
UTF-8
Java
279
java
Autoconst.java
Java
[ { "context": "\r\npublic interface Autoconst \r\n{\r\n\tString chrkey=\"webdriver.chrome.driver\";\r\n\tString chrval=\"./driver/chromedr", "end": 82, "score": 0.7534130811691284, "start": 72, "tag": "KEY", "value": "webdriver." } ]
null
[]
package com.Generic; public interface Autoconst { String chrkey="webdriver.chrome.driver"; String chrval="./driver/chromedriver.exe"; String geckey="webdriver.gecko.driver"; String gecrval="./driver/geckodriver.exe"; String Expath="./input/Input01.xlsx"; }
279
0.716846
0.709677
12
21.25
18.565762
43
false
false
0
0
0
0
0
0
1
false
false
14
47b8101600e54fd71af94067eadfe7983ac60b28
20,109,036,919,203
246c777042e6adf823f8183abb8d559bacfd59f6
/app/src/main/java/com/pdac/cameracolor/CustomViews/CameraPreview.java
ed0836943c36dc49cf8b39fbcb1897556cae5246
[]
no_license
avivCodhen/CameraColor
https://github.com/avivCodhen/CameraColor
87a450b46e8814a86534a54fe43ba6f382fbb85d
41dcd80558f5621c643bfff52896e2cb43bc73ae
refs/heads/master
2018-11-04T06:25:56.792000
2018-08-26T14:33:17
2018-08-26T14:33:17
146,182,552
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.pdac.cameracolor.CustomViews; import android.app.Activity; import android.app.Service; import android.content.Context; import android.graphics.ImageFormat; import android.hardware.Camera; import android.util.Log; import android.view.Surface; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * * this is a class copied from diffrent application * */ public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback{ // SurfaceHolder private SurfaceHolder mHolder; // Our Camera. public Camera mCamera; private Camera.PreviewCallback callback; // Parent Context. private Context mContext; // Camera Sizing (For rotation, orientation changes) private Camera.Size mPreviewSize; private Camera.Size mPictureSize; // List of supported preview sizes private List<Camera.Size> mSupportedPreviewSizes; // List of supported picture sizes private List<Camera.Size> mSupportedPictureSizes; private static final Object lock = new Object(); private final ViewGroup previewView; // View holding this camera. private View mCameraView; private int mCameraId; private Camera.Parameters mParams; private int cameraOrientation; public CameraPreview(ViewGroup previewView, Camera.Parameters mParams, Context context, Camera camera, Camera.PreviewCallback previewCallback, View cameraView) { super(context); this.previewView = previewView; this.mParams = mParams; this.mCamera = camera; // Capture the context mCameraView = cameraView; mContext = context; setCamera(camera); this.callback = previewCallback; // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed. mHolder = getHolder(); mHolder.addCallback(this); mHolder.setKeepScreenOn(true); // deprecated setting, but required on Android versions prior to 3.0 mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } /** * Begin the preview of the camera input. */ public void startCameraPreview() { try { mCamera.setPreviewDisplay(mHolder); mCamera.setPreviewCallback(callback); mCamera.startPreview(); } catch (Exception e) { e.printStackTrace(); } } /** * Extract supported preview and flash modes from the camera. * * @param camera */ private void setCamera(Camera camera) { // Source: http://stackoverflow.com/questions/7942378/android-camera-will-not-work-startpreview-fails mCamera = camera; mSupportedPreviewSizes = mParams.getSupportedPreviewSizes(); if (mSupportedPreviewSizes != null) { mPreviewSize = getBestPreviewSize(mSupportedPreviewSizes); } mSupportedPictureSizes = mParams.getSupportedPictureSizes(); if (mSupportedPictureSizes != null) { mPictureSize = getPictureSize(mSupportedPictureSizes, mPreviewSize); } requestLayout(); } /** * The Surface has been created, now tell the camera where to draw the preview. * * @param holder */ public void surfaceCreated(SurfaceHolder holder) { try { mCamera.setPreviewDisplay(holder); } catch (IOException e) { e.printStackTrace(); } } /** * Dispose of the camera preview. * * @param holder */ public void surfaceDestroyed(SurfaceHolder holder) { if (mCamera != null) { mCamera.stopPreview(); } } /** * React to surface changed events * * @param holder * @param format * @param w * @param h */ public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // If your preview can change or rotate, take care of those events here. // Make sure to stop the preview before resizing or reformatting it. if (mHolder.getSurface() == null) { // preview surface does not exist return; } // stop preview before making changes try { // Set the auto-focus mode to "continuous" if (mParams.getSupportedFocusModes() != null && mParams.getSupportedFocusModes().contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) { mParams.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE); } mParams.setPreviewFormat(ImageFormat.NV21); // Preview size must exist. if (mPreviewSize != null) { mParams.setPreviewSize(mPreviewSize.width, mPreviewSize.height); mParams.setPictureSize(mPictureSize.width, mPictureSize.height); Camera.CameraInfo info = new Camera.CameraInfo(); Camera.getCameraInfo(mCameraId, info); ViewGroup.LayoutParams params = previewView.getLayoutParams(); double frameRatio = (double) mPreviewSize.width / (double) mPreviewSize.height; double displayRatio = (double) h / (double) w; if (frameRatio > displayRatio) { params.height = (int) (w * frameRatio); params.width = w; } else if (frameRatio < displayRatio) { params.height = h; params.width = (int) (h / frameRatio); } else { params.width = w; params.height = h; } previewView.setLayoutParams(params); synchronized (lock) { cameraOrientation = getCorrectCameraOrientation(info); } } mCamera.stopPreview(); mCamera.setParameters(mParams); mCamera.setDisplayOrientation(cameraOrientation); mCamera.setPreviewDisplay(holder); mCamera.startPreview(); mCamera.setPreviewCallback(callback); } catch (Exception e) { e.printStackTrace(); } } /** * Calculate the measurements of the layout * * @param widthMeasureSpec * @param heightMeasureSpec */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // Source: http://stackoverflow.com/questions/7942378/android-camera-will-not-work-startpreview-fails final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec); final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec); setMeasuredDimension(width, height); } private Camera.Size getBestPreviewSize(List<Camera.Size> sizes) { Camera.Size biggest = null; for (Camera.Size size : sizes) { if (size.width == 3840 && size.height == 2160) { biggest = size; break; } } if (biggest == null) { for (Camera.Size size : sizes) { if (size.width == 1920 && size.height == 1080) { biggest = size; break; } else { if (biggest == null) { biggest = size; } else if (size.height >= biggest.height && size.width >= biggest.width) { biggest = size; } } } } return biggest; } private Camera.Size getPictureSize(List<Camera.Size> sizes, Camera.Size camSize) { Camera.Size biggest = null; float ratio = (float) camSize.width / (float) camSize.height; ArrayList<Camera.Size> sameRatio = new ArrayList<>(); for (Camera.Size pictureSize : sizes) { if (biggest == null) { biggest = pictureSize; } else if (pictureSize.height >= biggest.height && pictureSize.width >= biggest.width) { biggest = pictureSize; } float pictureRatio = (float) pictureSize.width / (float) pictureSize.height; if (ratio == pictureRatio) { if (pictureSize.width == 1920 && pictureSize.height == 1080) return pictureSize; sameRatio.add(pictureSize); } } // } Camera.Size biggestSameRatio = null; for (Camera.Size sameRatioSize : sameRatio) { if (biggestSameRatio == null) { biggestSameRatio = sameRatioSize; } else if (sameRatioSize.width >= biggestSameRatio.width && sameRatioSize.height >= biggestSameRatio.height) { biggestSameRatio = sameRatioSize; } } if (biggestSameRatio != null) { return biggestSameRatio; } return biggest; } int getCorrectCameraOrientation(Camera.CameraInfo info) { WindowManager wm= (WindowManager)mContext.getSystemService(Service.WINDOW_SERVICE); int rotation = wm.getDefaultDisplay().getRotation(); int degrees = 0; switch (rotation) { case Surface.ROTATION_0: degrees = 0; break; case Surface.ROTATION_90: degrees = 90; break; case Surface.ROTATION_180: degrees = 180; break; case Surface.ROTATION_270: degrees = 270; break; } int result; if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { result = (info.orientation + degrees) % 360; result = (360 - result) % 360; } else { result = (info.orientation - degrees + 360) % 360; } return result; } }
UTF-8
Java
10,146
java
CameraPreview.java
Java
[]
null
[]
package com.pdac.cameracolor.CustomViews; import android.app.Activity; import android.app.Service; import android.content.Context; import android.graphics.ImageFormat; import android.hardware.Camera; import android.util.Log; import android.view.Surface; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * * this is a class copied from diffrent application * */ public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback{ // SurfaceHolder private SurfaceHolder mHolder; // Our Camera. public Camera mCamera; private Camera.PreviewCallback callback; // Parent Context. private Context mContext; // Camera Sizing (For rotation, orientation changes) private Camera.Size mPreviewSize; private Camera.Size mPictureSize; // List of supported preview sizes private List<Camera.Size> mSupportedPreviewSizes; // List of supported picture sizes private List<Camera.Size> mSupportedPictureSizes; private static final Object lock = new Object(); private final ViewGroup previewView; // View holding this camera. private View mCameraView; private int mCameraId; private Camera.Parameters mParams; private int cameraOrientation; public CameraPreview(ViewGroup previewView, Camera.Parameters mParams, Context context, Camera camera, Camera.PreviewCallback previewCallback, View cameraView) { super(context); this.previewView = previewView; this.mParams = mParams; this.mCamera = camera; // Capture the context mCameraView = cameraView; mContext = context; setCamera(camera); this.callback = previewCallback; // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed. mHolder = getHolder(); mHolder.addCallback(this); mHolder.setKeepScreenOn(true); // deprecated setting, but required on Android versions prior to 3.0 mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } /** * Begin the preview of the camera input. */ public void startCameraPreview() { try { mCamera.setPreviewDisplay(mHolder); mCamera.setPreviewCallback(callback); mCamera.startPreview(); } catch (Exception e) { e.printStackTrace(); } } /** * Extract supported preview and flash modes from the camera. * * @param camera */ private void setCamera(Camera camera) { // Source: http://stackoverflow.com/questions/7942378/android-camera-will-not-work-startpreview-fails mCamera = camera; mSupportedPreviewSizes = mParams.getSupportedPreviewSizes(); if (mSupportedPreviewSizes != null) { mPreviewSize = getBestPreviewSize(mSupportedPreviewSizes); } mSupportedPictureSizes = mParams.getSupportedPictureSizes(); if (mSupportedPictureSizes != null) { mPictureSize = getPictureSize(mSupportedPictureSizes, mPreviewSize); } requestLayout(); } /** * The Surface has been created, now tell the camera where to draw the preview. * * @param holder */ public void surfaceCreated(SurfaceHolder holder) { try { mCamera.setPreviewDisplay(holder); } catch (IOException e) { e.printStackTrace(); } } /** * Dispose of the camera preview. * * @param holder */ public void surfaceDestroyed(SurfaceHolder holder) { if (mCamera != null) { mCamera.stopPreview(); } } /** * React to surface changed events * * @param holder * @param format * @param w * @param h */ public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // If your preview can change or rotate, take care of those events here. // Make sure to stop the preview before resizing or reformatting it. if (mHolder.getSurface() == null) { // preview surface does not exist return; } // stop preview before making changes try { // Set the auto-focus mode to "continuous" if (mParams.getSupportedFocusModes() != null && mParams.getSupportedFocusModes().contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) { mParams.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE); } mParams.setPreviewFormat(ImageFormat.NV21); // Preview size must exist. if (mPreviewSize != null) { mParams.setPreviewSize(mPreviewSize.width, mPreviewSize.height); mParams.setPictureSize(mPictureSize.width, mPictureSize.height); Camera.CameraInfo info = new Camera.CameraInfo(); Camera.getCameraInfo(mCameraId, info); ViewGroup.LayoutParams params = previewView.getLayoutParams(); double frameRatio = (double) mPreviewSize.width / (double) mPreviewSize.height; double displayRatio = (double) h / (double) w; if (frameRatio > displayRatio) { params.height = (int) (w * frameRatio); params.width = w; } else if (frameRatio < displayRatio) { params.height = h; params.width = (int) (h / frameRatio); } else { params.width = w; params.height = h; } previewView.setLayoutParams(params); synchronized (lock) { cameraOrientation = getCorrectCameraOrientation(info); } } mCamera.stopPreview(); mCamera.setParameters(mParams); mCamera.setDisplayOrientation(cameraOrientation); mCamera.setPreviewDisplay(holder); mCamera.startPreview(); mCamera.setPreviewCallback(callback); } catch (Exception e) { e.printStackTrace(); } } /** * Calculate the measurements of the layout * * @param widthMeasureSpec * @param heightMeasureSpec */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // Source: http://stackoverflow.com/questions/7942378/android-camera-will-not-work-startpreview-fails final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec); final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec); setMeasuredDimension(width, height); } private Camera.Size getBestPreviewSize(List<Camera.Size> sizes) { Camera.Size biggest = null; for (Camera.Size size : sizes) { if (size.width == 3840 && size.height == 2160) { biggest = size; break; } } if (biggest == null) { for (Camera.Size size : sizes) { if (size.width == 1920 && size.height == 1080) { biggest = size; break; } else { if (biggest == null) { biggest = size; } else if (size.height >= biggest.height && size.width >= biggest.width) { biggest = size; } } } } return biggest; } private Camera.Size getPictureSize(List<Camera.Size> sizes, Camera.Size camSize) { Camera.Size biggest = null; float ratio = (float) camSize.width / (float) camSize.height; ArrayList<Camera.Size> sameRatio = new ArrayList<>(); for (Camera.Size pictureSize : sizes) { if (biggest == null) { biggest = pictureSize; } else if (pictureSize.height >= biggest.height && pictureSize.width >= biggest.width) { biggest = pictureSize; } float pictureRatio = (float) pictureSize.width / (float) pictureSize.height; if (ratio == pictureRatio) { if (pictureSize.width == 1920 && pictureSize.height == 1080) return pictureSize; sameRatio.add(pictureSize); } } // } Camera.Size biggestSameRatio = null; for (Camera.Size sameRatioSize : sameRatio) { if (biggestSameRatio == null) { biggestSameRatio = sameRatioSize; } else if (sameRatioSize.width >= biggestSameRatio.width && sameRatioSize.height >= biggestSameRatio.height) { biggestSameRatio = sameRatioSize; } } if (biggestSameRatio != null) { return biggestSameRatio; } return biggest; } int getCorrectCameraOrientation(Camera.CameraInfo info) { WindowManager wm= (WindowManager)mContext.getSystemService(Service.WINDOW_SERVICE); int rotation = wm.getDefaultDisplay().getRotation(); int degrees = 0; switch (rotation) { case Surface.ROTATION_0: degrees = 0; break; case Surface.ROTATION_90: degrees = 90; break; case Surface.ROTATION_180: degrees = 180; break; case Surface.ROTATION_270: degrees = 270; break; } int result; if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { result = (info.orientation + degrees) % 360; result = (360 - result) % 360; } else { result = (info.orientation - degrees + 360) % 360; } return result; } }
10,146
0.588606
0.581116
325
30.218462
27.401037
165
false
false
0
0
0
0
0
0
0.436923
false
false
14
36db4067b669b707176971d7191cd14e2f177b53
4,818,953,355,378
92e2a8b47a075cc8e458669a4d43f424668d65bd
/src/main/java/leetcode/L105_ConstructBinaryTreeFromPreorderAndInorderTraversal.java
dedb976bad1a3e38c6386d8f9d646ddff92161f8
[]
no_license
IS908/leetcode
https://github.com/IS908/leetcode
0a46277fc7aa60e3938619a582bfdbaaffd55d17
2846b56192b6ad26fa7ab7faeb7d3957e1801e21
refs/heads/master
2021-01-23T14:03:43.131000
2019-07-28T16:01:02
2019-07-28T16:01:02
54,365,166
3
0
null
false
2020-10-13T08:47:39
2016-03-21T06:29:10
2019-07-28T16:01:15
2020-10-13T08:47:37
323
2
0
1
Java
false
false
package leetcode; import leetcode.Utils.TreeNode; /** * Given preorder and inorder traversal of a tree, construct the binary tree. * <p/> * Created by kevin on 2016/3/30. */ public class L105_ConstructBinaryTreeFromPreorderAndInorderTraversal { public TreeNode buildTree(int[] preorder, int[] inorder) { if (preorder == null) return null; TreeNode root = buildByPreIn(preorder, inorder, 0, preorder.length - 1, 0, inorder.length - 1); return root; } public TreeNode buildByPreIn(int[] preorder, int[] inorder, int p_s, int p_e, int i_s, int i_e) { if (p_s > p_e) return null; int pivot = preorder[p_s]; int loc = i_s; for (; loc < i_e; loc++) { if (pivot == inorder[loc]) break; } int len = loc - i_s; TreeNode node = new TreeNode(pivot); node.left = buildByPreIn(preorder, inorder, p_s + 1, p_s + len, i_s, loc - 1); node.right = buildByPreIn(preorder, inorder, p_s + len + 1, p_e, loc + 1, i_e); return node; } }
UTF-8
Java
1,054
java
L105_ConstructBinaryTreeFromPreorderAndInorderTraversal.java
Java
[ { "context": ", construct the binary tree.\n * <p/>\n * Created by kevin on 2016/3/30.\n */\npublic class L105_ConstructBina", "end": 161, "score": 0.9981314539909363, "start": 156, "tag": "USERNAME", "value": "kevin" } ]
null
[]
package leetcode; import leetcode.Utils.TreeNode; /** * Given preorder and inorder traversal of a tree, construct the binary tree. * <p/> * Created by kevin on 2016/3/30. */ public class L105_ConstructBinaryTreeFromPreorderAndInorderTraversal { public TreeNode buildTree(int[] preorder, int[] inorder) { if (preorder == null) return null; TreeNode root = buildByPreIn(preorder, inorder, 0, preorder.length - 1, 0, inorder.length - 1); return root; } public TreeNode buildByPreIn(int[] preorder, int[] inorder, int p_s, int p_e, int i_s, int i_e) { if (p_s > p_e) return null; int pivot = preorder[p_s]; int loc = i_s; for (; loc < i_e; loc++) { if (pivot == inorder[loc]) break; } int len = loc - i_s; TreeNode node = new TreeNode(pivot); node.left = buildByPreIn(preorder, inorder, p_s + 1, p_s + len, i_s, loc - 1); node.right = buildByPreIn(preorder, inorder, p_s + len + 1, p_e, loc + 1, i_e); return node; } }
1,054
0.597723
0.580645
30
34.133335
31.285496
103
false
false
0
0
0
0
0
0
1.266667
false
false
14
e4224ef9f9075b7a722d8e4d08da08136bbdf759
24,223,615,609,926
e04b2e8702528789c15e94a00808221671d3a8ba
/neDetectionProject/src/de/uniwue/mk/malletcrf/MaxEntClassifierTrainer.java
010cca33461f08a833fde8516e006ab1ba66f948
[ "Apache-2.0" ]
permissive
MarkusKrug/NERDetection
https://github.com/MarkusKrug/NERDetection
4c6e5348932f5619db141d47422d2a6cf5ee7f9b
806bd94bd5a9823741b10220ab9bacd4adc49784
refs/heads/master
2016-09-05T13:20:17.582000
2015-04-21T05:03:49
2015-04-21T05:03:49
29,518,378
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package de.uniwue.mk.malletcrf; import java.io.File; import cc.mallet.classify.MaxEntTrainer; import cc.mallet.pipe.Pipe; import cc.mallet.types.InstanceList; public class MaxEntClassifierTrainer { public static void train(File trainFile, File modelFile) throws Exception { IPipeInitializer initializer = new ClassificationPipeInitializer(); Pipe pipe = initializer.initializePipe(); MalletIO ioHandler = new MalletIO(); MaxEntTrainer trainer = new MaxEntTrainer(); InstanceList instances = TSVFeatureReader.readFeatures(trainFile, pipe); cc.mallet.classify.MaxEnt model = trainer.train(instances); ioHandler.serializeModel(model, modelFile.getAbsolutePath()); } }
UTF-8
Java
707
java
MaxEntClassifierTrainer.java
Java
[]
null
[]
package de.uniwue.mk.malletcrf; import java.io.File; import cc.mallet.classify.MaxEntTrainer; import cc.mallet.pipe.Pipe; import cc.mallet.types.InstanceList; public class MaxEntClassifierTrainer { public static void train(File trainFile, File modelFile) throws Exception { IPipeInitializer initializer = new ClassificationPipeInitializer(); Pipe pipe = initializer.initializePipe(); MalletIO ioHandler = new MalletIO(); MaxEntTrainer trainer = new MaxEntTrainer(); InstanceList instances = TSVFeatureReader.readFeatures(trainFile, pipe); cc.mallet.classify.MaxEnt model = trainer.train(instances); ioHandler.serializeModel(model, modelFile.getAbsolutePath()); } }
707
0.769448
0.769448
26
26.192308
27.366486
77
false
false
0
0
0
0
0
0
0.576923
false
false
14
e6d86f9a0b02629b6f2dd8378c78bf9f326ae212
32,908,039,426,270
2517d4d57c489fedbbca00e09d30e9ea4d5e6b80
/app/src/main/java/com/vadomosan/coronaargame/RotatingNode.java
eebeae506d46b7ce9ad3a539b42bb9f4d0ebeae3
[]
no_license
vahidmohammadisan/kill-corona
https://github.com/vahidmohammadisan/kill-corona
79992ba42520c54d1c26bd7db061417e5b7d6ad6
3d23049c45d9fff658cb0d55696887264d89c77f
refs/heads/master
2022-04-22T16:13:57.354000
2020-04-21T07:28:44
2020-04-21T07:28:44
257,512,075
4
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.vadomosan.coronaargame; import android.animation.ObjectAnimator; import android.view.animation.LinearInterpolator; import androidx.annotation.Nullable; import com.google.ar.sceneform.FrameTime; import com.google.ar.sceneform.Node; import com.google.ar.sceneform.math.Quaternion; import com.google.ar.sceneform.math.QuaternionEvaluator; import com.google.ar.sceneform.math.Vector3; public class RotatingNode extends Node { @Nullable private ObjectAnimator orbitAnimation = null; private float degreesPerSecond = 90.0f; private final boolean clockwise; private final float axisTiltDeg; private float lastSpeedMultiplier = 1.0f; private float speed = 1.0f; public RotatingNode(boolean clockwise, float axisTiltDeg) { this.clockwise = clockwise; this.axisTiltDeg = axisTiltDeg; } @Override public void onUpdate(FrameTime frameTime) { super.onUpdate(frameTime); if (orbitAnimation == null) { return; } float speedMultiplier = 1.0f; if (lastSpeedMultiplier == speedMultiplier) { return; } if (speedMultiplier == 0.0f) { orbitAnimation.pause(); } else { orbitAnimation.resume(); float animatedFraction = orbitAnimation.getAnimatedFraction(); orbitAnimation.setDuration(getAnimationDuration()); orbitAnimation.setCurrentFraction(animatedFraction); } lastSpeedMultiplier = speedMultiplier; } public void setDegreesPerSecond(float degreesPerSecond) { this.degreesPerSecond = degreesPerSecond; } @Override public void onActivate() { startAnimation(); } @Override public void onDeactivate() { stopAnimation(); } private long getAnimationDuration() { return (long) (1000 * 360 / (degreesPerSecond * speed)); } private void startAnimation() { if (orbitAnimation != null) { return; } orbitAnimation = createAnimator(clockwise, axisTiltDeg); orbitAnimation.setTarget(this); orbitAnimation.setDuration(getAnimationDuration()); orbitAnimation.start(); } private void stopAnimation() { if (orbitAnimation == null) { return; } orbitAnimation.cancel(); orbitAnimation = null; } private static ObjectAnimator createAnimator(boolean clockwise, float axisTiltDeg) { Quaternion[] orientations = new Quaternion[4]; Quaternion baseOrientation = Quaternion.axisAngle(new Vector3(1.0f, 0f, 0.0f), axisTiltDeg); for (int i = 0; i < orientations.length; i++) { float angle = i * 360 / (orientations.length - 1); if (clockwise) { angle = 360 - angle; } Quaternion orientation = Quaternion.axisAngle(new Vector3(0.0f, 1.0f, 0.0f), angle); orientations[i] = Quaternion.multiply(baseOrientation, orientation); } ObjectAnimator orbitAnimation = new ObjectAnimator(); orbitAnimation.setObjectValues((Object[]) orientations); orbitAnimation.setPropertyName("localRotation"); orbitAnimation.setEvaluator(new QuaternionEvaluator()); orbitAnimation.setRepeatCount(ObjectAnimator.INFINITE); orbitAnimation.setRepeatMode(ObjectAnimator.RESTART); orbitAnimation.setInterpolator(new LinearInterpolator()); orbitAnimation.setAutoCancel(true); return orbitAnimation; } }
UTF-8
Java
3,573
java
RotatingNode.java
Java
[]
null
[]
package com.vadomosan.coronaargame; import android.animation.ObjectAnimator; import android.view.animation.LinearInterpolator; import androidx.annotation.Nullable; import com.google.ar.sceneform.FrameTime; import com.google.ar.sceneform.Node; import com.google.ar.sceneform.math.Quaternion; import com.google.ar.sceneform.math.QuaternionEvaluator; import com.google.ar.sceneform.math.Vector3; public class RotatingNode extends Node { @Nullable private ObjectAnimator orbitAnimation = null; private float degreesPerSecond = 90.0f; private final boolean clockwise; private final float axisTiltDeg; private float lastSpeedMultiplier = 1.0f; private float speed = 1.0f; public RotatingNode(boolean clockwise, float axisTiltDeg) { this.clockwise = clockwise; this.axisTiltDeg = axisTiltDeg; } @Override public void onUpdate(FrameTime frameTime) { super.onUpdate(frameTime); if (orbitAnimation == null) { return; } float speedMultiplier = 1.0f; if (lastSpeedMultiplier == speedMultiplier) { return; } if (speedMultiplier == 0.0f) { orbitAnimation.pause(); } else { orbitAnimation.resume(); float animatedFraction = orbitAnimation.getAnimatedFraction(); orbitAnimation.setDuration(getAnimationDuration()); orbitAnimation.setCurrentFraction(animatedFraction); } lastSpeedMultiplier = speedMultiplier; } public void setDegreesPerSecond(float degreesPerSecond) { this.degreesPerSecond = degreesPerSecond; } @Override public void onActivate() { startAnimation(); } @Override public void onDeactivate() { stopAnimation(); } private long getAnimationDuration() { return (long) (1000 * 360 / (degreesPerSecond * speed)); } private void startAnimation() { if (orbitAnimation != null) { return; } orbitAnimation = createAnimator(clockwise, axisTiltDeg); orbitAnimation.setTarget(this); orbitAnimation.setDuration(getAnimationDuration()); orbitAnimation.start(); } private void stopAnimation() { if (orbitAnimation == null) { return; } orbitAnimation.cancel(); orbitAnimation = null; } private static ObjectAnimator createAnimator(boolean clockwise, float axisTiltDeg) { Quaternion[] orientations = new Quaternion[4]; Quaternion baseOrientation = Quaternion.axisAngle(new Vector3(1.0f, 0f, 0.0f), axisTiltDeg); for (int i = 0; i < orientations.length; i++) { float angle = i * 360 / (orientations.length - 1); if (clockwise) { angle = 360 - angle; } Quaternion orientation = Quaternion.axisAngle(new Vector3(0.0f, 1.0f, 0.0f), angle); orientations[i] = Quaternion.multiply(baseOrientation, orientation); } ObjectAnimator orbitAnimation = new ObjectAnimator(); orbitAnimation.setObjectValues((Object[]) orientations); orbitAnimation.setPropertyName("localRotation"); orbitAnimation.setEvaluator(new QuaternionEvaluator()); orbitAnimation.setRepeatCount(ObjectAnimator.INFINITE); orbitAnimation.setRepeatMode(ObjectAnimator.RESTART); orbitAnimation.setInterpolator(new LinearInterpolator()); orbitAnimation.setAutoCancel(true); return orbitAnimation; } }
3,573
0.655751
0.644276
122
28.286884
24.964394
100
false
false
0
0
0
0
0
0
0.540984
false
false
14
5206e988ab6703c3af7ebb3f6ae5deb24c76a3ad
16,733,192,639,976
630771c6c3ba94843080ef2dda14e36e1280aba5
/src/main/java/com/web/demo/controls/CropRestController.java
87932238d574bc24fac356d76288cfacc6cdc1b1
[]
no_license
harilearning1989/spring-boot-oracle-k8s
https://github.com/harilearning1989/spring-boot-oracle-k8s
7eb5c764b61519d25188a59c5faa6cf209fefed3
5913b4eb0313424d311596cb8eb6db2e47d2e5d3
refs/heads/master
2023-07-31T22:55:07.478000
2021-09-09T12:41:07
2021-09-09T12:41:07
398,726,918
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.web.demo.controls; import com.web.demo.dtos.CropInsuranceDTO; import com.web.demo.services.CropService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import static java.util.concurrent.CompletableFuture.supplyAsync; @RestController @RequestMapping("crops") public class CropRestController { private static final Logger LOGGER = LoggerFactory.getLogger(CropRestController.class); CropService cropService; @Autowired public void setCropService(CropService cropService) { this.cropService = cropService; } @GetMapping(value = "/readCrop") public ResponseEntity<List<CropInsuranceDTO>> readCropCSV() { CompletableFuture<List<CropInsuranceDTO>> cropFuture = supplyAsync(() -> cropService.readCropDetails()); try { return ResponseEntity.status(HttpStatus.OK).body(cropFuture.get()); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } return null; } }
UTF-8
Java
1,482
java
CropRestController.java
Java
[]
null
[]
package com.web.demo.controls; import com.web.demo.dtos.CropInsuranceDTO; import com.web.demo.services.CropService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import static java.util.concurrent.CompletableFuture.supplyAsync; @RestController @RequestMapping("crops") public class CropRestController { private static final Logger LOGGER = LoggerFactory.getLogger(CropRestController.class); CropService cropService; @Autowired public void setCropService(CropService cropService) { this.cropService = cropService; } @GetMapping(value = "/readCrop") public ResponseEntity<List<CropInsuranceDTO>> readCropCSV() { CompletableFuture<List<CropInsuranceDTO>> cropFuture = supplyAsync(() -> cropService.readCropDetails()); try { return ResponseEntity.status(HttpStatus.OK).body(cropFuture.get()); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } return null; } }
1,482
0.758435
0.757085
44
32.68182
25.369785
91
false
false
0
0
0
0
0
0
0.522727
false
false
14
17f3c546fc7ab68a7d6ef985fc7d3a5d55914d50
15,058,155,392,600
89a35f8cec7cd1ff9421181fabad45eeb6cc09a6
/src/test/java/javaPrograms/InheritanceExamples/Child.java
51ab500ae04dad1aa787179ce787cd28310801ea
[]
no_license
DeepKandey/JavaAndSeleniumConcepts
https://github.com/DeepKandey/JavaAndSeleniumConcepts
21000aebc0322eb2a97baaecbf95b9549e65d0af
40b095d1239d87298e326a103bf288d9b870cc08
refs/heads/master
2023-06-22T07:54:27.358000
2022-12-15T16:44:28
2022-12-15T16:44:28
139,228,234
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package javaPrograms.InheritanceExamples; public class Child extends Parent { int a = 100; public void m1() { System.out.println("Child"); } public static void main(String[] args) { Child obj = new Child(); Parent pObj = obj; System.out.println(((Child) pObj).a); System.out.println(pObj.a); // For variables in inheritance, it goes by reference variable pObj.m1(); // for method definition in inheritance, it goes by object type. } }
UTF-8
Java
493
java
Child.java
Java
[]
null
[]
package javaPrograms.InheritanceExamples; public class Child extends Parent { int a = 100; public void m1() { System.out.println("Child"); } public static void main(String[] args) { Child obj = new Child(); Parent pObj = obj; System.out.println(((Child) pObj).a); System.out.println(pObj.a); // For variables in inheritance, it goes by reference variable pObj.m1(); // for method definition in inheritance, it goes by object type. } }
493
0.647059
0.636917
19
23.947369
26.595358
94
false
false
0
0
0
0
0
0
0.526316
false
false
14
f3bcee89d16b2207a5895257b182098f32f2196f
9,311,489,109,139
533d671dc699454e5ae36e2943dc3dbbcc81b791
/sprockets/core-sprockets/src/se/abalon/usecase/CurrencyRequestFormat.java
ff868e29ab6f01d7d866009d64ff902c9066044a
[]
no_license
tstjerndal/steveham_git
https://github.com/tstjerndal/steveham_git
1647206badef42458459c0eb4072cedafaa40874
094308ce12cf64ab1d8f434fcdbf24289c47b6e2
refs/heads/master
2016-08-07T18:38:38.255000
2013-12-10T11:46:43
2013-12-10T11:46:43
37,447,267
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Created on Oct 25, 2004 * */ package se.abalon.usecase; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.ParseException; import java.util.Locale; import java.util.Map; import se.abalon.util.FormatException; /** * Translates a String containing Locale formatted currency information to a Double. * * @author Fredrik Hellström [f.hellstrom@abalon.se] */ public class CurrencyRequestFormat implements RequestFormat { /** * @see se.abalon.usecase.RequestFormat#getValue(java.util.Map, java.lang.String, java.lang.Object, java.util.Locale) */ public Object getValue(Map requestData, String key, Object originalValue, Locale locale) throws FormatException { String currStr = (String) requestData.get(key + ":CURRENCY"); DecimalFormatSymbols dsf = new DecimalFormatSymbols(locale); DecimalFormat cf = (DecimalFormat) DecimalFormat.getInstance(locale); Object parsedValue = null; try { //cf.setCurrency(BofPersistenceManagerFactory.getDefaultCurrency()); cf.setDecimalFormatSymbols(dsf); parsedValue = cf.parse(currStr); } catch (ParseException e) { throw new FormatException(se.abalon.bof.ResourceKeys.STRING_PARSING_ERROR, new Object[] {currStr}); } if (parsedValue instanceof Double) { return parsedValue; } else if (parsedValue instanceof Long) { return new Double(((Long)parsedValue).longValue()); } else if (parsedValue instanceof Integer) { return new Double(((Integer)parsedValue).intValue()); } else { throw new FormatException(se.abalon.bof.ResourceKeys.STRING_PARSING_ERROR, new Object[] {currStr}); } } }
UTF-8
Java
1,691
java
CurrencyRequestFormat.java
Java
[ { "context": " currency information to a Double.\r\n *\r\n * @author Fredrik Hellström [f.hellstrom@abalon.se]\r\n */\r\npublic class Curren", "end": 394, "score": 0.9998756647109985, "start": 377, "tag": "NAME", "value": "Fredrik Hellström" }, { "context": "n to a Double.\r\n *\r\n * @author Fredrik Hellström [f.hellstrom@abalon.se]\r\n */\r\npublic class CurrencyRequestFormat impleme", "end": 417, "score": 0.9999353289604187, "start": 396, "tag": "EMAIL", "value": "f.hellstrom@abalon.se" } ]
null
[]
/* * Created on Oct 25, 2004 * */ package se.abalon.usecase; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.ParseException; import java.util.Locale; import java.util.Map; import se.abalon.util.FormatException; /** * Translates a String containing Locale formatted currency information to a Double. * * @author <NAME> [<EMAIL>] */ public class CurrencyRequestFormat implements RequestFormat { /** * @see se.abalon.usecase.RequestFormat#getValue(java.util.Map, java.lang.String, java.lang.Object, java.util.Locale) */ public Object getValue(Map requestData, String key, Object originalValue, Locale locale) throws FormatException { String currStr = (String) requestData.get(key + ":CURRENCY"); DecimalFormatSymbols dsf = new DecimalFormatSymbols(locale); DecimalFormat cf = (DecimalFormat) DecimalFormat.getInstance(locale); Object parsedValue = null; try { //cf.setCurrency(BofPersistenceManagerFactory.getDefaultCurrency()); cf.setDecimalFormatSymbols(dsf); parsedValue = cf.parse(currStr); } catch (ParseException e) { throw new FormatException(se.abalon.bof.ResourceKeys.STRING_PARSING_ERROR, new Object[] {currStr}); } if (parsedValue instanceof Double) { return parsedValue; } else if (parsedValue instanceof Long) { return new Double(((Long)parsedValue).longValue()); } else if (parsedValue instanceof Integer) { return new Double(((Integer)parsedValue).intValue()); } else { throw new FormatException(se.abalon.bof.ResourceKeys.STRING_PARSING_ERROR, new Object[] {currStr}); } } }
1,665
0.719527
0.715976
53
29.886793
32.316631
118
false
false
0
0
0
0
0
0
1.811321
false
false
14
859a9aa731b53290d68162f89994743c8ba3abbc
26,250,840,167,351
51227d22a5dff4b7dcdc935cb9e3e1ff4ebbafb1
/requsetAndResponseDemo/src/main/java/com/DownloadDemo.java
8cf15a7590dc05f15bb1a69e12278aff6a69220e
[]
no_license
ming954688/java
https://github.com/ming954688/java
7b2321b756bcc488a524661d2dc11cb79072bd17
45748663da21f5201ec492162b2045f45ac1813d
refs/heads/master
2022-06-30T07:21:34.005000
2020-02-20T14:09:35
2020-02-20T14:09:35
237,375,290
0
0
null
false
2022-06-21T02:43:26
2020-01-31T06:43:01
2020-02-20T14:10:09
2022-06-21T02:43:22
42,447
0
0
7
Java
false
false
package com; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; @WebServlet(name = "DownloadDemo", urlPatterns = "/downlaod") public class DownloadDemo extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String filename = request.getParameter("filename"); response.setHeader("Content-Disposition","attachment; filename="+filename); ServletContext servletContext = getServletContext(); String path = servletContext.getRealPath(filename); FileInputStream is = new FileInputStream(path); ServletOutputStream outputStream = response.getOutputStream(); int len = 0; byte[] bytes = new byte[50]; while ((len = is.read(bytes)) != -1) { outputStream.write(bytes, 0, len); } outputStream.close(); is.close(); } }
UTF-8
Java
1,411
java
DownloadDemo.java
Java
[]
null
[]
package com; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; @WebServlet(name = "DownloadDemo", urlPatterns = "/downlaod") public class DownloadDemo extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String filename = request.getParameter("filename"); response.setHeader("Content-Disposition","attachment; filename="+filename); ServletContext servletContext = getServletContext(); String path = servletContext.getRealPath(filename); FileInputStream is = new FileInputStream(path); ServletOutputStream outputStream = response.getOutputStream(); int len = 0; byte[] bytes = new byte[50]; while ((len = is.read(bytes)) != -1) { outputStream.write(bytes, 0, len); } outputStream.close(); is.close(); } }
1,411
0.737066
0.733522
39
35.179485
30.157597
122
false
false
0
0
0
0
0
0
0.820513
false
false
14
d6cd4ee1c214f71b20e2179b3c915b1989fc28d7
19,018,115,213,750
6091fc75fd8baee1f278207e0715b06182ca02ed
/app/src/main/java/com/example/administrator/pandatvsecond/util/PermissionUtils.java
222327d2444bca71498cb2a8543ef776276444a5
[]
no_license
3132153418/PandaTvsecond
https://github.com/3132153418/PandaTvsecond
9bde73f882f67e83cb67e9345ba9c1ac37985755
59e709b0e07d37931c1ff4cf4cff144c87e3d12f
refs/heads/master
2021-01-01T19:27:06.793000
2017-08-02T11:27:05
2017-08-02T11:27:05
98,590,001
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.administrator.pandatvsecond.util; /** * Created by Administrator on 2017/7/28. */ public class PermissionUtils { }
UTF-8
Java
140
java
PermissionUtils.java
Java
[ { "context": "ministrator.pandatvsecond.util;\n\n/**\n * Created by Administrator on 2017/7/28.\n */\n\npublic class PermissionUtils {", "end": 86, "score": 0.5355654954910278, "start": 73, "tag": "NAME", "value": "Administrator" } ]
null
[]
package com.example.administrator.pandatvsecond.util; /** * Created by Administrator on 2017/7/28. */ public class PermissionUtils { }
140
0.742857
0.692857
9
14.555555
19.726526
53
false
false
0
0
0
0
0
0
0.111111
false
false
14
d702f05616a7670e7ca098672e96c17879f4db24
85,899,352,641
86606c9b89868d4b57aab41f6451c22a80394219
/get2018/src/meta/abhay/scf/assignment9/ShapeFactory.java
0a5206a15b7af22d5ccaf6431cb2e6c3fe989974
[]
no_license
meta-abhay-verma/GET2018
https://github.com/meta-abhay-verma/GET2018
d58a7b064f2edc5e7c6005db0926fc9c78943f8c
02095b0710f7b9164f17d5bd38846ac5e9f85f55
refs/heads/master
2020-03-22T23:23:51.114000
2018-10-15T09:27:25
2018-10-15T09:27:25
140,807,781
2
0
null
false
2018-10-31T10:35:34
2018-07-13T06:41:13
2018-10-15T09:27:41
2018-10-31T10:31:53
79,229
2
0
2
Java
false
null
package meta.abhay.scf.assignment9; import java.util.List; /** * Create a Factory class that will create shapes based on the ShapeType. * It will expose static method createShape that will take ShapeType, Point and List<Integer>. * Where Point will specify either starting point of the shape or center point, a generic way. * And the list of integers will display other parameters of the shape like for square only width, * circle only radius, rectangle length and breadth, so on. * * @author Abhay * */ public class ShapeFactory { /** * Generates a object of the type of shape given * @param shapeType Type of the shape to be created * @param point Coordinates of origin/center w.r.t shape * @param parameters list of parameters to pass * @return object of shape * @throws Exception Invalid shape type or parameters */ public static Shape createShape(Shape.ShapeType shapeType, Point point, List<Integer> parameters) throws Exception{ Shape shape; switch(shapeType){ case CIRCLE: if (parameters.size() < 1) throw new Exception("Invalid Parameters : 1 Parameter ecpected for circle"); shape = new Circle(point, parameters.get(0)); break; case RECTANGLE: if (parameters.size() < 2) throw new Exception("Invalid Parameters : 2 Parameter ecpected for rectangle"); shape = new Rectangle(point, parameters.get(0), parameters.get(1)); break; case REGULAR_POLYGON: if (parameters.size() < 2) throw new Exception("Invalid Parameters : 2 Parameter ecpected for regular polygon"); shape = new RegularPolygon(point, parameters.get(0), parameters.get(1)); break; case SQUARE: if (parameters.size() < 1) throw new Exception("Invalid Parameters : 1 Parameter ecpected for square"); shape = new Square(point, parameters.get(0)); break; case TRIANGLE: if (parameters.size() < 3) throw new Exception("Invalid Parameters : 3 Parameter ecpected for triangle"); shape = new Triangle(point, parameters.get(0), parameters.get(1), parameters.get(2)); break; default: throw new Exception("Invalid shape type"); } return shape; } }
UTF-8
Java
2,223
java
ShapeFactory.java
Java
[ { "context": "tangle length and breadth, so on.\r\n * \r\n * @author Abhay\r\n *\r\n */\r\npublic class ShapeFactory {\r\n\r\n\t/**\r\n\t ", "end": 523, "score": 0.91941899061203, "start": 518, "tag": "NAME", "value": "Abhay" } ]
null
[]
package meta.abhay.scf.assignment9; import java.util.List; /** * Create a Factory class that will create shapes based on the ShapeType. * It will expose static method createShape that will take ShapeType, Point and List<Integer>. * Where Point will specify either starting point of the shape or center point, a generic way. * And the list of integers will display other parameters of the shape like for square only width, * circle only radius, rectangle length and breadth, so on. * * @author Abhay * */ public class ShapeFactory { /** * Generates a object of the type of shape given * @param shapeType Type of the shape to be created * @param point Coordinates of origin/center w.r.t shape * @param parameters list of parameters to pass * @return object of shape * @throws Exception Invalid shape type or parameters */ public static Shape createShape(Shape.ShapeType shapeType, Point point, List<Integer> parameters) throws Exception{ Shape shape; switch(shapeType){ case CIRCLE: if (parameters.size() < 1) throw new Exception("Invalid Parameters : 1 Parameter ecpected for circle"); shape = new Circle(point, parameters.get(0)); break; case RECTANGLE: if (parameters.size() < 2) throw new Exception("Invalid Parameters : 2 Parameter ecpected for rectangle"); shape = new Rectangle(point, parameters.get(0), parameters.get(1)); break; case REGULAR_POLYGON: if (parameters.size() < 2) throw new Exception("Invalid Parameters : 2 Parameter ecpected for regular polygon"); shape = new RegularPolygon(point, parameters.get(0), parameters.get(1)); break; case SQUARE: if (parameters.size() < 1) throw new Exception("Invalid Parameters : 1 Parameter ecpected for square"); shape = new Square(point, parameters.get(0)); break; case TRIANGLE: if (parameters.size() < 3) throw new Exception("Invalid Parameters : 3 Parameter ecpected for triangle"); shape = new Triangle(point, parameters.get(0), parameters.get(1), parameters.get(2)); break; default: throw new Exception("Invalid shape type"); } return shape; } }
2,223
0.687359
0.678363
62
33.854839
32.222935
116
false
false
0
0
0
0
0
0
2.274194
false
false
14
d36ba09554d2094d419e1564b0ec13c89af15e89
14,113,262,537,681
647ec12ce50f06e7380fdbfb5b71e9e2d1ac03b4
/com.tencent.minihd.qq/assets/exlibs.1.jar/classes.jar/com/tencent/mobileqq/utils/SendMessageHandler$SendMessageRunnable.java
7155b97947c9ee35b80778ae50b7069200d80e2e
[]
no_license
tsuzcx/qq_apk
https://github.com/tsuzcx/qq_apk
0d5e792c3c7351ab781957bac465c55c505caf61
afe46ef5640d0ba6850cdefd3c11badbd725a3f6
refs/heads/main
2022-07-02T10:32:11.651000
2022-02-01T12:41:38
2022-02-01T12:41:38
453,860,108
36
9
null
false
2022-01-31T09:46:26
2022-01-31T02:43:22
2022-01-31T06:56:43
2022-01-31T09:46:26
167,304
0
1
1
Java
false
false
package com.tencent.mobileqq.utils; public class SendMessageHandler$SendMessageRunnable implements Runnable { public int a; public String a; public String[] a; public long c; public boolean c; public long d = 9223372036854775807L; public long e = 9223372036854775807L; public long f = -1L; public long g = -1L; public long h = -1L; public SendMessageHandler$SendMessageRunnable() { this.jdField_c_of_type_Boolean = false; this.jdField_c_of_type_Long = -1L; this.jdField_a_of_type_Int = -1; this.jdField_a_of_type_JavaLangString = ""; this.jdField_a_of_type_ArrayOfJavaLangString = new String[0]; } public void run() {} public String toString() { StringBuilder localStringBuilder = new StringBuilder(); localStringBuilder.append("{"); localStringBuilder.append("index:"); localStringBuilder.append(String.valueOf(this.jdField_a_of_type_Int)); localStringBuilder.append(",reason:"); localStringBuilder.append(this.jdField_a_of_type_JavaLangString); localStringBuilder.append(",startTime:"); localStringBuilder.append(String.valueOf(this.g - this.f)); localStringBuilder.append(",timeOut:"); localStringBuilder.append(String.valueOf(this.g - this.f + this.jdField_c_of_type_Long)); if (this.jdField_c_of_type_Boolean) { localStringBuilder.append(",duration:"); localStringBuilder.append(String.valueOf(this.h - this.g)); localStringBuilder.append(",error:"); localStringBuilder.append(String.valueOf(this.d)); if (this.e != 9223372036854775807L) { localStringBuilder.append(",serverReply:"); localStringBuilder.append(String.valueOf(this.e)); } } for (;;) { localStringBuilder.append("}"); return localStringBuilder.toString(); localStringBuilder.append(",status:RUNNING"); } } } /* Location: L:\local\mybackup\temp\qq_apk\com.tencent.minihd.qq\assets\exlibs.1.jar\classes.jar * Qualified Name: com.tencent.mobileqq.utils.SendMessageHandler.SendMessageRunnable * JD-Core Version: 0.7.0.1 */
UTF-8
Java
2,183
java
SendMessageHandler$SendMessageRunnable.java
Java
[]
null
[]
package com.tencent.mobileqq.utils; public class SendMessageHandler$SendMessageRunnable implements Runnable { public int a; public String a; public String[] a; public long c; public boolean c; public long d = 9223372036854775807L; public long e = 9223372036854775807L; public long f = -1L; public long g = -1L; public long h = -1L; public SendMessageHandler$SendMessageRunnable() { this.jdField_c_of_type_Boolean = false; this.jdField_c_of_type_Long = -1L; this.jdField_a_of_type_Int = -1; this.jdField_a_of_type_JavaLangString = ""; this.jdField_a_of_type_ArrayOfJavaLangString = new String[0]; } public void run() {} public String toString() { StringBuilder localStringBuilder = new StringBuilder(); localStringBuilder.append("{"); localStringBuilder.append("index:"); localStringBuilder.append(String.valueOf(this.jdField_a_of_type_Int)); localStringBuilder.append(",reason:"); localStringBuilder.append(this.jdField_a_of_type_JavaLangString); localStringBuilder.append(",startTime:"); localStringBuilder.append(String.valueOf(this.g - this.f)); localStringBuilder.append(",timeOut:"); localStringBuilder.append(String.valueOf(this.g - this.f + this.jdField_c_of_type_Long)); if (this.jdField_c_of_type_Boolean) { localStringBuilder.append(",duration:"); localStringBuilder.append(String.valueOf(this.h - this.g)); localStringBuilder.append(",error:"); localStringBuilder.append(String.valueOf(this.d)); if (this.e != 9223372036854775807L) { localStringBuilder.append(",serverReply:"); localStringBuilder.append(String.valueOf(this.e)); } } for (;;) { localStringBuilder.append("}"); return localStringBuilder.toString(); localStringBuilder.append(",status:RUNNING"); } } } /* Location: L:\local\mybackup\temp\qq_apk\com.tencent.minihd.qq\assets\exlibs.1.jar\classes.jar * Qualified Name: com.tencent.mobileqq.utils.SendMessageHandler.SendMessageRunnable * JD-Core Version: 0.7.0.1 */
2,183
0.66743
0.63628
69
29.724638
25.63336
106
false
false
0
0
0
0
0
0
0.637681
false
false
14
63b983b4bf9c11b50b2014e87476f461525196af
30,434,138,271,157
c0542546866385891c196b665d65a8bfa810f1a3
/decompiled/com/android/org/conscrypt/OpenSSLSignature.java
f9545c2720f2fc8265a82f6b5c57e6962d89418a
[]
no_license
auxor/android-wear-decompile
https://github.com/auxor/android-wear-decompile
6892f3564d316b1f436757b72690864936dd1a82
eb8ad0d8003c5a3b5623918c79334290f143a2a8
refs/heads/master
2016-09-08T02:32:48.433000
2015-10-12T02:17:27
2015-10-12T02:19:32
42,517,868
5
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.android.org.conscrypt; import java.security.InvalidKeyException; import java.security.InvalidParameterException; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SignatureException; import java.security.SignatureSpi; public class OpenSSLSignature extends SignatureSpi { private OpenSSLDigestContext ctx; private final EngineType engineType; private final long evpAlgorithm; private OpenSSLKey key; private boolean signing; private final byte[] singleByte; /* renamed from: com.android.org.conscrypt.OpenSSLSignature.1 */ static /* synthetic */ class AnonymousClass1 { static final /* synthetic */ int[] $SwitchMap$org$conscrypt$OpenSSLSignature$EngineType; static { $SwitchMap$org$conscrypt$OpenSSLSignature$EngineType = new int[EngineType.values().length]; try { $SwitchMap$org$conscrypt$OpenSSLSignature$EngineType[EngineType.RSA.ordinal()] = 1; } catch (NoSuchFieldError e) { } try { $SwitchMap$org$conscrypt$OpenSSLSignature$EngineType[EngineType.DSA.ordinal()] = 2; } catch (NoSuchFieldError e2) { } try { $SwitchMap$org$conscrypt$OpenSSLSignature$EngineType[EngineType.EC.ordinal()] = 3; } catch (NoSuchFieldError e3) { } } } private enum EngineType { RSA, DSA, EC } public static final class MD5RSA extends OpenSSLSignature { private static final long EVP_MD; static { EVP_MD = NativeCrypto.EVP_get_digestbyname("RSA-MD5"); } public MD5RSA() throws NoSuchAlgorithmException { super(EngineType.RSA, null); } } public static final class SHA1DSA extends OpenSSLSignature { private static final long EVP_MD; static { EVP_MD = NativeCrypto.EVP_get_digestbyname("DSA-SHA1"); } public SHA1DSA() throws NoSuchAlgorithmException { super(EngineType.DSA, null); } } public static final class SHA1ECDSA extends OpenSSLSignature { private static final long EVP_MD; static { EVP_MD = NativeCrypto.EVP_get_digestbyname("SHA1"); } public SHA1ECDSA() throws NoSuchAlgorithmException { super(EngineType.EC, null); } } public static final class SHA1RSA extends OpenSSLSignature { private static final long EVP_MD; static { EVP_MD = NativeCrypto.EVP_get_digestbyname("RSA-SHA1"); } public SHA1RSA() throws NoSuchAlgorithmException { super(EngineType.RSA, null); } } public static final class SHA224ECDSA extends OpenSSLSignature { private static final long EVP_MD; static { EVP_MD = NativeCrypto.EVP_get_digestbyname("SHA224"); } public SHA224ECDSA() throws NoSuchAlgorithmException { super(EngineType.EC, null); } } public static final class SHA224RSA extends OpenSSLSignature { private static final long EVP_MD; static { EVP_MD = NativeCrypto.EVP_get_digestbyname("RSA-SHA224"); } public SHA224RSA() throws NoSuchAlgorithmException { super(EngineType.RSA, null); } } public static final class SHA256ECDSA extends OpenSSLSignature { private static final long EVP_MD; static { EVP_MD = NativeCrypto.EVP_get_digestbyname("SHA256"); } public SHA256ECDSA() throws NoSuchAlgorithmException { super(EngineType.EC, null); } } public static final class SHA256RSA extends OpenSSLSignature { private static final long EVP_MD; static { EVP_MD = NativeCrypto.EVP_get_digestbyname("RSA-SHA256"); } public SHA256RSA() throws NoSuchAlgorithmException { super(EngineType.RSA, null); } } public static final class SHA384ECDSA extends OpenSSLSignature { private static final long EVP_MD; static { EVP_MD = NativeCrypto.EVP_get_digestbyname("SHA384"); } public SHA384ECDSA() throws NoSuchAlgorithmException { super(EngineType.EC, null); } } public static final class SHA384RSA extends OpenSSLSignature { private static final long EVP_MD; static { EVP_MD = NativeCrypto.EVP_get_digestbyname("RSA-SHA384"); } public SHA384RSA() throws NoSuchAlgorithmException { super(EngineType.RSA, null); } } public static final class SHA512ECDSA extends OpenSSLSignature { private static final long EVP_MD; static { EVP_MD = NativeCrypto.EVP_get_digestbyname("SHA512"); } public SHA512ECDSA() throws NoSuchAlgorithmException { super(EngineType.EC, null); } } public static final class SHA512RSA extends OpenSSLSignature { private static final long EVP_MD; static { EVP_MD = NativeCrypto.EVP_get_digestbyname("RSA-SHA512"); } public SHA512RSA() throws NoSuchAlgorithmException { super(EngineType.RSA, null); } } protected boolean engineVerify(byte[] r11) throws java.security.SignatureException { /* JADX: method processing error */ /* Error: java.lang.NullPointerException at jadx.core.dex.visitors.ssa.SSATransform.placePhi(SSATransform.java:82) at jadx.core.dex.visitors.ssa.SSATransform.process(SSATransform.java:50) at jadx.core.dex.visitors.ssa.SSATransform.visit(SSATransform.java:42) at jadx.core.dex.visitors.DepthTraversal.visit(DepthTraversal.java:31) at jadx.core.dex.visitors.DepthTraversal.visit(DepthTraversal.java:17) at jadx.core.ProcessClass.process(ProcessClass.java:37) at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:281) at jadx.api.JavaClass.decompile(JavaClass.java:59) at jadx.api.JadxDecompiler$1.run(JadxDecompiler.java:161) */ /* r10 = this; r8 = 1; r9 = 0; r0 = r10.key; if (r0 != 0) goto L_0x000e; L_0x0006: r0 = new java.security.SignatureException; r1 = "Need DSA or RSA public key"; r0.<init>(r1); throw r0; L_0x000e: r0 = r10.ctx; Catch:{ Exception -> 0x0026, all -> 0x002c } r2 = 0; Catch:{ Exception -> 0x0026, all -> 0x002c } r3 = r11.length; Catch:{ Exception -> 0x0026, all -> 0x002c } r1 = r10.key; Catch:{ Exception -> 0x0026, all -> 0x002c } r4 = r1.getPkeyContext(); Catch:{ Exception -> 0x0026, all -> 0x002c } r1 = r11; Catch:{ Exception -> 0x0026, all -> 0x002c } r7 = com.android.org.conscrypt.NativeCrypto.EVP_VerifyFinal(r0, r1, r2, r3, r4); Catch:{ Exception -> 0x0026, all -> 0x002c } if (r7 != r8) goto L_0x0024; L_0x001f: r0 = r8; L_0x0020: r10.resetContext(); L_0x0023: return r0; L_0x0024: r0 = r9; goto L_0x0020; L_0x0026: r6 = move-exception; r10.resetContext(); r0 = r9; goto L_0x0023; L_0x002c: r0 = move-exception; r10.resetContext(); throw r0; */ throw new UnsupportedOperationException("Method not decompiled: com.android.org.conscrypt.OpenSSLSignature.engineVerify(byte[]):boolean"); } private OpenSSLSignature(long algorithm, EngineType engineType) throws NoSuchAlgorithmException { this.singleByte = new byte[1]; this.engineType = engineType; this.evpAlgorithm = algorithm; } private final void resetContext() { OpenSSLDigestContext ctxLocal = new OpenSSLDigestContext(NativeCrypto.EVP_MD_CTX_create()); NativeCrypto.EVP_MD_CTX_init(ctxLocal); if (this.signing) { enableDSASignatureNonceHardeningIfApplicable(); NativeCrypto.EVP_SignInit(ctxLocal, this.evpAlgorithm); } else { NativeCrypto.EVP_VerifyInit(ctxLocal, this.evpAlgorithm); } this.ctx = ctxLocal; } protected void engineUpdate(byte input) { this.singleByte[0] = input; engineUpdate(this.singleByte, 0, 1); } protected void engineUpdate(byte[] input, int offset, int len) { OpenSSLDigestContext ctxLocal = this.ctx; if (this.signing) { NativeCrypto.EVP_SignUpdate(ctxLocal, input, offset, len); } else { NativeCrypto.EVP_VerifyUpdate(ctxLocal, input, offset, len); } } protected Object engineGetParameter(String param) throws InvalidParameterException { return null; } private void checkEngineType(OpenSSLKey pkey) throws InvalidKeyException { int pkeyType = NativeCrypto.EVP_PKEY_type(pkey.getPkeyContext()); switch (AnonymousClass1.$SwitchMap$org$conscrypt$OpenSSLSignature$EngineType[this.engineType.ordinal()]) { case NativeCrypto.SSL_kRSA /*1*/: if (pkeyType != 6) { throw new InvalidKeyException("Signature initialized as " + this.engineType + " (not RSA)"); } case NativeCrypto.SSL_kDHr /*2*/: if (pkeyType != NativeCrypto.EVP_PKEY_DSA) { throw new InvalidKeyException("Signature initialized as " + this.engineType + " (not DSA)"); } case NativeCrypto.SSL_ST_OK /*3*/: if (pkeyType != NativeCrypto.EVP_PKEY_EC) { throw new InvalidKeyException("Signature initialized as " + this.engineType + " (not EC)"); } default: throw new InvalidKeyException("Key must be of type " + this.engineType); } } private void initInternal(OpenSSLKey newKey, boolean signing) throws InvalidKeyException { checkEngineType(newKey); this.key = newKey; this.signing = signing; resetContext(); } protected void engineInitSign(PrivateKey privateKey) throws InvalidKeyException { initInternal(OpenSSLKey.fromPrivateKey(privateKey), true); } private void enableDSASignatureNonceHardeningIfApplicable() { OpenSSLKey key = this.key; switch (AnonymousClass1.$SwitchMap$org$conscrypt$OpenSSLSignature$EngineType[this.engineType.ordinal()]) { case NativeCrypto.SSL_kDHr /*2*/: NativeCrypto.set_DSA_flag_nonce_from_hash(key.getPkeyContext()); case NativeCrypto.SSL_ST_OK /*3*/: NativeCrypto.EC_KEY_set_nonce_from_hash(key.getPkeyContext(), true); default: } } protected void engineInitVerify(PublicKey publicKey) throws InvalidKeyException { initInternal(OpenSSLKey.fromPublicKey(publicKey), false); } protected void engineSetParameter(String param, Object value) throws InvalidParameterException { } protected byte[] engineSign() throws SignatureException { if (this.key == null) { throw new SignatureException("Need DSA or RSA or EC private key"); } try { byte[] buffer = new byte[NativeCrypto.EVP_PKEY_size(this.key.getPkeyContext())]; int bytesWritten = NativeCrypto.EVP_SignFinal(this.ctx, buffer, 0, this.key.getPkeyContext()); byte[] signature = new byte[bytesWritten]; System.arraycopy(buffer, 0, signature, 0, bytesWritten); resetContext(); return signature; } catch (Exception ex) { throw new SignatureException(ex); } catch (Throwable th) { resetContext(); } } }
UTF-8
Java
11,862
java
OpenSSLSignature.java
Java
[]
null
[]
package com.android.org.conscrypt; import java.security.InvalidKeyException; import java.security.InvalidParameterException; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SignatureException; import java.security.SignatureSpi; public class OpenSSLSignature extends SignatureSpi { private OpenSSLDigestContext ctx; private final EngineType engineType; private final long evpAlgorithm; private OpenSSLKey key; private boolean signing; private final byte[] singleByte; /* renamed from: com.android.org.conscrypt.OpenSSLSignature.1 */ static /* synthetic */ class AnonymousClass1 { static final /* synthetic */ int[] $SwitchMap$org$conscrypt$OpenSSLSignature$EngineType; static { $SwitchMap$org$conscrypt$OpenSSLSignature$EngineType = new int[EngineType.values().length]; try { $SwitchMap$org$conscrypt$OpenSSLSignature$EngineType[EngineType.RSA.ordinal()] = 1; } catch (NoSuchFieldError e) { } try { $SwitchMap$org$conscrypt$OpenSSLSignature$EngineType[EngineType.DSA.ordinal()] = 2; } catch (NoSuchFieldError e2) { } try { $SwitchMap$org$conscrypt$OpenSSLSignature$EngineType[EngineType.EC.ordinal()] = 3; } catch (NoSuchFieldError e3) { } } } private enum EngineType { RSA, DSA, EC } public static final class MD5RSA extends OpenSSLSignature { private static final long EVP_MD; static { EVP_MD = NativeCrypto.EVP_get_digestbyname("RSA-MD5"); } public MD5RSA() throws NoSuchAlgorithmException { super(EngineType.RSA, null); } } public static final class SHA1DSA extends OpenSSLSignature { private static final long EVP_MD; static { EVP_MD = NativeCrypto.EVP_get_digestbyname("DSA-SHA1"); } public SHA1DSA() throws NoSuchAlgorithmException { super(EngineType.DSA, null); } } public static final class SHA1ECDSA extends OpenSSLSignature { private static final long EVP_MD; static { EVP_MD = NativeCrypto.EVP_get_digestbyname("SHA1"); } public SHA1ECDSA() throws NoSuchAlgorithmException { super(EngineType.EC, null); } } public static final class SHA1RSA extends OpenSSLSignature { private static final long EVP_MD; static { EVP_MD = NativeCrypto.EVP_get_digestbyname("RSA-SHA1"); } public SHA1RSA() throws NoSuchAlgorithmException { super(EngineType.RSA, null); } } public static final class SHA224ECDSA extends OpenSSLSignature { private static final long EVP_MD; static { EVP_MD = NativeCrypto.EVP_get_digestbyname("SHA224"); } public SHA224ECDSA() throws NoSuchAlgorithmException { super(EngineType.EC, null); } } public static final class SHA224RSA extends OpenSSLSignature { private static final long EVP_MD; static { EVP_MD = NativeCrypto.EVP_get_digestbyname("RSA-SHA224"); } public SHA224RSA() throws NoSuchAlgorithmException { super(EngineType.RSA, null); } } public static final class SHA256ECDSA extends OpenSSLSignature { private static final long EVP_MD; static { EVP_MD = NativeCrypto.EVP_get_digestbyname("SHA256"); } public SHA256ECDSA() throws NoSuchAlgorithmException { super(EngineType.EC, null); } } public static final class SHA256RSA extends OpenSSLSignature { private static final long EVP_MD; static { EVP_MD = NativeCrypto.EVP_get_digestbyname("RSA-SHA256"); } public SHA256RSA() throws NoSuchAlgorithmException { super(EngineType.RSA, null); } } public static final class SHA384ECDSA extends OpenSSLSignature { private static final long EVP_MD; static { EVP_MD = NativeCrypto.EVP_get_digestbyname("SHA384"); } public SHA384ECDSA() throws NoSuchAlgorithmException { super(EngineType.EC, null); } } public static final class SHA384RSA extends OpenSSLSignature { private static final long EVP_MD; static { EVP_MD = NativeCrypto.EVP_get_digestbyname("RSA-SHA384"); } public SHA384RSA() throws NoSuchAlgorithmException { super(EngineType.RSA, null); } } public static final class SHA512ECDSA extends OpenSSLSignature { private static final long EVP_MD; static { EVP_MD = NativeCrypto.EVP_get_digestbyname("SHA512"); } public SHA512ECDSA() throws NoSuchAlgorithmException { super(EngineType.EC, null); } } public static final class SHA512RSA extends OpenSSLSignature { private static final long EVP_MD; static { EVP_MD = NativeCrypto.EVP_get_digestbyname("RSA-SHA512"); } public SHA512RSA() throws NoSuchAlgorithmException { super(EngineType.RSA, null); } } protected boolean engineVerify(byte[] r11) throws java.security.SignatureException { /* JADX: method processing error */ /* Error: java.lang.NullPointerException at jadx.core.dex.visitors.ssa.SSATransform.placePhi(SSATransform.java:82) at jadx.core.dex.visitors.ssa.SSATransform.process(SSATransform.java:50) at jadx.core.dex.visitors.ssa.SSATransform.visit(SSATransform.java:42) at jadx.core.dex.visitors.DepthTraversal.visit(DepthTraversal.java:31) at jadx.core.dex.visitors.DepthTraversal.visit(DepthTraversal.java:17) at jadx.core.ProcessClass.process(ProcessClass.java:37) at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:281) at jadx.api.JavaClass.decompile(JavaClass.java:59) at jadx.api.JadxDecompiler$1.run(JadxDecompiler.java:161) */ /* r10 = this; r8 = 1; r9 = 0; r0 = r10.key; if (r0 != 0) goto L_0x000e; L_0x0006: r0 = new java.security.SignatureException; r1 = "Need DSA or RSA public key"; r0.<init>(r1); throw r0; L_0x000e: r0 = r10.ctx; Catch:{ Exception -> 0x0026, all -> 0x002c } r2 = 0; Catch:{ Exception -> 0x0026, all -> 0x002c } r3 = r11.length; Catch:{ Exception -> 0x0026, all -> 0x002c } r1 = r10.key; Catch:{ Exception -> 0x0026, all -> 0x002c } r4 = r1.getPkeyContext(); Catch:{ Exception -> 0x0026, all -> 0x002c } r1 = r11; Catch:{ Exception -> 0x0026, all -> 0x002c } r7 = com.android.org.conscrypt.NativeCrypto.EVP_VerifyFinal(r0, r1, r2, r3, r4); Catch:{ Exception -> 0x0026, all -> 0x002c } if (r7 != r8) goto L_0x0024; L_0x001f: r0 = r8; L_0x0020: r10.resetContext(); L_0x0023: return r0; L_0x0024: r0 = r9; goto L_0x0020; L_0x0026: r6 = move-exception; r10.resetContext(); r0 = r9; goto L_0x0023; L_0x002c: r0 = move-exception; r10.resetContext(); throw r0; */ throw new UnsupportedOperationException("Method not decompiled: com.android.org.conscrypt.OpenSSLSignature.engineVerify(byte[]):boolean"); } private OpenSSLSignature(long algorithm, EngineType engineType) throws NoSuchAlgorithmException { this.singleByte = new byte[1]; this.engineType = engineType; this.evpAlgorithm = algorithm; } private final void resetContext() { OpenSSLDigestContext ctxLocal = new OpenSSLDigestContext(NativeCrypto.EVP_MD_CTX_create()); NativeCrypto.EVP_MD_CTX_init(ctxLocal); if (this.signing) { enableDSASignatureNonceHardeningIfApplicable(); NativeCrypto.EVP_SignInit(ctxLocal, this.evpAlgorithm); } else { NativeCrypto.EVP_VerifyInit(ctxLocal, this.evpAlgorithm); } this.ctx = ctxLocal; } protected void engineUpdate(byte input) { this.singleByte[0] = input; engineUpdate(this.singleByte, 0, 1); } protected void engineUpdate(byte[] input, int offset, int len) { OpenSSLDigestContext ctxLocal = this.ctx; if (this.signing) { NativeCrypto.EVP_SignUpdate(ctxLocal, input, offset, len); } else { NativeCrypto.EVP_VerifyUpdate(ctxLocal, input, offset, len); } } protected Object engineGetParameter(String param) throws InvalidParameterException { return null; } private void checkEngineType(OpenSSLKey pkey) throws InvalidKeyException { int pkeyType = NativeCrypto.EVP_PKEY_type(pkey.getPkeyContext()); switch (AnonymousClass1.$SwitchMap$org$conscrypt$OpenSSLSignature$EngineType[this.engineType.ordinal()]) { case NativeCrypto.SSL_kRSA /*1*/: if (pkeyType != 6) { throw new InvalidKeyException("Signature initialized as " + this.engineType + " (not RSA)"); } case NativeCrypto.SSL_kDHr /*2*/: if (pkeyType != NativeCrypto.EVP_PKEY_DSA) { throw new InvalidKeyException("Signature initialized as " + this.engineType + " (not DSA)"); } case NativeCrypto.SSL_ST_OK /*3*/: if (pkeyType != NativeCrypto.EVP_PKEY_EC) { throw new InvalidKeyException("Signature initialized as " + this.engineType + " (not EC)"); } default: throw new InvalidKeyException("Key must be of type " + this.engineType); } } private void initInternal(OpenSSLKey newKey, boolean signing) throws InvalidKeyException { checkEngineType(newKey); this.key = newKey; this.signing = signing; resetContext(); } protected void engineInitSign(PrivateKey privateKey) throws InvalidKeyException { initInternal(OpenSSLKey.fromPrivateKey(privateKey), true); } private void enableDSASignatureNonceHardeningIfApplicable() { OpenSSLKey key = this.key; switch (AnonymousClass1.$SwitchMap$org$conscrypt$OpenSSLSignature$EngineType[this.engineType.ordinal()]) { case NativeCrypto.SSL_kDHr /*2*/: NativeCrypto.set_DSA_flag_nonce_from_hash(key.getPkeyContext()); case NativeCrypto.SSL_ST_OK /*3*/: NativeCrypto.EC_KEY_set_nonce_from_hash(key.getPkeyContext(), true); default: } } protected void engineInitVerify(PublicKey publicKey) throws InvalidKeyException { initInternal(OpenSSLKey.fromPublicKey(publicKey), false); } protected void engineSetParameter(String param, Object value) throws InvalidParameterException { } protected byte[] engineSign() throws SignatureException { if (this.key == null) { throw new SignatureException("Need DSA or RSA or EC private key"); } try { byte[] buffer = new byte[NativeCrypto.EVP_PKEY_size(this.key.getPkeyContext())]; int bytesWritten = NativeCrypto.EVP_SignFinal(this.ctx, buffer, 0, this.key.getPkeyContext()); byte[] signature = new byte[bytesWritten]; System.arraycopy(buffer, 0, signature, 0, bytesWritten); resetContext(); return signature; } catch (Exception ex) { throw new SignatureException(ex); } catch (Throwable th) { resetContext(); } } }
11,862
0.624094
0.598466
348
33.086208
30.284351
146
false
false
0
0
0
0
0
0
0.543103
false
false
14
a3f639cf10b1c09f5943c897b9a18dda51500fa3
26,456,998,605,346
b9a89c76faf85e618be5cfad7f44c3c727db981c
/src/com/elikill58/negativity/sponge/protocols/FastEatProtocol.java
fbc367936f596f728e1a354b7d76892247ee77aa
[]
no_license
RedNesto/Negativity
https://github.com/RedNesto/Negativity
97abb5c9a7c7659145afacb644a776a0ff000611
c45252fb311ffa664ddbf984093c23bfe4c21913
refs/heads/master
2021-08-11T02:30:43.579000
2021-07-25T13:59:46
2021-07-25T13:59:46
178,409,930
2
0
null
true
2019-03-29T13:24:52
2019-03-29T13:24:51
2019-03-26T16:57:40
2019-03-22T16:19:57
810
0
0
0
null
false
null
package com.elikill58.negativity.sponge.protocols; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.filter.cause.First; import org.spongepowered.api.event.item.inventory.UseItemStackEvent; import org.spongepowered.api.item.ItemTypes; import com.elikill58.negativity.sponge.SpongeNegativityPlayer; import com.elikill58.negativity.universal.Cheat; import com.elikill58.negativity.universal.CheatKeys; import com.elikill58.negativity.universal.FlyingReason; public class FastEatProtocol extends Cheat { public FastEatProtocol() { super(CheatKeys.FAST_EAT, true, ItemTypes.COOKED_BEEF, CheatCategory.PLAYER, true, "fasteat", "autoeat"); } @Listener public void onItemConsume(UseItemStackEvent.Finish e, @First Player p) { SpongeNegativityPlayer np = SpongeNegativityPlayer.getNegativityPlayer(p); np.flyingReason = FlyingReason.EAT; np.eatMaterial = e.getItemStackInUse().getType(); } }
UTF-8
Java
990
java
FastEatProtocol.java
Java
[ { "context": "package com.elikill58.negativity.sponge.protocols;\n\nimport org.spongepo", "end": 21, "score": 0.633939266204834, "start": 19, "tag": "USERNAME", "value": "58" }, { "context": "spongepowered.api.item.ItemTypes;\n\nimport com.elikill58.negativity.sponge.SpongeNegativityPlayer;\nimport ", "end": 345, "score": 0.6129605770111084, "start": 340, "tag": "USERNAME", "value": "ill58" }, { "context": ".sponge.SpongeNegativityPlayer;\nimport com.elikill58.negativity.universal.Cheat;\nimport com.elikill58", "end": 407, "score": 0.5069008469581604, "start": 406, "tag": "USERNAME", "value": "5" } ]
null
[]
package com.elikill58.negativity.sponge.protocols; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.filter.cause.First; import org.spongepowered.api.event.item.inventory.UseItemStackEvent; import org.spongepowered.api.item.ItemTypes; import com.elikill58.negativity.sponge.SpongeNegativityPlayer; import com.elikill58.negativity.universal.Cheat; import com.elikill58.negativity.universal.CheatKeys; import com.elikill58.negativity.universal.FlyingReason; public class FastEatProtocol extends Cheat { public FastEatProtocol() { super(CheatKeys.FAST_EAT, true, ItemTypes.COOKED_BEEF, CheatCategory.PLAYER, true, "fasteat", "autoeat"); } @Listener public void onItemConsume(UseItemStackEvent.Finish e, @First Player p) { SpongeNegativityPlayer np = SpongeNegativityPlayer.getNegativityPlayer(p); np.flyingReason = FlyingReason.EAT; np.eatMaterial = e.getItemStackInUse().getType(); } }
990
0.816162
0.806061
26
37.076923
29.478706
107
false
false
0
0
0
0
0
0
1.307692
false
false
14
8d6ce1292440e0cacf6c9927ce913238333fb629
2,628,520,049,725
8929080c3ae0fe6ebc57cdcfbc8f04f8f3cad413
/src/test/java/com/zeroten/javales/classObject/ClassThisTest.java
5858b7b13d63aa10e18352d13ace4b4586a737ff
[]
no_license
renshaoqi/JavaStudyDemo
https://github.com/renshaoqi/JavaStudyDemo
3277db1b70e936e062c2141465437c47ea783b17
de59abc86e24ca424eff0e51d2ee26197b93aec2
refs/heads/master
2020-11-24T18:03:32.951000
2020-01-03T09:51:15
2020-01-03T09:51:15
228,283,476
1
0
null
false
2020-10-13T18:14:43
2019-12-16T02:05:57
2020-01-03T09:51:51
2020-10-13T18:14:43
59
1
0
1
Java
false
false
package com.zeroten.javales.classObject; import org.testng.annotations.Test; public class ClassThisTest { private int index; // 构造器 public ClassThisTest () {} // 实例方法 public void println(String name) { System.out.println(this.index + ".hello" + name); } // 可变参数 public void println(int... nums) { if (nums == null) { System.out.println("si null"); } if (nums.length == 0) { System.out.println("param length is zero"); } System.out.println("..............."); for (int n = 0; n < nums.length; n++) { System.out.println(nums[n]); } } @Test public void testThis() { ClassThisTest obj = new ClassThisTest(); // obj.println("work"); // obj.println(); // obj.println(1); obj.println(1, 3, 5, 7); } }
UTF-8
Java
941
java
ClassThisTest.java
Java
[]
null
[]
package com.zeroten.javales.classObject; import org.testng.annotations.Test; public class ClassThisTest { private int index; // 构造器 public ClassThisTest () {} // 实例方法 public void println(String name) { System.out.println(this.index + ".hello" + name); } // 可变参数 public void println(int... nums) { if (nums == null) { System.out.println("si null"); } if (nums.length == 0) { System.out.println("param length is zero"); } System.out.println("..............."); for (int n = 0; n < nums.length; n++) { System.out.println(nums[n]); } } @Test public void testThis() { ClassThisTest obj = new ClassThisTest(); // obj.println("work"); // obj.println(); // obj.println(1); obj.println(1, 3, 5, 7); } }
941
0.49728
0.489663
36
23.527779
17.127766
57
false
false
0
0
0
0
0
0
0.5
false
false
14
4fbdb660e3af32b24be1a54a1fe83a89047e3281
3,891,240,431,010
5bb439afe8d8da430824988a22e777220c00f69a
/src/com/daffodil/ssb/model/EmployeeCodeMap.java
82d5bc77124750188ca1d0026bea45660a5aef7e
[]
no_license
moshiurse/SpringDemo
https://github.com/moshiurse/SpringDemo
59fc969c09936d96e40b4bdf520da9a96d593206
4eaa53ce88890e71bae19fce342fc4f161498dc5
refs/heads/master
2021-07-20T11:22:33.144000
2017-10-26T00:58:38
2017-10-26T00:58:38
99,309,364
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.daffodil.ssb.model; import javax.persistence.Entity; import javax.persistence.Table; import org.springframework.stereotype.Controller; @Entity @Table(name="acc_emp_acc_code_map") public class EmployeeCodeMap { private int id; private String employeeId; private String accountCode; private String codeType; private int companyId; private String createdBy; }
UTF-8
Java
382
java
EmployeeCodeMap.java
Java
[]
null
[]
package com.daffodil.ssb.model; import javax.persistence.Entity; import javax.persistence.Table; import org.springframework.stereotype.Controller; @Entity @Table(name="acc_emp_acc_code_map") public class EmployeeCodeMap { private int id; private String employeeId; private String accountCode; private String codeType; private int companyId; private String createdBy; }
382
0.793194
0.793194
19
19.105263
14.927526
49
false
false
0
0
0
0
0
0
0.894737
false
false
14
485365dc45fa7746449338ce0d609e01dc14a8f0
24,223,615,616,539
e75afa002edb86b429e3d22c8fa42ba596e35cb5
/src/tptpaxsel/Main.java
347774d1cdea8f597147d5f591250a2f2bc71093
[]
no_license
dkuehlwein/tptpaxsel
https://github.com/dkuehlwein/tptpaxsel
ce06ff0aa358430970cb760439ff6e32ba02a6d5
4096d23e7bc989912cb5a6f3e5e6ffbda7037d8a
refs/heads/master
2021-01-11T11:01:42.122000
2010-12-17T10:36:18
2010-12-17T10:36:18
32,890,814
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package tptpaxsel; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import tptpaxsel.PSA.PSADivvy; import tptpaxsel.PSA.PSAExistential; import tptpaxsel.PSA.PSAPremiseGrowth; import tptpaxsel.PSA.PSARandomize; import tptpaxsel.PSA.PSASimple; import tptpaxsel.example.Example; /** * @author Daniel Kühlwein * */ public class Main { static private PrintStream stdOut = System.out; static private double weightObligationEdges = 1.0; static private double weightAPRILS = 0.0; static private double weightNaproche = 1.0; static private int maxTime = 300; /* Currently not used!!! */ /** * Hack your tests here. * Supported provers are E ("E") and Vampire ("V"). The Vampire binary must be in /lib/VAMPIRE * * @param args */ public static void main(String[] args) { // AtpApi aaa = new AtpApi("test/javanaproche/","test/javanaproche/obligations.nap"); // aaa.setSimple(0.0, 0.0, 1.0, "E", 3, 1); // aaa.runSingleByFilename("1-apod(1)-holds(apod(1), 10, 0).input"); Example example; Obligations obligations; PSASimple one; PSASimple two; PSAPremiseGrowth premiseGrowth; PSADivvy divvy; PSAExistential ex = new PSAExistential(); PSARandomize random = new PSARandomize(); /* Copy pasteable foobar */ String[] provers = new String[2]; provers[0] = "V"; provers[1] = "E"; String[] proverV = new String[1]; proverV[0] = "V"; premiseGrowth = new PSAPremiseGrowth(5, "plus", 10, 5, 0, provers); divvy = new PSADivvy(2, 5, provers, true); one = new PSASimple("V",300); two = new PSASimple("E",5); /* End Copy pasteable foobar */ /* Start tests */ example = new Example("Euclid"); //example.runAprils(); obligations = example.obligations; //ex.deleteExistentialPremises(obligations); //random.changeCheckSettings(obligations); //Default values are weightAPRILS = 1; weightObligationGraph=1; maxTime = 5 * 1000 obligations.weightAPRILS = 1.0; obligations.weightNaproche = 1.0; obligations.weightObligationGraph = 1.0; obligations.maxTime = maxTime; //PSA Settings premiseGrowth = new PSAPremiseGrowth(200, "plus", 10, 1, 0, provers); // Log System.out.println("Example: "+example.name); premiseGrowth.changeCheckSettings(obligations); obligations.checkObligations(); /* Write machine readable stats Start */ Statistics.printMachineStats(obligations, "foo.stats"); Statistics.printProcessTimeline(obligations, 600, "foo.timeline"); /* Write machine readable stats End */ // /* Start tests */ // example = new Example("Euclid"); // //example.runAprils(); // obligations = example.obligations; // //ex.deleteExistentialPremises(obligations); // //random.changeCheckSettings(obligations); // //Default values are weightAPRILS = 1; weightObligationGraph=1; maxTime = 5 * 1000 // obligations.weightAPRILS = 1.0; // obligations.weightNaproche = 1.0; // obligations.weightObligationGraph = 1.0; // obligations.maxTime = maxTime; // //PSA Settings // divvy = new PSADivvy(2, 5, proverV, true); // // Log // System.out.println("Example: "+example.name); // divvy.changeCheckSettings(obligations); // obligations.checkObligations(); // /* Write machine readable stats Start */ // Statistics.printMachineStats(obligations, "EuclidDivvyV2tries5secN1A1.stats"); // Statistics.printProcessTimeline(obligations, 600, "EuclidDivvyV2tries5secN1A1.timeline"); // /* Write machine readable stats End */ // // // /* Start tests */ // example = new Example("Euclid"); // //example.runAprils(); // obligations = example.obligations; // //ex.deleteExistentialPremises(obligations); // //random.changeCheckSettings(obligations); // //Default values are weightAPRILS = 1; weightObligationGraph=1; maxTime = 5 * 1000 // obligations.weightAPRILS = 1.0; // obligations.weightNaproche = 1.0; // obligations.weightObligationGraph = 1.0; // obligations.maxTime = maxTime; // //PSA Settings // premiseGrowth = new PSAPremiseGrowth(10, "plus", 10, 5, 0, provers); // // Log // System.out.println("Example: "+example.name); // premiseGrowth.changeCheckSettings(obligations); // obligations.checkObligations(); // /* Write machine readable stats Start */ // Statistics.printMachineStats(obligations, "EuclidVE10plus10time5sN1A1.stats"); // Statistics.printProcessTimeline(obligations, 600, "EuclidVE10plus10time5sN1A1.timeline"); // /* Write machine readable stats End */ // // /* Start tests */ // example = new Example("Euclid"); // //example.runAprils(); // obligations = example.obligations; // //ex.deleteExistentialPremises(obligations); // //random.changeCheckSettings(obligations); // //Default values are weightAPRILS = 1; weightObligationGraph=1; maxTime = 5 * 1000 // obligations.weightAPRILS = 1.0; // obligations.weightNaproche = 1.0; // obligations.weightObligationGraph = 1.0; // obligations.maxTime = maxTime; // //PSA Settings // divvy = new PSADivvy(2, 5, provers, true); // // Log // System.out.println("Example: "+example.name); // divvy.changeCheckSettings(obligations); // obligations.checkObligations(); // /* Write machine readable stats Start */ // Statistics.printMachineStats(obligations, "EuclidDivvyVE2tries5secN1A1.stats"); // Statistics.printProcessTimeline(obligations, 600, "EuclidDivvyVE2tries5secN1A1.timeline"); // /* Write machine readable stats End */ // // /* Start tests */ // example = new Example("Mizar"); // //example.runAprils(); // obligations = example.obligations; // //ex.deleteExistentialPremises(obligations); // //random.changeCheckSettings(obligations); // //Default values are weightAPRILS = 1; weightObligationGraph=1; maxTime = 5 * 1000 // obligations.weightAPRILS = 0.0; // obligations.weightNaproche = 1.0; // obligations.weightObligationGraph = 1.0; // obligations.maxTime = maxTime; // //PSA Settings // premiseGrowth = new PSAPremiseGrowth(10, "plus", 10, 5, 0, proverV); // // Log // System.out.println("Example: "+example.name); // premiseGrowth.changeCheckSettings(obligations); // obligations.checkObligations(); // /* Write machine readable stats Start */ // Statistics.printMachineStats(obligations, "MizarV10plus10time5sN1A0.stats"); // Statistics.printProcessTimeline(obligations, 600, "MizarV10plus10time5sN1A0.timeline"); // /* Write machine readable stats End */ // // /* Start tests */ // example = new Example("Mizar"); // //example.runAprils(); // obligations = example.obligations; // //ex.deleteExistentialPremises(obligations); // //random.changeCheckSettings(obligations); // //Default values are weightAPRILS = 1; weightObligationGraph=1; maxTime = 5 * 1000 // obligations.weightAPRILS = 1.0; // obligations.weightNaproche = 0.0; // obligations.weightObligationGraph = 1.0; // obligations.maxTime = maxTime; // //PSA Settings // premiseGrowth = new PSAPremiseGrowth(10, "plus", 10, 5, 0, proverV); // // Log // System.out.println("Example: "+example.name); // premiseGrowth.changeCheckSettings(obligations); // obligations.checkObligations(); // /* Write machine readable stats Start */ // Statistics.printMachineStats(obligations, "MizarV10plus10time5sN0A1.stats"); // Statistics.printProcessTimeline(obligations, 600, "MizarV10plus10time5sN0A1.timeline"); // /* Write machine readable stats End */ // // /* Start tests */ // example = new Example("MizarHard"); // //example.runAprils(); // obligations = example.obligations; // //ex.deleteExistentialPremises(obligations); // //random.changeCheckSettings(obligations); // //Default values are weightAPRILS = 1; weightObligationGraph=1; maxTime = 5 * 1000 // obligations.weightAPRILS = 0.0; // obligations.weightNaproche = 1.0; // obligations.weightObligationGraph = 1.0; // obligations.maxTime = maxTime; // //PSA Settings // premiseGrowth = new PSAPremiseGrowth(10, "plus", 10, 5, 0, proverV); // // Log // System.out.println("Example: "+example.name); // premiseGrowth.changeCheckSettings(obligations); // obligations.checkObligations(); // /* Write machine readable stats Start */ // Statistics.printMachineStats(obligations, "MizarHardV10plus10time5sN1A0.stats"); // Statistics.printProcessTimeline(obligations, 600, "MizarHardV10plus10time5sN1A0.timeline"); // /* Write machine readable stats End */ // // /* Start tests */ // example = new Example("MizarHard"); // //example.runAprils(); // obligations = example.obligations; // //ex.deleteExistentialPremises(obligations); // //random.changeCheckSettings(obligations); // //Default values are weightAPRILS = 1; weightObligationGraph=1; maxTime = 5 * 1000 // obligations.weightAPRILS = 1.0; // obligations.weightNaproche = 0.0; // obligations.weightObligationGraph = 1.0; // obligations.maxTime = maxTime; // //PSA Settings // premiseGrowth = new PSAPremiseGrowth(10, "plus", 10, 5, 0, proverV); // // Log // System.out.println("Example: "+example.name); // premiseGrowth.changeCheckSettings(obligations); // obligations.checkObligations(); // /* Write machine readable stats Start */ // Statistics.printMachineStats(obligations, "MizarHardV10plus10time5sN0A1.stats"); // Statistics.printProcessTimeline(obligations, 600, "MizarHardV10plus10time5sN0A1.timeline"); // /* Write machine readable stats End */ } /* Redirect output stream to file */ static public void setLog(String File) { try { System.setOut(new PrintStream(new FileOutputStream(File))); } catch (FileNotFoundException ex) { System.out.println("Cannot direct StdOut to file "+File); ex.printStackTrace(); return; } } static public void stdOutReset() { System.setOut(stdOut); } }
UTF-8
Java
9,842
java
Main.java
Java
[ { "context": "import tptpaxsel.example.Example;\n\n\n/**\n * @author Daniel Kühlwein\n *\n */\npublic class Main {\n\t\n\tstatic private Prin", "end": 373, "score": 0.9998785853385925, "start": 358, "tag": "NAME", "value": "Daniel Kühlwein" }, { "context": "* Start tests */\n// example = new Example(\"Mizar\");\n//\t\t//example.runAprils();\n//\t\tobligations = e", "end": 5512, "score": 0.9985865950584412, "start": 5507, "tag": "NAME", "value": "Mizar" }, { "context": "* Start tests */\n// example = new Example(\"Mizar\");\n//\t\t//example.runAprils();\n//\t\tobligations = e", "end": 6493, "score": 0.9983999729156494, "start": 6488, "tag": "NAME", "value": "Mizar" }, { "context": "* Start tests */\n// example = new Example(\"MizarHard\");\n//\t\t//example.runAprils();\n//\t\tobligations = e", "end": 7478, "score": 0.9182149767875671, "start": 7469, "tag": "USERNAME", "value": "MizarHard" }, { "context": " Start tests */\n// example = new Example(\"MizarHard\");\n//\t\t//example.runAprils();\n//\t\tobligations = e", "end": 8471, "score": 0.9151611328125, "start": 8463, "tag": "USERNAME", "value": "izarHard" } ]
null
[]
/** * */ package tptpaxsel; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import tptpaxsel.PSA.PSADivvy; import tptpaxsel.PSA.PSAExistential; import tptpaxsel.PSA.PSAPremiseGrowth; import tptpaxsel.PSA.PSARandomize; import tptpaxsel.PSA.PSASimple; import tptpaxsel.example.Example; /** * @author <NAME> * */ public class Main { static private PrintStream stdOut = System.out; static private double weightObligationEdges = 1.0; static private double weightAPRILS = 0.0; static private double weightNaproche = 1.0; static private int maxTime = 300; /* Currently not used!!! */ /** * Hack your tests here. * Supported provers are E ("E") and Vampire ("V"). The Vampire binary must be in /lib/VAMPIRE * * @param args */ public static void main(String[] args) { // AtpApi aaa = new AtpApi("test/javanaproche/","test/javanaproche/obligations.nap"); // aaa.setSimple(0.0, 0.0, 1.0, "E", 3, 1); // aaa.runSingleByFilename("1-apod(1)-holds(apod(1), 10, 0).input"); Example example; Obligations obligations; PSASimple one; PSASimple two; PSAPremiseGrowth premiseGrowth; PSADivvy divvy; PSAExistential ex = new PSAExistential(); PSARandomize random = new PSARandomize(); /* Copy pasteable foobar */ String[] provers = new String[2]; provers[0] = "V"; provers[1] = "E"; String[] proverV = new String[1]; proverV[0] = "V"; premiseGrowth = new PSAPremiseGrowth(5, "plus", 10, 5, 0, provers); divvy = new PSADivvy(2, 5, provers, true); one = new PSASimple("V",300); two = new PSASimple("E",5); /* End Copy pasteable foobar */ /* Start tests */ example = new Example("Euclid"); //example.runAprils(); obligations = example.obligations; //ex.deleteExistentialPremises(obligations); //random.changeCheckSettings(obligations); //Default values are weightAPRILS = 1; weightObligationGraph=1; maxTime = 5 * 1000 obligations.weightAPRILS = 1.0; obligations.weightNaproche = 1.0; obligations.weightObligationGraph = 1.0; obligations.maxTime = maxTime; //PSA Settings premiseGrowth = new PSAPremiseGrowth(200, "plus", 10, 1, 0, provers); // Log System.out.println("Example: "+example.name); premiseGrowth.changeCheckSettings(obligations); obligations.checkObligations(); /* Write machine readable stats Start */ Statistics.printMachineStats(obligations, "foo.stats"); Statistics.printProcessTimeline(obligations, 600, "foo.timeline"); /* Write machine readable stats End */ // /* Start tests */ // example = new Example("Euclid"); // //example.runAprils(); // obligations = example.obligations; // //ex.deleteExistentialPremises(obligations); // //random.changeCheckSettings(obligations); // //Default values are weightAPRILS = 1; weightObligationGraph=1; maxTime = 5 * 1000 // obligations.weightAPRILS = 1.0; // obligations.weightNaproche = 1.0; // obligations.weightObligationGraph = 1.0; // obligations.maxTime = maxTime; // //PSA Settings // divvy = new PSADivvy(2, 5, proverV, true); // // Log // System.out.println("Example: "+example.name); // divvy.changeCheckSettings(obligations); // obligations.checkObligations(); // /* Write machine readable stats Start */ // Statistics.printMachineStats(obligations, "EuclidDivvyV2tries5secN1A1.stats"); // Statistics.printProcessTimeline(obligations, 600, "EuclidDivvyV2tries5secN1A1.timeline"); // /* Write machine readable stats End */ // // // /* Start tests */ // example = new Example("Euclid"); // //example.runAprils(); // obligations = example.obligations; // //ex.deleteExistentialPremises(obligations); // //random.changeCheckSettings(obligations); // //Default values are weightAPRILS = 1; weightObligationGraph=1; maxTime = 5 * 1000 // obligations.weightAPRILS = 1.0; // obligations.weightNaproche = 1.0; // obligations.weightObligationGraph = 1.0; // obligations.maxTime = maxTime; // //PSA Settings // premiseGrowth = new PSAPremiseGrowth(10, "plus", 10, 5, 0, provers); // // Log // System.out.println("Example: "+example.name); // premiseGrowth.changeCheckSettings(obligations); // obligations.checkObligations(); // /* Write machine readable stats Start */ // Statistics.printMachineStats(obligations, "EuclidVE10plus10time5sN1A1.stats"); // Statistics.printProcessTimeline(obligations, 600, "EuclidVE10plus10time5sN1A1.timeline"); // /* Write machine readable stats End */ // // /* Start tests */ // example = new Example("Euclid"); // //example.runAprils(); // obligations = example.obligations; // //ex.deleteExistentialPremises(obligations); // //random.changeCheckSettings(obligations); // //Default values are weightAPRILS = 1; weightObligationGraph=1; maxTime = 5 * 1000 // obligations.weightAPRILS = 1.0; // obligations.weightNaproche = 1.0; // obligations.weightObligationGraph = 1.0; // obligations.maxTime = maxTime; // //PSA Settings // divvy = new PSADivvy(2, 5, provers, true); // // Log // System.out.println("Example: "+example.name); // divvy.changeCheckSettings(obligations); // obligations.checkObligations(); // /* Write machine readable stats Start */ // Statistics.printMachineStats(obligations, "EuclidDivvyVE2tries5secN1A1.stats"); // Statistics.printProcessTimeline(obligations, 600, "EuclidDivvyVE2tries5secN1A1.timeline"); // /* Write machine readable stats End */ // // /* Start tests */ // example = new Example("Mizar"); // //example.runAprils(); // obligations = example.obligations; // //ex.deleteExistentialPremises(obligations); // //random.changeCheckSettings(obligations); // //Default values are weightAPRILS = 1; weightObligationGraph=1; maxTime = 5 * 1000 // obligations.weightAPRILS = 0.0; // obligations.weightNaproche = 1.0; // obligations.weightObligationGraph = 1.0; // obligations.maxTime = maxTime; // //PSA Settings // premiseGrowth = new PSAPremiseGrowth(10, "plus", 10, 5, 0, proverV); // // Log // System.out.println("Example: "+example.name); // premiseGrowth.changeCheckSettings(obligations); // obligations.checkObligations(); // /* Write machine readable stats Start */ // Statistics.printMachineStats(obligations, "MizarV10plus10time5sN1A0.stats"); // Statistics.printProcessTimeline(obligations, 600, "MizarV10plus10time5sN1A0.timeline"); // /* Write machine readable stats End */ // // /* Start tests */ // example = new Example("Mizar"); // //example.runAprils(); // obligations = example.obligations; // //ex.deleteExistentialPremises(obligations); // //random.changeCheckSettings(obligations); // //Default values are weightAPRILS = 1; weightObligationGraph=1; maxTime = 5 * 1000 // obligations.weightAPRILS = 1.0; // obligations.weightNaproche = 0.0; // obligations.weightObligationGraph = 1.0; // obligations.maxTime = maxTime; // //PSA Settings // premiseGrowth = new PSAPremiseGrowth(10, "plus", 10, 5, 0, proverV); // // Log // System.out.println("Example: "+example.name); // premiseGrowth.changeCheckSettings(obligations); // obligations.checkObligations(); // /* Write machine readable stats Start */ // Statistics.printMachineStats(obligations, "MizarV10plus10time5sN0A1.stats"); // Statistics.printProcessTimeline(obligations, 600, "MizarV10plus10time5sN0A1.timeline"); // /* Write machine readable stats End */ // // /* Start tests */ // example = new Example("MizarHard"); // //example.runAprils(); // obligations = example.obligations; // //ex.deleteExistentialPremises(obligations); // //random.changeCheckSettings(obligations); // //Default values are weightAPRILS = 1; weightObligationGraph=1; maxTime = 5 * 1000 // obligations.weightAPRILS = 0.0; // obligations.weightNaproche = 1.0; // obligations.weightObligationGraph = 1.0; // obligations.maxTime = maxTime; // //PSA Settings // premiseGrowth = new PSAPremiseGrowth(10, "plus", 10, 5, 0, proverV); // // Log // System.out.println("Example: "+example.name); // premiseGrowth.changeCheckSettings(obligations); // obligations.checkObligations(); // /* Write machine readable stats Start */ // Statistics.printMachineStats(obligations, "MizarHardV10plus10time5sN1A0.stats"); // Statistics.printProcessTimeline(obligations, 600, "MizarHardV10plus10time5sN1A0.timeline"); // /* Write machine readable stats End */ // // /* Start tests */ // example = new Example("MizarHard"); // //example.runAprils(); // obligations = example.obligations; // //ex.deleteExistentialPremises(obligations); // //random.changeCheckSettings(obligations); // //Default values are weightAPRILS = 1; weightObligationGraph=1; maxTime = 5 * 1000 // obligations.weightAPRILS = 1.0; // obligations.weightNaproche = 0.0; // obligations.weightObligationGraph = 1.0; // obligations.maxTime = maxTime; // //PSA Settings // premiseGrowth = new PSAPremiseGrowth(10, "plus", 10, 5, 0, proverV); // // Log // System.out.println("Example: "+example.name); // premiseGrowth.changeCheckSettings(obligations); // obligations.checkObligations(); // /* Write machine readable stats Start */ // Statistics.printMachineStats(obligations, "MizarHardV10plus10time5sN0A1.stats"); // Statistics.printProcessTimeline(obligations, 600, "MizarHardV10plus10time5sN0A1.timeline"); // /* Write machine readable stats End */ } /* Redirect output stream to file */ static public void setLog(String File) { try { System.setOut(new PrintStream(new FileOutputStream(File))); } catch (FileNotFoundException ex) { System.out.println("Cannot direct StdOut to file "+File); ex.printStackTrace(); return; } } static public void stdOutReset() { System.setOut(stdOut); } }
9,832
0.700234
0.670359
257
37.291828
23.817816
95
false
false
0
0
0
0
0
0
2.805448
false
false
14
9f526e159f44141329104fda65427c7ce2fa5d13
9,337,258,960,537
22ca095ac2b4cae31645318e66864e162ef15323
/CosLibrary/src/main/java/com/cossystem/core/pojos/TblEmpleadosExperienciaPerfil.java
e7bc4f0d980d1857eebf7f069b83e4ade05bf5c4
[]
no_license
jkarlos1402/CossystemMaven
https://github.com/jkarlos1402/CossystemMaven
89f7dc6414721ca6d0be07dc04a2b0c28b252eba
4a282074019a97c552c751dcac32171be59bbb8e
refs/heads/master
2021-08-23T23:47:56.910000
2017-12-07T04:00:09
2017-12-07T04:00:09
112,812,173
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 com.cossystem.core.pojos; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author TMXIDSJPINAM */ @Entity @Table(name = "tbl_Empleados_ExperienciaPerfil") @XmlRootElement @NamedQueries({ @NamedQuery(name = "TblEmpleadosExperienciaPerfil.findAll", query = "SELECT t FROM TblEmpleadosExperienciaPerfil t")}) public class TblEmpleadosExperienciaPerfil implements Serializable { // private static final long serialVersionUID = 1L; @Column(name = "IdEmpresa") private Integer idEmpresa; @Id @Basic(optional = false) @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "IdExperiencia") private Integer idExperiencia; @Column(name = "Exp_Titulo") private String expTitulo; @Column(name = "Exp_Notas") private String expNotas; @Column(name = "Exp_Anios") private Integer expAnios; @Column(name = "Confirmada") private Boolean confirmada; @JoinColumn(name = "IdEmpleado", referencedColumnName = "IdEmpleado") @ManyToOne private TblEmpleados idEmpleado; public TblEmpleadosExperienciaPerfil() { } public TblEmpleadosExperienciaPerfil(Integer idExperiencia) { this.idExperiencia = idExperiencia; } public Integer getIdEmpresa() { return idEmpresa; } public void setIdEmpresa(Integer idEmpresa) { this.idEmpresa = idEmpresa; } public Integer getIdExperiencia() { return idExperiencia; } public void setIdExperiencia(Integer idExperiencia) { this.idExperiencia = idExperiencia; } public String getExpTitulo() { return expTitulo; } public void setExpTitulo(String expTitulo) { this.expTitulo = expTitulo; } public String getExpNotas() { return expNotas; } public void setExpNotas(String expNotas) { this.expNotas = expNotas; } public Integer getExpAnios() { return expAnios; } public void setExpAnios(Integer expAnios) { this.expAnios = expAnios; } public Boolean getConfirmada() { return confirmada; } public void setConfirmada(Boolean confirmada) { this.confirmada = confirmada; } @XmlTransient public TblEmpleados getIdEmpleado() { return idEmpleado; } public void setIdEmpleado(TblEmpleados idEmpleado) { this.idEmpleado = idEmpleado; } @Override public int hashCode() { int hash = 0; hash += (idExperiencia != null ? idExperiencia.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof TblEmpleadosExperienciaPerfil)) { return false; } TblEmpleadosExperienciaPerfil other = (TblEmpleadosExperienciaPerfil) object; if ((this.idExperiencia == null && other.idExperiencia != null) || (this.idExperiencia != null && !this.idExperiencia.equals(other.idExperiencia))) { return false; } return true; } @Override public String toString() { return "com.cossystem.core.pojos.empleado.TblEmpleadosExperienciaPerfil[ idExperiencia=" + idExperiencia + " ]"; } }
UTF-8
Java
4,101
java
TblEmpleadosExperienciaPerfil.java
Java
[ { "context": "nd.annotation.XmlTransient;\r\n\r\n/**\r\n *\r\n * @author TMXIDSJPINAM\r\n */\r\n@Entity\r\n@Table(name = \"tbl_Empleados_Exper", "end": 790, "score": 0.997049868106842, "start": 778, "tag": "USERNAME", "value": "TMXIDSJPINAM" } ]
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 com.cossystem.core.pojos; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author TMXIDSJPINAM */ @Entity @Table(name = "tbl_Empleados_ExperienciaPerfil") @XmlRootElement @NamedQueries({ @NamedQuery(name = "TblEmpleadosExperienciaPerfil.findAll", query = "SELECT t FROM TblEmpleadosExperienciaPerfil t")}) public class TblEmpleadosExperienciaPerfil implements Serializable { // private static final long serialVersionUID = 1L; @Column(name = "IdEmpresa") private Integer idEmpresa; @Id @Basic(optional = false) @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "IdExperiencia") private Integer idExperiencia; @Column(name = "Exp_Titulo") private String expTitulo; @Column(name = "Exp_Notas") private String expNotas; @Column(name = "Exp_Anios") private Integer expAnios; @Column(name = "Confirmada") private Boolean confirmada; @JoinColumn(name = "IdEmpleado", referencedColumnName = "IdEmpleado") @ManyToOne private TblEmpleados idEmpleado; public TblEmpleadosExperienciaPerfil() { } public TblEmpleadosExperienciaPerfil(Integer idExperiencia) { this.idExperiencia = idExperiencia; } public Integer getIdEmpresa() { return idEmpresa; } public void setIdEmpresa(Integer idEmpresa) { this.idEmpresa = idEmpresa; } public Integer getIdExperiencia() { return idExperiencia; } public void setIdExperiencia(Integer idExperiencia) { this.idExperiencia = idExperiencia; } public String getExpTitulo() { return expTitulo; } public void setExpTitulo(String expTitulo) { this.expTitulo = expTitulo; } public String getExpNotas() { return expNotas; } public void setExpNotas(String expNotas) { this.expNotas = expNotas; } public Integer getExpAnios() { return expAnios; } public void setExpAnios(Integer expAnios) { this.expAnios = expAnios; } public Boolean getConfirmada() { return confirmada; } public void setConfirmada(Boolean confirmada) { this.confirmada = confirmada; } @XmlTransient public TblEmpleados getIdEmpleado() { return idEmpleado; } public void setIdEmpleado(TblEmpleados idEmpleado) { this.idEmpleado = idEmpleado; } @Override public int hashCode() { int hash = 0; hash += (idExperiencia != null ? idExperiencia.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof TblEmpleadosExperienciaPerfil)) { return false; } TblEmpleadosExperienciaPerfil other = (TblEmpleadosExperienciaPerfil) object; if ((this.idExperiencia == null && other.idExperiencia != null) || (this.idExperiencia != null && !this.idExperiencia.equals(other.idExperiencia))) { return false; } return true; } @Override public String toString() { return "com.cossystem.core.pojos.empleado.TblEmpleadosExperienciaPerfil[ idExperiencia=" + idExperiencia + " ]"; } }
4,101
0.663741
0.663009
143
26.678322
25.942001
157
false
false
0
0
0
0
0
0
0.370629
false
false
14
50400fcb9ed3f9dbc02706debe4a108c2d6a4a63
30,709,016,196,432
905d39a384c3b0d4b2ec35dcdce0cd5d085df8fe
/effectivejava/src/main/java/com/rightkarma/effectivejava/noninstantiable/NonInstantiableUtilityClass.java
0ef39ed358b673ddfa18e18fb459e93d04be1ab7
[]
no_license
RightKarma/learnjava
https://github.com/RightKarma/learnjava
78c8dd57d831fbe04612eddca9539f9da9bbe2fc
97ed0f8d9eed3e3b2c1387d293028f8c8b15df99
refs/heads/master
2020-01-05T04:47:19.499000
2019-07-08T05:10:33
2019-07-08T05:10:33
123,669,892
1
2
null
false
2019-05-09T07:18:39
2018-03-03T07:30:14
2019-03-10T10:36:08
2019-05-09T07:18:33
1,835
0
1
1
Java
false
false
package com.rightkarma.effectivejava.noninstantiable; // to make it clear that you don't want class to be instantiated, // create constructore as private // create other methods as static public class NonInstantiableUtilityClass { private NonInstantiableUtilityClass() { } public static void otherStaticMethods(){ //... } }
UTF-8
Java
351
java
NonInstantiableUtilityClass.java
Java
[]
null
[]
package com.rightkarma.effectivejava.noninstantiable; // to make it clear that you don't want class to be instantiated, // create constructore as private // create other methods as static public class NonInstantiableUtilityClass { private NonInstantiableUtilityClass() { } public static void otherStaticMethods(){ //... } }
351
0.729345
0.729345
14
24.071428
22.150345
65
false
false
0
0
0
0
0
0
0.142857
false
false
14
e80138219960992bca190e544344b680e3a8e3e4
5,746,666,247,467
cd30c8ddf12482ba71c930998e7bce5669b93ded
/src/main/java/com/currencybaskets/dto/AggregatedAmountDto.java
672fe5aec58a70b8b2e4a26d91dcd4afc2aefd8b
[ "MIT" ]
permissive
egorvlgavr/currency-baskets
https://github.com/egorvlgavr/currency-baskets
ecb53bec5846eeaf259026ab15b7eee7ae9e7050
2dac5bfbd5192ed656928f81d3bd1e9a57898795
refs/heads/master
2018-11-05T00:22:08.535000
2018-10-06T12:23:39
2018-10-06T12:23:39
115,663,896
0
0
MIT
false
2018-09-30T18:53:14
2017-12-28T22:20:33
2018-09-12T15:11:17
2018-09-30T18:53:14
1,836
0
0
0
Java
false
null
package com.currencybaskets.dto; import com.currencybaskets.dao.model.AggregatedAmount; import com.currencybaskets.util.CurrencyColorMap; import lombok.Data; import java.math.BigDecimal; @Data public class AggregatedAmountDto { private String currency; private BigDecimal amount; private String color; public static AggregatedAmountDto fromEntity(AggregatedAmount entity) { AggregatedAmountDto dto = new AggregatedAmountDto(); dto.setAmount(entity.getAmount()); String currency = entity.getCurrency().getName(); dto.setCurrency(currency); dto.setColor(CurrencyColorMap.getCurrencyColor(currency)); return dto; } }
UTF-8
Java
686
java
AggregatedAmountDto.java
Java
[]
null
[]
package com.currencybaskets.dto; import com.currencybaskets.dao.model.AggregatedAmount; import com.currencybaskets.util.CurrencyColorMap; import lombok.Data; import java.math.BigDecimal; @Data public class AggregatedAmountDto { private String currency; private BigDecimal amount; private String color; public static AggregatedAmountDto fromEntity(AggregatedAmount entity) { AggregatedAmountDto dto = new AggregatedAmountDto(); dto.setAmount(entity.getAmount()); String currency = entity.getCurrency().getName(); dto.setCurrency(currency); dto.setColor(CurrencyColorMap.getCurrencyColor(currency)); return dto; } }
686
0.74344
0.74344
23
28.826086
22.842852
75
false
false
0
0
0
0
0
0
0.608696
false
false
14
742f795c53b7590c89b810f2574eecfb0047e508
7,593,502,186,278
9a4cac200744301680c5e5749971f138cd0eaed9
/project/src/sd/tp1/client/cloud/cache/CachedPicture.java
2b9fda65047be07c784a7bb61e4d9d5acfde5339
[]
no_license
GoncaloBFM/DistributedImageServer
https://github.com/GoncaloBFM/DistributedImageServer
9eb7f6d046fa6e93de4b2546c1aea6ff0ec1df60
b6597ce6028f1f5fdf19f91ef83814e30eb90b0a
refs/heads/master
2021-05-31T23:31:57.263000
2016-05-10T19:43:46
2016-05-10T19:43:46
53,962,824
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package sd.tp1.client.cloud.cache; import sd.tp1.Album; import sd.tp1.Picture; import java.io.File; import java.io.IOException; import java.nio.file.Files; /** * Created by apontes on 4/5/16. */ public class CachedPicture extends CachedObject<byte[]> implements Picture, CachedBlob { private static final long DEFAULT_TTL = 60000; private static final File CACHE_DIR = new File(".pictureCache"); static{ if(!CACHE_DIR.exists()){ if(CACHE_DIR.mkdir()){ CACHE_DIR.deleteOnExit(); } else throw new RuntimeException("Cannot create picture cache directory: " + CACHE_DIR.getAbsolutePath()); } else if (!CACHE_DIR.isDirectory()) throw new RuntimeException("Picture cache directory is a file: " + CACHE_DIR.getAbsolutePath()); } private int length; private File file; private String pictureName, albumName; CachedPicture(Album album, Picture picture, byte[] content){ this(album, picture, content, DEFAULT_TTL); } CachedPicture(Album album, Picture picture, byte[] content, long ttl) { super(content, ttl); this.albumName = album.getName(); this.pictureName = picture.getPictureName(); } @Override public int length() { return this.length; } @Override public synchronized void swap() { File dir; synchronized (CACHE_DIR){ dir = new File(CACHE_DIR, albumName); if(!dir.exists()){ if(!dir.mkdir()) throw new RuntimeException("Can't create album folder to cache picture"); dir.deleteOnExit(); } } this.file = new File(dir, this.pictureName); try { Files.write(file.toPath(), super.content); this.file.deleteOnExit(); } catch (IOException e) { e.printStackTrace(); super.isDirty(); } //Free RAM super.content = null; } @Override public boolean isOnRam() { return super.content != null; } @Override public boolean isOnDisk() { return this.file != null && this.file.exists(); } public String getPictureName() { return this.pictureName; } @Override public synchronized void recache(byte[] object, long ttl) { super.recache(object, ttl); this.length = object.length; if(this.file != null){ this.file.delete(); this.file = null; } } @Override public synchronized byte[] get() { byte[] content = this.content; if(content != null) return content; if(this.file != null){ try { return Files.readAllBytes(this.file.toPath()); } catch (IOException e) { e.printStackTrace(); } } return null; } @Override protected void finalize() throws Throwable { if(this.file != null) this.file.delete(); super.finalize(); } @Override public int hashCode() { return String.format("%s//%s", this.pictureName, this.albumName).hashCode(); } @Override public boolean equals(Object obj) { if(obj instanceof CachedPicture){ CachedPicture picture = (CachedPicture) obj; return picture.pictureName.equals(this.pictureName) && picture.albumName.equals(this.albumName); } return super.equals(obj); } public String getAlbumName(){ return this.albumName; } }
UTF-8
Java
3,648
java
CachedPicture.java
Java
[ { "context": "on;\nimport java.nio.file.Files;\n\n/**\n * Created by apontes on 4/5/16.\n */\npublic class CachedPicture extends", "end": 184, "score": 0.999504804611206, "start": 177, "tag": "USERNAME", "value": "apontes" } ]
null
[]
package sd.tp1.client.cloud.cache; import sd.tp1.Album; import sd.tp1.Picture; import java.io.File; import java.io.IOException; import java.nio.file.Files; /** * Created by apontes on 4/5/16. */ public class CachedPicture extends CachedObject<byte[]> implements Picture, CachedBlob { private static final long DEFAULT_TTL = 60000; private static final File CACHE_DIR = new File(".pictureCache"); static{ if(!CACHE_DIR.exists()){ if(CACHE_DIR.mkdir()){ CACHE_DIR.deleteOnExit(); } else throw new RuntimeException("Cannot create picture cache directory: " + CACHE_DIR.getAbsolutePath()); } else if (!CACHE_DIR.isDirectory()) throw new RuntimeException("Picture cache directory is a file: " + CACHE_DIR.getAbsolutePath()); } private int length; private File file; private String pictureName, albumName; CachedPicture(Album album, Picture picture, byte[] content){ this(album, picture, content, DEFAULT_TTL); } CachedPicture(Album album, Picture picture, byte[] content, long ttl) { super(content, ttl); this.albumName = album.getName(); this.pictureName = picture.getPictureName(); } @Override public int length() { return this.length; } @Override public synchronized void swap() { File dir; synchronized (CACHE_DIR){ dir = new File(CACHE_DIR, albumName); if(!dir.exists()){ if(!dir.mkdir()) throw new RuntimeException("Can't create album folder to cache picture"); dir.deleteOnExit(); } } this.file = new File(dir, this.pictureName); try { Files.write(file.toPath(), super.content); this.file.deleteOnExit(); } catch (IOException e) { e.printStackTrace(); super.isDirty(); } //Free RAM super.content = null; } @Override public boolean isOnRam() { return super.content != null; } @Override public boolean isOnDisk() { return this.file != null && this.file.exists(); } public String getPictureName() { return this.pictureName; } @Override public synchronized void recache(byte[] object, long ttl) { super.recache(object, ttl); this.length = object.length; if(this.file != null){ this.file.delete(); this.file = null; } } @Override public synchronized byte[] get() { byte[] content = this.content; if(content != null) return content; if(this.file != null){ try { return Files.readAllBytes(this.file.toPath()); } catch (IOException e) { e.printStackTrace(); } } return null; } @Override protected void finalize() throws Throwable { if(this.file != null) this.file.delete(); super.finalize(); } @Override public int hashCode() { return String.format("%s//%s", this.pictureName, this.albumName).hashCode(); } @Override public boolean equals(Object obj) { if(obj instanceof CachedPicture){ CachedPicture picture = (CachedPicture) obj; return picture.pictureName.equals(this.pictureName) && picture.albumName.equals(this.albumName); } return super.equals(obj); } public String getAlbumName(){ return this.albumName; } }
3,648
0.570724
0.567434
150
23.32
23.798689
114
true
false
0
0
0
0
0
0
0.44
false
false
14
9fd2e9004f8c7ad055adc5b1a3b7e6917823b5b9
9,062,381,002,327
a35a6a74ef97c991a5f017732f27ada99ce44d1f
/qy.times.game/src/main/java/com/game/template/CircleTemplate.java
74974c9b8fb01da2f80cf2bf88af2d2c9a913576
[]
no_license
zouzhiwu/qy-java
https://github.com/zouzhiwu/qy-java
7d518df0d39e73b780d4cc931338c43cba4f5076
4be2ca43461358850d8a2cb8b0f46dea2bcba678
refs/heads/master
2020-05-23T13:23:37.326000
2019-05-16T01:53:18
2019-05-16T01:53:18
186,774,511
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.game.template; public class CircleTemplate extends TemplateBase { private Integer radius; private Integer liftime; private Integer stay; private Integer hurt; public CircleTemplate(Integer id, String name, Integer radius, Integer liftime, Integer stay, Integer hurt) { super.setId(id); super.setName(name); this.radius = radius; this.liftime = liftime; this.stay = stay; this.hurt = hurt; } public Integer getRadius() { return radius; } public void setRadius(Integer radius) { this.radius = radius; } public Integer getLiftime() { return liftime; } public void setTime(Integer liftime) { this.liftime = liftime; } public Integer getStay() { return stay; } public void setStay(Integer stay) { this.stay = stay; } public Integer getHurt() { return hurt; } public void setHurt(Integer hurt) { this.hurt = hurt; } @Override public String toString() { return String.format("[id=%d, name=%s radius=%s liftime=%s stay=%s hurt=%s]", super.getId(), super.getName(), radius, liftime, stay, hurt); } }
UTF-8
Java
1,073
java
CircleTemplate.java
Java
[]
null
[]
package com.game.template; public class CircleTemplate extends TemplateBase { private Integer radius; private Integer liftime; private Integer stay; private Integer hurt; public CircleTemplate(Integer id, String name, Integer radius, Integer liftime, Integer stay, Integer hurt) { super.setId(id); super.setName(name); this.radius = radius; this.liftime = liftime; this.stay = stay; this.hurt = hurt; } public Integer getRadius() { return radius; } public void setRadius(Integer radius) { this.radius = radius; } public Integer getLiftime() { return liftime; } public void setTime(Integer liftime) { this.liftime = liftime; } public Integer getStay() { return stay; } public void setStay(Integer stay) { this.stay = stay; } public Integer getHurt() { return hurt; } public void setHurt(Integer hurt) { this.hurt = hurt; } @Override public String toString() { return String.format("[id=%d, name=%s radius=%s liftime=%s stay=%s hurt=%s]", super.getId(), super.getName(), radius, liftime, stay, hurt); } }
1,073
0.695247
0.695247
49
20.918367
25.917322
147
false
false
0
0
0
0
0
0
1.734694
false
false
14
25ae9c306cb65b20fba4d3ffd5158a759484464f
9,534,827,402,494
d9a1e8da98cb7aef92dcb12088985f8cac666783
/pervider_business_1002_p2p/src/main/java/com/wyy/pervider_business_1002_p2p/service/BidRequestService.java
fd462048d933c1ba1c8594c80c3d975da99a5531
[]
no_license
wang1024it/springcloud_P2P
https://github.com/wang1024it/springcloud_P2P
d70cece4a40ed3cf6683b5c2357bc8a1e53b0d27
f1fa905dfe131af0971c9de636651d3ff0ad22a2
refs/heads/master
2022-11-07T03:09:17.037000
2019-12-18T10:49:12
2019-12-18T10:49:12
228,818,903
0
0
null
false
2022-10-12T20:35:16
2019-12-18T10:47:01
2019-12-18T10:52:35
2022-10-12T20:35:13
243
0
0
9
Java
false
false
package com.wyy.pervider_business_1002_p2p.service; import com.wyy.common_p2p.entity.borrowing.BidRequest; import com.wyy.common_p2p.utils.Query; import java.util.List; public interface BidRequestService { /** * 通过ID查询单条数据 * * @param id 主键 * @return 实例对象 */ BidRequest queryById(Integer id); /** * 查找出当前用户的借款项目 * @param membersId * @return */ BidRequest getCurrentBidRequest(Integer membersId); /** * 获取当前最大的id * @return */ Integer getMaxId(); /** * 新增数据 * * @param bidRequest 实例对象 * @return 添加行数 */ int insert(BidRequest bidRequest); /** * 通过query对象查询 * * @param query 分页查询对象 * @return 对象列表 */ List<BidRequest> queryPager(Query query); /** * 修改数据 * * @param bidRequest 实例对象 * @return 修改行数 */ int update(BidRequest bidRequest); /** * 通过主键删除数据 * * @param id 主键 * @return 删除行数 */ int deleteById(Integer id); /** * 借款失败 退钱 * @param requestId */ void failedPayment(Integer requestId); }
UTF-8
Java
1,327
java
BidRequestService.java
Java
[]
null
[]
package com.wyy.pervider_business_1002_p2p.service; import com.wyy.common_p2p.entity.borrowing.BidRequest; import com.wyy.common_p2p.utils.Query; import java.util.List; public interface BidRequestService { /** * 通过ID查询单条数据 * * @param id 主键 * @return 实例对象 */ BidRequest queryById(Integer id); /** * 查找出当前用户的借款项目 * @param membersId * @return */ BidRequest getCurrentBidRequest(Integer membersId); /** * 获取当前最大的id * @return */ Integer getMaxId(); /** * 新增数据 * * @param bidRequest 实例对象 * @return 添加行数 */ int insert(BidRequest bidRequest); /** * 通过query对象查询 * * @param query 分页查询对象 * @return 对象列表 */ List<BidRequest> queryPager(Query query); /** * 修改数据 * * @param bidRequest 实例对象 * @return 修改行数 */ int update(BidRequest bidRequest); /** * 通过主键删除数据 * * @param id 主键 * @return 删除行数 */ int deleteById(Integer id); /** * 借款失败 退钱 * @param requestId */ void failedPayment(Integer requestId); }
1,327
0.5539
0.547765
73
14.643836
14.383562
55
false
false
0
0
0
0
0
0
0.164384
false
false
14
d1ad70d47ae0b0b6da02c27384dc16a4d56a5e70
16,939,351,024,023
511af8f0846e9feaa23c67408fa40df74f7e74aa
/dbflute-buri-example/src/main/java/com/example/dbflute/buri/dbflute/cbean/cq/bs/AbstractBsBuriStateUserCQ.java
87bd84caeb8fa459f90ceebbd21edda2d4a4483b
[ "Apache-2.0" ]
permissive
seasarorg/dbflute-nostalgic
https://github.com/seasarorg/dbflute-nostalgic
f43a55a430d227f4c8e5b1785f3067dc2555e6de
af80e512b92d500c708328241b711003598831a4
refs/heads/master
2021-01-10T22:11:49.029000
2014-01-18T12:10:42
2014-01-18T12:10:42
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.dbflute.buri.dbflute.cbean.cq.bs; import java.util.*; import org.seasar.dbflute.cbean.*; import org.seasar.dbflute.cbean.chelper.*; import org.seasar.dbflute.cbean.ckey.*; import org.seasar.dbflute.cbean.coption.*; import org.seasar.dbflute.cbean.cvalue.ConditionValue; import org.seasar.dbflute.cbean.sqlclause.SqlClause; import org.seasar.dbflute.dbmeta.DBMetaProvider; import com.example.dbflute.buri.dbflute.allcommon.*; import com.example.dbflute.buri.dbflute.cbean.*; import com.example.dbflute.buri.dbflute.cbean.cq.*; /** * The abstract condition-query of BURISTATEUSER. * @author DBFlute(AutoGenerator) */ public abstract class AbstractBsBuriStateUserCQ extends AbstractConditionQuery { // =================================================================================== // Constructor // =========== public AbstractBsBuriStateUserCQ(ConditionQuery childQuery, SqlClause sqlClause, String aliasName, int nestLevel) { super(childQuery, sqlClause, aliasName, nestLevel); } // =================================================================================== // DBMeta Provider // =============== @Override protected DBMetaProvider xgetDBMetaProvider() { return DBMetaInstanceHandler.getProvider(); } // =================================================================================== // Table Name // ========== public String getTableDbName() { return "BURISTATEUSER"; } // =================================================================================== // Query // ===== /** * Equal(=). And NullIgnored, OnlyOnceRegistered. <br /> * STATEUSERID: {PK, NotNull, NUMBER(18)} * @param stateUserId The value of stateUserId as equal. */ public void setStateUserId_Equal(Long stateUserId) { doSetStateUserId_Equal(stateUserId); } protected void doSetStateUserId_Equal(Long stateUserId) { regStateUserId(CK_EQ, stateUserId); } /** * GreaterThan(&gt;). And NullIgnored, OnlyOnceRegistered. <br /> * STATEUSERID: {PK, NotNull, NUMBER(18)} * @param stateUserId The value of stateUserId as greaterThan. */ public void setStateUserId_GreaterThan(Long stateUserId) { regStateUserId(CK_GT, stateUserId); } /** * LessThan(&lt;). And NullIgnored, OnlyOnceRegistered. <br /> * STATEUSERID: {PK, NotNull, NUMBER(18)} * @param stateUserId The value of stateUserId as lessThan. */ public void setStateUserId_LessThan(Long stateUserId) { regStateUserId(CK_LT, stateUserId); } /** * GreaterEqual(&gt;=). And NullIgnored, OnlyOnceRegistered. <br /> * STATEUSERID: {PK, NotNull, NUMBER(18)} * @param stateUserId The value of stateUserId as greaterEqual. */ public void setStateUserId_GreaterEqual(Long stateUserId) { regStateUserId(CK_GE, stateUserId); } /** * LessEqual(&lt;=). And NullIgnored, OnlyOnceRegistered. <br /> * STATEUSERID: {PK, NotNull, NUMBER(18)} * @param stateUserId The value of stateUserId as lessEqual. */ public void setStateUserId_LessEqual(Long stateUserId) { regStateUserId(CK_LE, stateUserId); } /** * RangeOf with various options. (versatile) <br /> * {(default) minNumber &lt;= column &lt;= maxNumber} <br /> * And NullIgnored, OnlyOnceRegistered. <br /> * STATEUSERID: {PK, NotNull, NUMBER(18)} * @param minNumber The min number of stateUserId. (NullAllowed) * @param maxNumber The max number of stateUserId. (NullAllowed) * @param rangeOfOption The option of range-of. (NotNull) */ public void setStateUserId_RangeOf(Long minNumber, Long maxNumber, RangeOfOption rangeOfOption) { regROO(minNumber, maxNumber, getCValueStateUserId(), "STATEUSERID", rangeOfOption); } /** * InScope {in (1, 2)}. And NullIgnored, NullElementIgnored, SeveralRegistered. <br /> * STATEUSERID: {PK, NotNull, NUMBER(18)} * @param stateUserIdList The collection of stateUserId as inScope. */ public void setStateUserId_InScope(Collection<Long> stateUserIdList) { doSetStateUserId_InScope(stateUserIdList); } protected void doSetStateUserId_InScope(Collection<Long> stateUserIdList) { regINS(CK_INS, cTL(stateUserIdList), getCValueStateUserId(), "STATEUSERID"); } /** * NotInScope {not in (1, 2)}. And NullIgnored, NullElementIgnored, SeveralRegistered. <br /> * STATEUSERID: {PK, NotNull, NUMBER(18)} * @param stateUserIdList The collection of stateUserId as notInScope. */ public void setStateUserId_NotInScope(Collection<Long> stateUserIdList) { doSetStateUserId_NotInScope(stateUserIdList); } protected void doSetStateUserId_NotInScope(Collection<Long> stateUserIdList) { regINS(CK_NINS, cTL(stateUserIdList), getCValueStateUserId(), "STATEUSERID"); } /** * IsNull {is null}. And OnlyOnceRegistered. <br /> * STATEUSERID: {PK, NotNull, NUMBER(18)} */ public void setStateUserId_IsNull() { regStateUserId(CK_ISN, DOBJ); } /** * IsNotNull {is not null}. And OnlyOnceRegistered. <br /> * STATEUSERID: {PK, NotNull, NUMBER(18)} */ public void setStateUserId_IsNotNull() { regStateUserId(CK_ISNN, DOBJ); } protected void regStateUserId(ConditionKey k, Object v) { regQ(k, v, getCValueStateUserId(), "STATEUSERID"); } abstract protected ConditionValue getCValueStateUserId(); /** * Equal(=). And NullIgnored, OnlyOnceRegistered. <br /> * STATEID: {IX, NUMBER(18), FK to BURISTATE} * @param stateId The value of stateId as equal. */ public void setStateId_Equal(Long stateId) { doSetStateId_Equal(stateId); } protected void doSetStateId_Equal(Long stateId) { regStateId(CK_EQ, stateId); } /** * GreaterThan(&gt;). And NullIgnored, OnlyOnceRegistered. <br /> * STATEID: {IX, NUMBER(18), FK to BURISTATE} * @param stateId The value of stateId as greaterThan. */ public void setStateId_GreaterThan(Long stateId) { regStateId(CK_GT, stateId); } /** * LessThan(&lt;). And NullIgnored, OnlyOnceRegistered. <br /> * STATEID: {IX, NUMBER(18), FK to BURISTATE} * @param stateId The value of stateId as lessThan. */ public void setStateId_LessThan(Long stateId) { regStateId(CK_LT, stateId); } /** * GreaterEqual(&gt;=). And NullIgnored, OnlyOnceRegistered. <br /> * STATEID: {IX, NUMBER(18), FK to BURISTATE} * @param stateId The value of stateId as greaterEqual. */ public void setStateId_GreaterEqual(Long stateId) { regStateId(CK_GE, stateId); } /** * LessEqual(&lt;=). And NullIgnored, OnlyOnceRegistered. <br /> * STATEID: {IX, NUMBER(18), FK to BURISTATE} * @param stateId The value of stateId as lessEqual. */ public void setStateId_LessEqual(Long stateId) { regStateId(CK_LE, stateId); } /** * RangeOf with various options. (versatile) <br /> * {(default) minNumber &lt;= column &lt;= maxNumber} <br /> * And NullIgnored, OnlyOnceRegistered. <br /> * STATEID: {IX, NUMBER(18), FK to BURISTATE} * @param minNumber The min number of stateId. (NullAllowed) * @param maxNumber The max number of stateId. (NullAllowed) * @param rangeOfOption The option of range-of. (NotNull) */ public void setStateId_RangeOf(Long minNumber, Long maxNumber, RangeOfOption rangeOfOption) { regROO(minNumber, maxNumber, getCValueStateId(), "STATEID", rangeOfOption); } /** * InScope {in (1, 2)}. And NullIgnored, NullElementIgnored, SeveralRegistered. <br /> * STATEID: {IX, NUMBER(18), FK to BURISTATE} * @param stateIdList The collection of stateId as inScope. */ public void setStateId_InScope(Collection<Long> stateIdList) { doSetStateId_InScope(stateIdList); } protected void doSetStateId_InScope(Collection<Long> stateIdList) { regINS(CK_INS, cTL(stateIdList), getCValueStateId(), "STATEID"); } /** * NotInScope {not in (1, 2)}. And NullIgnored, NullElementIgnored, SeveralRegistered. <br /> * STATEID: {IX, NUMBER(18), FK to BURISTATE} * @param stateIdList The collection of stateId as notInScope. */ public void setStateId_NotInScope(Collection<Long> stateIdList) { doSetStateId_NotInScope(stateIdList); } protected void doSetStateId_NotInScope(Collection<Long> stateIdList) { regINS(CK_NINS, cTL(stateIdList), getCValueStateId(), "STATEID"); } /** * Set up InScopeRelation (sub-query). <br /> * {in (select STATEID from BURISTATE where ...)} <br /> * BURISTATE by my STATEID, named 'buriState'. * @param subQuery The sub-query of BuriState for 'in-scope'. (NotNull) */ public void inScopeBuriState(SubQuery<BuriStateCB> subQuery) { assertObjectNotNull("subQuery<BuriStateCB>", subQuery); BuriStateCB cb = new BuriStateCB(); cb.xsetupForInScopeRelation(this); subQuery.query(cb); String subQueryPropertyName = keepStateId_InScopeRelation_BuriState(cb.query()); // for saving query-value. registerInScopeRelation(cb.query(), "STATEID", "STATEID", subQueryPropertyName, "buriState"); } public abstract String keepStateId_InScopeRelation_BuriState(BuriStateCQ subQuery); /** * Set up NotInScopeRelation (sub-query). <br /> * {not in (select STATEID from BURISTATE where ...)} <br /> * BURISTATE by my STATEID, named 'buriState'. * @param subQuery The sub-query of BuriState for 'not in-scope'. (NotNull) */ public void notInScopeBuriState(SubQuery<BuriStateCB> subQuery) { assertObjectNotNull("subQuery<BuriStateCB>", subQuery); BuriStateCB cb = new BuriStateCB(); cb.xsetupForInScopeRelation(this); subQuery.query(cb); String subQueryPropertyName = keepStateId_NotInScopeRelation_BuriState(cb.query()); // for saving query-value. registerNotInScopeRelation(cb.query(), "STATEID", "STATEID", subQueryPropertyName, "buriState"); } public abstract String keepStateId_NotInScopeRelation_BuriState(BuriStateCQ subQuery); /** * IsNull {is null}. And OnlyOnceRegistered. <br /> * STATEID: {IX, NUMBER(18), FK to BURISTATE} */ public void setStateId_IsNull() { regStateId(CK_ISN, DOBJ); } /** * IsNotNull {is not null}. And OnlyOnceRegistered. <br /> * STATEID: {IX, NUMBER(18), FK to BURISTATE} */ public void setStateId_IsNotNull() { regStateId(CK_ISNN, DOBJ); } protected void regStateId(ConditionKey k, Object v) { regQ(k, v, getCValueStateId(), "STATEID"); } abstract protected ConditionValue getCValueStateId(); /** * Equal(=). And NullIgnored, OnlyOnceRegistered. <br /> * BURIUSERID: {IX, NUMBER(18), FK to BURIUSER} * @param buriUserId The value of buriUserId as equal. */ public void setBuriUserId_Equal(Long buriUserId) { doSetBuriUserId_Equal(buriUserId); } protected void doSetBuriUserId_Equal(Long buriUserId) { regBuriUserId(CK_EQ, buriUserId); } /** * GreaterThan(&gt;). And NullIgnored, OnlyOnceRegistered. <br /> * BURIUSERID: {IX, NUMBER(18), FK to BURIUSER} * @param buriUserId The value of buriUserId as greaterThan. */ public void setBuriUserId_GreaterThan(Long buriUserId) { regBuriUserId(CK_GT, buriUserId); } /** * LessThan(&lt;). And NullIgnored, OnlyOnceRegistered. <br /> * BURIUSERID: {IX, NUMBER(18), FK to BURIUSER} * @param buriUserId The value of buriUserId as lessThan. */ public void setBuriUserId_LessThan(Long buriUserId) { regBuriUserId(CK_LT, buriUserId); } /** * GreaterEqual(&gt;=). And NullIgnored, OnlyOnceRegistered. <br /> * BURIUSERID: {IX, NUMBER(18), FK to BURIUSER} * @param buriUserId The value of buriUserId as greaterEqual. */ public void setBuriUserId_GreaterEqual(Long buriUserId) { regBuriUserId(CK_GE, buriUserId); } /** * LessEqual(&lt;=). And NullIgnored, OnlyOnceRegistered. <br /> * BURIUSERID: {IX, NUMBER(18), FK to BURIUSER} * @param buriUserId The value of buriUserId as lessEqual. */ public void setBuriUserId_LessEqual(Long buriUserId) { regBuriUserId(CK_LE, buriUserId); } /** * RangeOf with various options. (versatile) <br /> * {(default) minNumber &lt;= column &lt;= maxNumber} <br /> * And NullIgnored, OnlyOnceRegistered. <br /> * BURIUSERID: {IX, NUMBER(18), FK to BURIUSER} * @param minNumber The min number of buriUserId. (NullAllowed) * @param maxNumber The max number of buriUserId. (NullAllowed) * @param rangeOfOption The option of range-of. (NotNull) */ public void setBuriUserId_RangeOf(Long minNumber, Long maxNumber, RangeOfOption rangeOfOption) { regROO(minNumber, maxNumber, getCValueBuriUserId(), "BURIUSERID", rangeOfOption); } /** * InScope {in (1, 2)}. And NullIgnored, NullElementIgnored, SeveralRegistered. <br /> * BURIUSERID: {IX, NUMBER(18), FK to BURIUSER} * @param buriUserIdList The collection of buriUserId as inScope. */ public void setBuriUserId_InScope(Collection<Long> buriUserIdList) { doSetBuriUserId_InScope(buriUserIdList); } protected void doSetBuriUserId_InScope(Collection<Long> buriUserIdList) { regINS(CK_INS, cTL(buriUserIdList), getCValueBuriUserId(), "BURIUSERID"); } /** * NotInScope {not in (1, 2)}. And NullIgnored, NullElementIgnored, SeveralRegistered. <br /> * BURIUSERID: {IX, NUMBER(18), FK to BURIUSER} * @param buriUserIdList The collection of buriUserId as notInScope. */ public void setBuriUserId_NotInScope(Collection<Long> buriUserIdList) { doSetBuriUserId_NotInScope(buriUserIdList); } protected void doSetBuriUserId_NotInScope(Collection<Long> buriUserIdList) { regINS(CK_NINS, cTL(buriUserIdList), getCValueBuriUserId(), "BURIUSERID"); } /** * Set up InScopeRelation (sub-query). <br /> * {in (select BURIUSERID from BURIUSER where ...)} <br /> * BURIUSER by my BURIUSERID, named 'buriUser'. * @param subQuery The sub-query of BuriUser for 'in-scope'. (NotNull) */ public void inScopeBuriUser(SubQuery<BuriUserCB> subQuery) { assertObjectNotNull("subQuery<BuriUserCB>", subQuery); BuriUserCB cb = new BuriUserCB(); cb.xsetupForInScopeRelation(this); subQuery.query(cb); String subQueryPropertyName = keepBuriUserId_InScopeRelation_BuriUser(cb.query()); // for saving query-value. registerInScopeRelation(cb.query(), "BURIUSERID", "BURIUSERID", subQueryPropertyName, "buriUser"); } public abstract String keepBuriUserId_InScopeRelation_BuriUser(BuriUserCQ subQuery); /** * Set up NotInScopeRelation (sub-query). <br /> * {not in (select BURIUSERID from BURIUSER where ...)} <br /> * BURIUSER by my BURIUSERID, named 'buriUser'. * @param subQuery The sub-query of BuriUser for 'not in-scope'. (NotNull) */ public void notInScopeBuriUser(SubQuery<BuriUserCB> subQuery) { assertObjectNotNull("subQuery<BuriUserCB>", subQuery); BuriUserCB cb = new BuriUserCB(); cb.xsetupForInScopeRelation(this); subQuery.query(cb); String subQueryPropertyName = keepBuriUserId_NotInScopeRelation_BuriUser(cb.query()); // for saving query-value. registerNotInScopeRelation(cb.query(), "BURIUSERID", "BURIUSERID", subQueryPropertyName, "buriUser"); } public abstract String keepBuriUserId_NotInScopeRelation_BuriUser(BuriUserCQ subQuery); /** * IsNull {is null}. And OnlyOnceRegistered. <br /> * BURIUSERID: {IX, NUMBER(18), FK to BURIUSER} */ public void setBuriUserId_IsNull() { regBuriUserId(CK_ISN, DOBJ); } /** * IsNotNull {is not null}. And OnlyOnceRegistered. <br /> * BURIUSERID: {IX, NUMBER(18), FK to BURIUSER} */ public void setBuriUserId_IsNotNull() { regBuriUserId(CK_ISNN, DOBJ); } protected void regBuriUserId(ConditionKey k, Object v) { regQ(k, v, getCValueBuriUserId(), "BURIUSERID"); } abstract protected ConditionValue getCValueBuriUserId(); /** * Equal(=). And NullIgnored, OnlyOnceRegistered. <br /> * INSERTDATE: {NotNull, TIMESTAMP(6)(11, 6)} * @param insertDate The value of insertDate as equal. */ public void setInsertDate_Equal(java.sql.Timestamp insertDate) { regInsertDate(CK_EQ, insertDate); } /** * GreaterThan(&gt;). And NullIgnored, OnlyOnceRegistered. <br /> * INSERTDATE: {NotNull, TIMESTAMP(6)(11, 6)} * @param insertDate The value of insertDate as greaterThan. */ public void setInsertDate_GreaterThan(java.sql.Timestamp insertDate) { regInsertDate(CK_GT, insertDate); } /** * LessThan(&lt;). And NullIgnored, OnlyOnceRegistered. <br /> * INSERTDATE: {NotNull, TIMESTAMP(6)(11, 6)} * @param insertDate The value of insertDate as lessThan. */ public void setInsertDate_LessThan(java.sql.Timestamp insertDate) { regInsertDate(CK_LT, insertDate); } /** * GreaterEqual(&gt;=). And NullIgnored, OnlyOnceRegistered. <br /> * INSERTDATE: {NotNull, TIMESTAMP(6)(11, 6)} * @param insertDate The value of insertDate as greaterEqual. */ public void setInsertDate_GreaterEqual(java.sql.Timestamp insertDate) { regInsertDate(CK_GE, insertDate); } /** * LessEqual(&lt;=). And NullIgnored, OnlyOnceRegistered. <br /> * INSERTDATE: {NotNull, TIMESTAMP(6)(11, 6)} * @param insertDate The value of insertDate as lessEqual. */ public void setInsertDate_LessEqual(java.sql.Timestamp insertDate) { regInsertDate(CK_LE, insertDate); } /** * FromTo with various options. (versatile) <br /> * {(default) fromDatetime &lt;= column &lt;= toDatetime} <br /> * And NullIgnored, OnlyOnceRegistered. <br /> * INSERTDATE: {NotNull, TIMESTAMP(6)(11, 6)} * @param fromDatetime The from-datetime(yyyy/MM/dd HH:mm:ss.SSS) of insertDate. (NullAllowed) * @param toDatetime The to-datetime(yyyy/MM/dd HH:mm:ss.SSS) of insertDate. (NullAllowed) * @param fromToOption The option of from-to. (NotNull) */ public void setInsertDate_FromTo(java.util.Date fromDatetime, java.util.Date toDatetime, FromToOption fromToOption) { regFTQ((fromDatetime != null ? new java.sql.Timestamp(fromDatetime.getTime()) : null), (toDatetime != null ? new java.sql.Timestamp(toDatetime.getTime()) : null), getCValueInsertDate(), "INSERTDATE", fromToOption); } /** * DateFromTo. (Date means yyyy/MM/dd) <br /> * {fromDate &lt;= column &lt; toDate + 1 day} <br /> * And NullIgnored, OnlyOnceRegistered. <br /> * INSERTDATE: {NotNull, TIMESTAMP(6)(11, 6)} * <pre> * e.g. from:{2007/04/10 08:24:53} to:{2007/04/16 14:36:29} * --&gt; column &gt;= '2007/04/10 00:00:00' * and column <span style="color: #FD4747">&lt; '2007/04/17 00:00:00'</span> * </pre> * @param fromDate The from-date(yyyy/MM/dd) of insertDate. (NullAllowed) * @param toDate The to-date(yyyy/MM/dd) of insertDate. (NullAllowed) */ public void setInsertDate_DateFromTo(java.util.Date fromDate, java.util.Date toDate) { setInsertDate_FromTo(fromDate, toDate, new DateFromToOption()); } /** * InScope {in ('1965-03-03', '1966-09-15')}. And NullIgnored, NullElementIgnored, SeveralRegistered. <br /> * INSERTDATE: {NotNull, TIMESTAMP(6)(11, 6)} * @param insertDateList The collection of insertDate as inScope. */ public void setInsertDate_InScope(Collection<java.sql.Timestamp> insertDateList) { doSetInsertDate_InScope(insertDateList); } protected void doSetInsertDate_InScope(Collection<java.sql.Timestamp> insertDateList) { regINS(CK_INS, cTL(insertDateList), getCValueInsertDate(), "INSERTDATE"); } /** * NotInScope {not in ('1965-03-03', '1966-09-15')}. And NullIgnored, NullElementIgnored, SeveralRegistered. <br /> * INSERTDATE: {NotNull, TIMESTAMP(6)(11, 6)} * @param insertDateList The collection of insertDate as notInScope. */ public void setInsertDate_NotInScope(Collection<java.sql.Timestamp> insertDateList) { doSetInsertDate_NotInScope(insertDateList); } protected void doSetInsertDate_NotInScope(Collection<java.sql.Timestamp> insertDateList) { regINS(CK_NINS, cTL(insertDateList), getCValueInsertDate(), "INSERTDATE"); } protected void regInsertDate(ConditionKey k, Object v) { regQ(k, v, getCValueInsertDate(), "INSERTDATE"); } abstract protected ConditionValue getCValueInsertDate(); /** * Equal(=). And NullIgnored, OnlyOnceRegistered. <br /> * DELETEDATE: {NotNull, TIMESTAMP(6)(11, 6)} * @param deleteDate The value of deleteDate as equal. */ public void setDeleteDate_Equal(java.sql.Timestamp deleteDate) { regDeleteDate(CK_EQ, deleteDate); } /** * GreaterThan(&gt;). And NullIgnored, OnlyOnceRegistered. <br /> * DELETEDATE: {NotNull, TIMESTAMP(6)(11, 6)} * @param deleteDate The value of deleteDate as greaterThan. */ public void setDeleteDate_GreaterThan(java.sql.Timestamp deleteDate) { regDeleteDate(CK_GT, deleteDate); } /** * LessThan(&lt;). And NullIgnored, OnlyOnceRegistered. <br /> * DELETEDATE: {NotNull, TIMESTAMP(6)(11, 6)} * @param deleteDate The value of deleteDate as lessThan. */ public void setDeleteDate_LessThan(java.sql.Timestamp deleteDate) { regDeleteDate(CK_LT, deleteDate); } /** * GreaterEqual(&gt;=). And NullIgnored, OnlyOnceRegistered. <br /> * DELETEDATE: {NotNull, TIMESTAMP(6)(11, 6)} * @param deleteDate The value of deleteDate as greaterEqual. */ public void setDeleteDate_GreaterEqual(java.sql.Timestamp deleteDate) { regDeleteDate(CK_GE, deleteDate); } /** * LessEqual(&lt;=). And NullIgnored, OnlyOnceRegistered. <br /> * DELETEDATE: {NotNull, TIMESTAMP(6)(11, 6)} * @param deleteDate The value of deleteDate as lessEqual. */ public void setDeleteDate_LessEqual(java.sql.Timestamp deleteDate) { regDeleteDate(CK_LE, deleteDate); } /** * FromTo with various options. (versatile) <br /> * {(default) fromDatetime &lt;= column &lt;= toDatetime} <br /> * And NullIgnored, OnlyOnceRegistered. <br /> * DELETEDATE: {NotNull, TIMESTAMP(6)(11, 6)} * @param fromDatetime The from-datetime(yyyy/MM/dd HH:mm:ss.SSS) of deleteDate. (NullAllowed) * @param toDatetime The to-datetime(yyyy/MM/dd HH:mm:ss.SSS) of deleteDate. (NullAllowed) * @param fromToOption The option of from-to. (NotNull) */ public void setDeleteDate_FromTo(java.util.Date fromDatetime, java.util.Date toDatetime, FromToOption fromToOption) { regFTQ((fromDatetime != null ? new java.sql.Timestamp(fromDatetime.getTime()) : null), (toDatetime != null ? new java.sql.Timestamp(toDatetime.getTime()) : null), getCValueDeleteDate(), "DELETEDATE", fromToOption); } /** * DateFromTo. (Date means yyyy/MM/dd) <br /> * {fromDate &lt;= column &lt; toDate + 1 day} <br /> * And NullIgnored, OnlyOnceRegistered. <br /> * DELETEDATE: {NotNull, TIMESTAMP(6)(11, 6)} * <pre> * e.g. from:{2007/04/10 08:24:53} to:{2007/04/16 14:36:29} * --&gt; column &gt;= '2007/04/10 00:00:00' * and column <span style="color: #FD4747">&lt; '2007/04/17 00:00:00'</span> * </pre> * @param fromDate The from-date(yyyy/MM/dd) of deleteDate. (NullAllowed) * @param toDate The to-date(yyyy/MM/dd) of deleteDate. (NullAllowed) */ public void setDeleteDate_DateFromTo(java.util.Date fromDate, java.util.Date toDate) { setDeleteDate_FromTo(fromDate, toDate, new DateFromToOption()); } /** * InScope {in ('1965-03-03', '1966-09-15')}. And NullIgnored, NullElementIgnored, SeveralRegistered. <br /> * DELETEDATE: {NotNull, TIMESTAMP(6)(11, 6)} * @param deleteDateList The collection of deleteDate as inScope. */ public void setDeleteDate_InScope(Collection<java.sql.Timestamp> deleteDateList) { doSetDeleteDate_InScope(deleteDateList); } protected void doSetDeleteDate_InScope(Collection<java.sql.Timestamp> deleteDateList) { regINS(CK_INS, cTL(deleteDateList), getCValueDeleteDate(), "DELETEDATE"); } /** * NotInScope {not in ('1965-03-03', '1966-09-15')}. And NullIgnored, NullElementIgnored, SeveralRegistered. <br /> * DELETEDATE: {NotNull, TIMESTAMP(6)(11, 6)} * @param deleteDateList The collection of deleteDate as notInScope. */ public void setDeleteDate_NotInScope(Collection<java.sql.Timestamp> deleteDateList) { doSetDeleteDate_NotInScope(deleteDateList); } protected void doSetDeleteDate_NotInScope(Collection<java.sql.Timestamp> deleteDateList) { regINS(CK_NINS, cTL(deleteDateList), getCValueDeleteDate(), "DELETEDATE"); } protected void regDeleteDate(ConditionKey k, Object v) { regQ(k, v, getCValueDeleteDate(), "DELETEDATE"); } abstract protected ConditionValue getCValueDeleteDate(); // =================================================================================== // ScalarCondition // =============== /** * Prepare ScalarCondition as equal. <br /> * {where FOO = (select max(BAR) from ...) * <pre> * cb.query().<span style="color: #FD4747">scalar_Equal()</span>.max(new SubQuery&lt;BuriStateUserCB&gt;() { * public void query(BuriStateUserCB subCB) { * subCB.specify().setXxx... <span style="color: #3F7E5E">// derived column for function</span> * subCB.query().setYyy... * } * }); * </pre> * @return The object to set up a function. (NotNull) */ public HpSSQFunction<BuriStateUserCB> scalar_Equal() { return xcreateSSQFunction(CK_EQ.getOperand()); } /** * Prepare ScalarCondition as equal. <br /> * {where FOO &lt;&gt; (select max(BAR) from ...) * <pre> * cb.query().<span style="color: #FD4747">scalar_NotEqual()</span>.max(new SubQuery&lt;BuriStateUserCB&gt;() { * public void query(BuriStateUserCB subCB) { * subCB.specify().setXxx... <span style="color: #3F7E5E">// derived column for function</span> * subCB.query().setYyy... * } * }); * </pre> * @return The object to set up a function. (NotNull) */ public HpSSQFunction<BuriStateUserCB> scalar_NotEqual() { return xcreateSSQFunction(CK_NES.getOperand()); } /** * Prepare ScalarCondition as greaterThan. <br /> * {where FOO &gt; (select max(BAR) from ...) * <pre> * cb.query().<span style="color: #FD4747">scalar_GreaterThan()</span>.max(new SubQuery&lt;BuriStateUserCB&gt;() { * public void query(BuriStateUserCB subCB) { * subCB.specify().setFoo... <span style="color: #3F7E5E">// derived column for function</span> * subCB.query().setBar... * } * }); * </pre> * @return The object to set up a function. (NotNull) */ public HpSSQFunction<BuriStateUserCB> scalar_GreaterThan() { return xcreateSSQFunction(CK_GT.getOperand()); } /** * Prepare ScalarCondition as lessThan. <br /> * {where FOO &lt; (select max(BAR) from ...) * <pre> * cb.query().<span style="color: #FD4747">scalar_LessThan()</span>.max(new SubQuery&lt;BuriStateUserCB&gt;() { * public void query(BuriStateUserCB subCB) { * subCB.specify().setFoo... <span style="color: #3F7E5E">// derived column for function</span> * subCB.query().setBar... * } * }); * </pre> * @return The object to set up a function. (NotNull) */ public HpSSQFunction<BuriStateUserCB> scalar_LessThan() { return xcreateSSQFunction(CK_LT.getOperand()); } /** * Prepare ScalarCondition as greaterEqual. <br /> * {where FOO &gt;= (select max(BAR) from ...) * <pre> * cb.query().<span style="color: #FD4747">scalar_GreaterEqual()</span>.max(new SubQuery&lt;BuriStateUserCB&gt;() { * public void query(BuriStateUserCB subCB) { * subCB.specify().setFoo... <span style="color: #3F7E5E">// derived column for function</span> * subCB.query().setBar... * } * }); * </pre> * @return The object to set up a function. (NotNull) */ public HpSSQFunction<BuriStateUserCB> scalar_GreaterEqual() { return xcreateSSQFunction(CK_GE.getOperand()); } /** * Prepare ScalarCondition as lessEqual. <br /> * {where FOO &lt;= (select max(BAR) from ...) * <pre> * cb.query().<span style="color: #FD4747">scalar_LessEqual()</span>.max(new SubQuery&lt;BuriStateUserCB&gt;() { * public void query(BuriStateUserCB subCB) { * subCB.specify().setFoo... <span style="color: #3F7E5E">// derived column for function</span> * subCB.query().setBar... * } * }); * </pre> * @return The object to set up a function. (NotNull) */ public HpSSQFunction<BuriStateUserCB> scalar_LessEqual() { return xcreateSSQFunction(CK_LE.getOperand()); } protected HpSSQFunction<BuriStateUserCB> xcreateSSQFunction(final String operand) { return new HpSSQFunction<BuriStateUserCB>(new HpSSQSetupper<BuriStateUserCB>() { public void setup(String function, SubQuery<BuriStateUserCB> subQuery, HpSSQOption<BuriStateUserCB> option) { xscalarCondition(function, subQuery, operand, option); } }); } protected void xscalarCondition(String function, SubQuery<BuriStateUserCB> subQuery, String operand, HpSSQOption<BuriStateUserCB> option) { assertObjectNotNull("subQuery<BuriStateUserCB>", subQuery); BuriStateUserCB cb = xcreateScalarConditionCB(); subQuery.query(cb); String subQueryPropertyName = keepScalarCondition(cb.query()); // for saving query-value option.setPartitionByCBean(xcreateScalarConditionPartitionByCB()); // for using partition-by registerScalarCondition(function, cb.query(), subQueryPropertyName, operand, option); } public abstract String keepScalarCondition(BuriStateUserCQ subQuery); protected BuriStateUserCB xcreateScalarConditionCB() { BuriStateUserCB cb = new BuriStateUserCB(); cb.xsetupForScalarCondition(this); return cb; } protected BuriStateUserCB xcreateScalarConditionPartitionByCB() { BuriStateUserCB cb = new BuriStateUserCB(); cb.xsetupForScalarConditionPartitionBy(this); return cb; } // =================================================================================== // MyselfDerived // ============= public void xsmyselfDerive(String function, SubQuery<BuriStateUserCB> subQuery, String aliasName, DerivedReferrerOption option) { assertObjectNotNull("subQuery<BuriStateUserCB>", subQuery); BuriStateUserCB cb = new BuriStateUserCB(); cb.xsetupForDerivedReferrer(this); subQuery.query(cb); String subQueryPropertyName = keepSpecifyMyselfDerived(cb.query()); // for saving query-value. registerSpecifyMyselfDerived(function, cb.query(), "STATEUSERID", "STATEUSERID", subQueryPropertyName, "myselfDerived", aliasName, option); } public abstract String keepSpecifyMyselfDerived(BuriStateUserCQ subQuery); /** * Prepare for (Query)MyselfDerived (SubQuery). * @return The object to set up a function for myself table. (NotNull) */ public HpQDRFunction<BuriStateUserCB> myselfDerived() { return xcreateQDRFunctionMyselfDerived(); } protected HpQDRFunction<BuriStateUserCB> xcreateQDRFunctionMyselfDerived() { return new HpQDRFunction<BuriStateUserCB>(new HpQDRSetupper<BuriStateUserCB>() { public void setup(String function, SubQuery<BuriStateUserCB> subQuery, String operand, Object value, DerivedReferrerOption option) { xqderiveMyselfDerived(function, subQuery, operand, value, option); } }); } public void xqderiveMyselfDerived(String function, SubQuery<BuriStateUserCB> subQuery, String operand, Object value, DerivedReferrerOption option) { assertObjectNotNull("subQuery<BuriStateUserCB>", subQuery); BuriStateUserCB cb = new BuriStateUserCB(); cb.xsetupForDerivedReferrer(this); subQuery.query(cb); String subQueryPropertyName = keepQueryMyselfDerived(cb.query()); // for saving query-value. String parameterPropertyName = keepQueryMyselfDerivedParameter(value); registerQueryMyselfDerived(function, cb.query(), "STATEUSERID", "STATEUSERID", subQueryPropertyName, "myselfDerived", operand, value, parameterPropertyName, option); } public abstract String keepQueryMyselfDerived(BuriStateUserCQ subQuery); public abstract String keepQueryMyselfDerivedParameter(Object parameterValue); // =================================================================================== // MyselfExists // ============ /** * Prepare for MyselfExists (SubQuery). * @param subQuery The implementation of sub query. (NotNull) */ public void myselfExists(SubQuery<BuriStateUserCB> subQuery) { assertObjectNotNull("subQuery<BuriStateUserCB>", subQuery); BuriStateUserCB cb = new BuriStateUserCB(); cb.xsetupForMyselfExists(this); subQuery.query(cb); String subQueryPropertyName = keepMyselfExists(cb.query()); // for saving query-value. registerMyselfExists(cb.query(), subQueryPropertyName); } public abstract String keepMyselfExists(BuriStateUserCQ subQuery); // =================================================================================== // MyselfInScope // ============= /** * Prepare for MyselfInScope (SubQuery). * @param subQuery The implementation of sub query. (NotNull) */ public void myselfInScope(SubQuery<BuriStateUserCB> subQuery) { assertObjectNotNull("subQuery<BuriStateUserCB>", subQuery); BuriStateUserCB cb = new BuriStateUserCB(); cb.xsetupForMyselfInScope(this); subQuery.query(cb); String subQueryPropertyName = keepMyselfInScope(cb.query()); // for saving query-value. registerMyselfInScope(cb.query(), subQueryPropertyName); } public abstract String keepMyselfInScope(BuriStateUserCQ subQuery); // =================================================================================== // Very Internal // ============= // very internal (for suppressing warn about 'Not Use Import') protected String xabCB() { return BuriStateUserCB.class.getName(); } protected String xabCQ() { return BuriStateUserCQ.class.getName(); } protected String xabLSO() { return LikeSearchOption.class.getName(); } protected String xabSSQS() { return HpSSQSetupper.class.getName(); } }
UTF-8
Java
37,554
java
AbstractBsBuriStateUserCQ.java
Java
[ { "context": "ract condition-query of BURISTATEUSER.\r\n * @author DBFlute(AutoGenerator)\r\n */\r\npublic abstract class Abstra", "end": 638, "score": 0.9953228831291199, "start": 631, "tag": "USERNAME", "value": "DBFlute" }, { "context": "<br />\r\n * BURIUSER by my BURIUSERID, named 'buriUser'.\r\n * @param subQuery The sub-query of BuriUs", "end": 15365, "score": 0.5597647428512573, "start": 15358, "tag": "USERNAME", "value": "uriUser" }, { "context": " <br />\r\n * BURIUSER by my BURIUSERID, named 'buriUser'.\r\n * @param subQuery The sub-query of BuriUs", "end": 16188, "score": 0.9930248260498047, "start": 16180, "tag": "USERNAME", "value": "buriUser" } ]
null
[]
package com.example.dbflute.buri.dbflute.cbean.cq.bs; import java.util.*; import org.seasar.dbflute.cbean.*; import org.seasar.dbflute.cbean.chelper.*; import org.seasar.dbflute.cbean.ckey.*; import org.seasar.dbflute.cbean.coption.*; import org.seasar.dbflute.cbean.cvalue.ConditionValue; import org.seasar.dbflute.cbean.sqlclause.SqlClause; import org.seasar.dbflute.dbmeta.DBMetaProvider; import com.example.dbflute.buri.dbflute.allcommon.*; import com.example.dbflute.buri.dbflute.cbean.*; import com.example.dbflute.buri.dbflute.cbean.cq.*; /** * The abstract condition-query of BURISTATEUSER. * @author DBFlute(AutoGenerator) */ public abstract class AbstractBsBuriStateUserCQ extends AbstractConditionQuery { // =================================================================================== // Constructor // =========== public AbstractBsBuriStateUserCQ(ConditionQuery childQuery, SqlClause sqlClause, String aliasName, int nestLevel) { super(childQuery, sqlClause, aliasName, nestLevel); } // =================================================================================== // DBMeta Provider // =============== @Override protected DBMetaProvider xgetDBMetaProvider() { return DBMetaInstanceHandler.getProvider(); } // =================================================================================== // Table Name // ========== public String getTableDbName() { return "BURISTATEUSER"; } // =================================================================================== // Query // ===== /** * Equal(=). And NullIgnored, OnlyOnceRegistered. <br /> * STATEUSERID: {PK, NotNull, NUMBER(18)} * @param stateUserId The value of stateUserId as equal. */ public void setStateUserId_Equal(Long stateUserId) { doSetStateUserId_Equal(stateUserId); } protected void doSetStateUserId_Equal(Long stateUserId) { regStateUserId(CK_EQ, stateUserId); } /** * GreaterThan(&gt;). And NullIgnored, OnlyOnceRegistered. <br /> * STATEUSERID: {PK, NotNull, NUMBER(18)} * @param stateUserId The value of stateUserId as greaterThan. */ public void setStateUserId_GreaterThan(Long stateUserId) { regStateUserId(CK_GT, stateUserId); } /** * LessThan(&lt;). And NullIgnored, OnlyOnceRegistered. <br /> * STATEUSERID: {PK, NotNull, NUMBER(18)} * @param stateUserId The value of stateUserId as lessThan. */ public void setStateUserId_LessThan(Long stateUserId) { regStateUserId(CK_LT, stateUserId); } /** * GreaterEqual(&gt;=). And NullIgnored, OnlyOnceRegistered. <br /> * STATEUSERID: {PK, NotNull, NUMBER(18)} * @param stateUserId The value of stateUserId as greaterEqual. */ public void setStateUserId_GreaterEqual(Long stateUserId) { regStateUserId(CK_GE, stateUserId); } /** * LessEqual(&lt;=). And NullIgnored, OnlyOnceRegistered. <br /> * STATEUSERID: {PK, NotNull, NUMBER(18)} * @param stateUserId The value of stateUserId as lessEqual. */ public void setStateUserId_LessEqual(Long stateUserId) { regStateUserId(CK_LE, stateUserId); } /** * RangeOf with various options. (versatile) <br /> * {(default) minNumber &lt;= column &lt;= maxNumber} <br /> * And NullIgnored, OnlyOnceRegistered. <br /> * STATEUSERID: {PK, NotNull, NUMBER(18)} * @param minNumber The min number of stateUserId. (NullAllowed) * @param maxNumber The max number of stateUserId. (NullAllowed) * @param rangeOfOption The option of range-of. (NotNull) */ public void setStateUserId_RangeOf(Long minNumber, Long maxNumber, RangeOfOption rangeOfOption) { regROO(minNumber, maxNumber, getCValueStateUserId(), "STATEUSERID", rangeOfOption); } /** * InScope {in (1, 2)}. And NullIgnored, NullElementIgnored, SeveralRegistered. <br /> * STATEUSERID: {PK, NotNull, NUMBER(18)} * @param stateUserIdList The collection of stateUserId as inScope. */ public void setStateUserId_InScope(Collection<Long> stateUserIdList) { doSetStateUserId_InScope(stateUserIdList); } protected void doSetStateUserId_InScope(Collection<Long> stateUserIdList) { regINS(CK_INS, cTL(stateUserIdList), getCValueStateUserId(), "STATEUSERID"); } /** * NotInScope {not in (1, 2)}. And NullIgnored, NullElementIgnored, SeveralRegistered. <br /> * STATEUSERID: {PK, NotNull, NUMBER(18)} * @param stateUserIdList The collection of stateUserId as notInScope. */ public void setStateUserId_NotInScope(Collection<Long> stateUserIdList) { doSetStateUserId_NotInScope(stateUserIdList); } protected void doSetStateUserId_NotInScope(Collection<Long> stateUserIdList) { regINS(CK_NINS, cTL(stateUserIdList), getCValueStateUserId(), "STATEUSERID"); } /** * IsNull {is null}. And OnlyOnceRegistered. <br /> * STATEUSERID: {PK, NotNull, NUMBER(18)} */ public void setStateUserId_IsNull() { regStateUserId(CK_ISN, DOBJ); } /** * IsNotNull {is not null}. And OnlyOnceRegistered. <br /> * STATEUSERID: {PK, NotNull, NUMBER(18)} */ public void setStateUserId_IsNotNull() { regStateUserId(CK_ISNN, DOBJ); } protected void regStateUserId(ConditionKey k, Object v) { regQ(k, v, getCValueStateUserId(), "STATEUSERID"); } abstract protected ConditionValue getCValueStateUserId(); /** * Equal(=). And NullIgnored, OnlyOnceRegistered. <br /> * STATEID: {IX, NUMBER(18), FK to BURISTATE} * @param stateId The value of stateId as equal. */ public void setStateId_Equal(Long stateId) { doSetStateId_Equal(stateId); } protected void doSetStateId_Equal(Long stateId) { regStateId(CK_EQ, stateId); } /** * GreaterThan(&gt;). And NullIgnored, OnlyOnceRegistered. <br /> * STATEID: {IX, NUMBER(18), FK to BURISTATE} * @param stateId The value of stateId as greaterThan. */ public void setStateId_GreaterThan(Long stateId) { regStateId(CK_GT, stateId); } /** * LessThan(&lt;). And NullIgnored, OnlyOnceRegistered. <br /> * STATEID: {IX, NUMBER(18), FK to BURISTATE} * @param stateId The value of stateId as lessThan. */ public void setStateId_LessThan(Long stateId) { regStateId(CK_LT, stateId); } /** * GreaterEqual(&gt;=). And NullIgnored, OnlyOnceRegistered. <br /> * STATEID: {IX, NUMBER(18), FK to BURISTATE} * @param stateId The value of stateId as greaterEqual. */ public void setStateId_GreaterEqual(Long stateId) { regStateId(CK_GE, stateId); } /** * LessEqual(&lt;=). And NullIgnored, OnlyOnceRegistered. <br /> * STATEID: {IX, NUMBER(18), FK to BURISTATE} * @param stateId The value of stateId as lessEqual. */ public void setStateId_LessEqual(Long stateId) { regStateId(CK_LE, stateId); } /** * RangeOf with various options. (versatile) <br /> * {(default) minNumber &lt;= column &lt;= maxNumber} <br /> * And NullIgnored, OnlyOnceRegistered. <br /> * STATEID: {IX, NUMBER(18), FK to BURISTATE} * @param minNumber The min number of stateId. (NullAllowed) * @param maxNumber The max number of stateId. (NullAllowed) * @param rangeOfOption The option of range-of. (NotNull) */ public void setStateId_RangeOf(Long minNumber, Long maxNumber, RangeOfOption rangeOfOption) { regROO(minNumber, maxNumber, getCValueStateId(), "STATEID", rangeOfOption); } /** * InScope {in (1, 2)}. And NullIgnored, NullElementIgnored, SeveralRegistered. <br /> * STATEID: {IX, NUMBER(18), FK to BURISTATE} * @param stateIdList The collection of stateId as inScope. */ public void setStateId_InScope(Collection<Long> stateIdList) { doSetStateId_InScope(stateIdList); } protected void doSetStateId_InScope(Collection<Long> stateIdList) { regINS(CK_INS, cTL(stateIdList), getCValueStateId(), "STATEID"); } /** * NotInScope {not in (1, 2)}. And NullIgnored, NullElementIgnored, SeveralRegistered. <br /> * STATEID: {IX, NUMBER(18), FK to BURISTATE} * @param stateIdList The collection of stateId as notInScope. */ public void setStateId_NotInScope(Collection<Long> stateIdList) { doSetStateId_NotInScope(stateIdList); } protected void doSetStateId_NotInScope(Collection<Long> stateIdList) { regINS(CK_NINS, cTL(stateIdList), getCValueStateId(), "STATEID"); } /** * Set up InScopeRelation (sub-query). <br /> * {in (select STATEID from BURISTATE where ...)} <br /> * BURISTATE by my STATEID, named 'buriState'. * @param subQuery The sub-query of BuriState for 'in-scope'. (NotNull) */ public void inScopeBuriState(SubQuery<BuriStateCB> subQuery) { assertObjectNotNull("subQuery<BuriStateCB>", subQuery); BuriStateCB cb = new BuriStateCB(); cb.xsetupForInScopeRelation(this); subQuery.query(cb); String subQueryPropertyName = keepStateId_InScopeRelation_BuriState(cb.query()); // for saving query-value. registerInScopeRelation(cb.query(), "STATEID", "STATEID", subQueryPropertyName, "buriState"); } public abstract String keepStateId_InScopeRelation_BuriState(BuriStateCQ subQuery); /** * Set up NotInScopeRelation (sub-query). <br /> * {not in (select STATEID from BURISTATE where ...)} <br /> * BURISTATE by my STATEID, named 'buriState'. * @param subQuery The sub-query of BuriState for 'not in-scope'. (NotNull) */ public void notInScopeBuriState(SubQuery<BuriStateCB> subQuery) { assertObjectNotNull("subQuery<BuriStateCB>", subQuery); BuriStateCB cb = new BuriStateCB(); cb.xsetupForInScopeRelation(this); subQuery.query(cb); String subQueryPropertyName = keepStateId_NotInScopeRelation_BuriState(cb.query()); // for saving query-value. registerNotInScopeRelation(cb.query(), "STATEID", "STATEID", subQueryPropertyName, "buriState"); } public abstract String keepStateId_NotInScopeRelation_BuriState(BuriStateCQ subQuery); /** * IsNull {is null}. And OnlyOnceRegistered. <br /> * STATEID: {IX, NUMBER(18), FK to BURISTATE} */ public void setStateId_IsNull() { regStateId(CK_ISN, DOBJ); } /** * IsNotNull {is not null}. And OnlyOnceRegistered. <br /> * STATEID: {IX, NUMBER(18), FK to BURISTATE} */ public void setStateId_IsNotNull() { regStateId(CK_ISNN, DOBJ); } protected void regStateId(ConditionKey k, Object v) { regQ(k, v, getCValueStateId(), "STATEID"); } abstract protected ConditionValue getCValueStateId(); /** * Equal(=). And NullIgnored, OnlyOnceRegistered. <br /> * BURIUSERID: {IX, NUMBER(18), FK to BURIUSER} * @param buriUserId The value of buriUserId as equal. */ public void setBuriUserId_Equal(Long buriUserId) { doSetBuriUserId_Equal(buriUserId); } protected void doSetBuriUserId_Equal(Long buriUserId) { regBuriUserId(CK_EQ, buriUserId); } /** * GreaterThan(&gt;). And NullIgnored, OnlyOnceRegistered. <br /> * BURIUSERID: {IX, NUMBER(18), FK to BURIUSER} * @param buriUserId The value of buriUserId as greaterThan. */ public void setBuriUserId_GreaterThan(Long buriUserId) { regBuriUserId(CK_GT, buriUserId); } /** * LessThan(&lt;). And NullIgnored, OnlyOnceRegistered. <br /> * BURIUSERID: {IX, NUMBER(18), FK to BURIUSER} * @param buriUserId The value of buriUserId as lessThan. */ public void setBuriUserId_LessThan(Long buriUserId) { regBuriUserId(CK_LT, buriUserId); } /** * GreaterEqual(&gt;=). And NullIgnored, OnlyOnceRegistered. <br /> * BURIUSERID: {IX, NUMBER(18), FK to BURIUSER} * @param buriUserId The value of buriUserId as greaterEqual. */ public void setBuriUserId_GreaterEqual(Long buriUserId) { regBuriUserId(CK_GE, buriUserId); } /** * LessEqual(&lt;=). And NullIgnored, OnlyOnceRegistered. <br /> * BURIUSERID: {IX, NUMBER(18), FK to BURIUSER} * @param buriUserId The value of buriUserId as lessEqual. */ public void setBuriUserId_LessEqual(Long buriUserId) { regBuriUserId(CK_LE, buriUserId); } /** * RangeOf with various options. (versatile) <br /> * {(default) minNumber &lt;= column &lt;= maxNumber} <br /> * And NullIgnored, OnlyOnceRegistered. <br /> * BURIUSERID: {IX, NUMBER(18), FK to BURIUSER} * @param minNumber The min number of buriUserId. (NullAllowed) * @param maxNumber The max number of buriUserId. (NullAllowed) * @param rangeOfOption The option of range-of. (NotNull) */ public void setBuriUserId_RangeOf(Long minNumber, Long maxNumber, RangeOfOption rangeOfOption) { regROO(minNumber, maxNumber, getCValueBuriUserId(), "BURIUSERID", rangeOfOption); } /** * InScope {in (1, 2)}. And NullIgnored, NullElementIgnored, SeveralRegistered. <br /> * BURIUSERID: {IX, NUMBER(18), FK to BURIUSER} * @param buriUserIdList The collection of buriUserId as inScope. */ public void setBuriUserId_InScope(Collection<Long> buriUserIdList) { doSetBuriUserId_InScope(buriUserIdList); } protected void doSetBuriUserId_InScope(Collection<Long> buriUserIdList) { regINS(CK_INS, cTL(buriUserIdList), getCValueBuriUserId(), "BURIUSERID"); } /** * NotInScope {not in (1, 2)}. And NullIgnored, NullElementIgnored, SeveralRegistered. <br /> * BURIUSERID: {IX, NUMBER(18), FK to BURIUSER} * @param buriUserIdList The collection of buriUserId as notInScope. */ public void setBuriUserId_NotInScope(Collection<Long> buriUserIdList) { doSetBuriUserId_NotInScope(buriUserIdList); } protected void doSetBuriUserId_NotInScope(Collection<Long> buriUserIdList) { regINS(CK_NINS, cTL(buriUserIdList), getCValueBuriUserId(), "BURIUSERID"); } /** * Set up InScopeRelation (sub-query). <br /> * {in (select BURIUSERID from BURIUSER where ...)} <br /> * BURIUSER by my BURIUSERID, named 'buriUser'. * @param subQuery The sub-query of BuriUser for 'in-scope'. (NotNull) */ public void inScopeBuriUser(SubQuery<BuriUserCB> subQuery) { assertObjectNotNull("subQuery<BuriUserCB>", subQuery); BuriUserCB cb = new BuriUserCB(); cb.xsetupForInScopeRelation(this); subQuery.query(cb); String subQueryPropertyName = keepBuriUserId_InScopeRelation_BuriUser(cb.query()); // for saving query-value. registerInScopeRelation(cb.query(), "BURIUSERID", "BURIUSERID", subQueryPropertyName, "buriUser"); } public abstract String keepBuriUserId_InScopeRelation_BuriUser(BuriUserCQ subQuery); /** * Set up NotInScopeRelation (sub-query). <br /> * {not in (select BURIUSERID from BURIUSER where ...)} <br /> * BURIUSER by my BURIUSERID, named 'buriUser'. * @param subQuery The sub-query of BuriUser for 'not in-scope'. (NotNull) */ public void notInScopeBuriUser(SubQuery<BuriUserCB> subQuery) { assertObjectNotNull("subQuery<BuriUserCB>", subQuery); BuriUserCB cb = new BuriUserCB(); cb.xsetupForInScopeRelation(this); subQuery.query(cb); String subQueryPropertyName = keepBuriUserId_NotInScopeRelation_BuriUser(cb.query()); // for saving query-value. registerNotInScopeRelation(cb.query(), "BURIUSERID", "BURIUSERID", subQueryPropertyName, "buriUser"); } public abstract String keepBuriUserId_NotInScopeRelation_BuriUser(BuriUserCQ subQuery); /** * IsNull {is null}. And OnlyOnceRegistered. <br /> * BURIUSERID: {IX, NUMBER(18), FK to BURIUSER} */ public void setBuriUserId_IsNull() { regBuriUserId(CK_ISN, DOBJ); } /** * IsNotNull {is not null}. And OnlyOnceRegistered. <br /> * BURIUSERID: {IX, NUMBER(18), FK to BURIUSER} */ public void setBuriUserId_IsNotNull() { regBuriUserId(CK_ISNN, DOBJ); } protected void regBuriUserId(ConditionKey k, Object v) { regQ(k, v, getCValueBuriUserId(), "BURIUSERID"); } abstract protected ConditionValue getCValueBuriUserId(); /** * Equal(=). And NullIgnored, OnlyOnceRegistered. <br /> * INSERTDATE: {NotNull, TIMESTAMP(6)(11, 6)} * @param insertDate The value of insertDate as equal. */ public void setInsertDate_Equal(java.sql.Timestamp insertDate) { regInsertDate(CK_EQ, insertDate); } /** * GreaterThan(&gt;). And NullIgnored, OnlyOnceRegistered. <br /> * INSERTDATE: {NotNull, TIMESTAMP(6)(11, 6)} * @param insertDate The value of insertDate as greaterThan. */ public void setInsertDate_GreaterThan(java.sql.Timestamp insertDate) { regInsertDate(CK_GT, insertDate); } /** * LessThan(&lt;). And NullIgnored, OnlyOnceRegistered. <br /> * INSERTDATE: {NotNull, TIMESTAMP(6)(11, 6)} * @param insertDate The value of insertDate as lessThan. */ public void setInsertDate_LessThan(java.sql.Timestamp insertDate) { regInsertDate(CK_LT, insertDate); } /** * GreaterEqual(&gt;=). And NullIgnored, OnlyOnceRegistered. <br /> * INSERTDATE: {NotNull, TIMESTAMP(6)(11, 6)} * @param insertDate The value of insertDate as greaterEqual. */ public void setInsertDate_GreaterEqual(java.sql.Timestamp insertDate) { regInsertDate(CK_GE, insertDate); } /** * LessEqual(&lt;=). And NullIgnored, OnlyOnceRegistered. <br /> * INSERTDATE: {NotNull, TIMESTAMP(6)(11, 6)} * @param insertDate The value of insertDate as lessEqual. */ public void setInsertDate_LessEqual(java.sql.Timestamp insertDate) { regInsertDate(CK_LE, insertDate); } /** * FromTo with various options. (versatile) <br /> * {(default) fromDatetime &lt;= column &lt;= toDatetime} <br /> * And NullIgnored, OnlyOnceRegistered. <br /> * INSERTDATE: {NotNull, TIMESTAMP(6)(11, 6)} * @param fromDatetime The from-datetime(yyyy/MM/dd HH:mm:ss.SSS) of insertDate. (NullAllowed) * @param toDatetime The to-datetime(yyyy/MM/dd HH:mm:ss.SSS) of insertDate. (NullAllowed) * @param fromToOption The option of from-to. (NotNull) */ public void setInsertDate_FromTo(java.util.Date fromDatetime, java.util.Date toDatetime, FromToOption fromToOption) { regFTQ((fromDatetime != null ? new java.sql.Timestamp(fromDatetime.getTime()) : null), (toDatetime != null ? new java.sql.Timestamp(toDatetime.getTime()) : null), getCValueInsertDate(), "INSERTDATE", fromToOption); } /** * DateFromTo. (Date means yyyy/MM/dd) <br /> * {fromDate &lt;= column &lt; toDate + 1 day} <br /> * And NullIgnored, OnlyOnceRegistered. <br /> * INSERTDATE: {NotNull, TIMESTAMP(6)(11, 6)} * <pre> * e.g. from:{2007/04/10 08:24:53} to:{2007/04/16 14:36:29} * --&gt; column &gt;= '2007/04/10 00:00:00' * and column <span style="color: #FD4747">&lt; '2007/04/17 00:00:00'</span> * </pre> * @param fromDate The from-date(yyyy/MM/dd) of insertDate. (NullAllowed) * @param toDate The to-date(yyyy/MM/dd) of insertDate. (NullAllowed) */ public void setInsertDate_DateFromTo(java.util.Date fromDate, java.util.Date toDate) { setInsertDate_FromTo(fromDate, toDate, new DateFromToOption()); } /** * InScope {in ('1965-03-03', '1966-09-15')}. And NullIgnored, NullElementIgnored, SeveralRegistered. <br /> * INSERTDATE: {NotNull, TIMESTAMP(6)(11, 6)} * @param insertDateList The collection of insertDate as inScope. */ public void setInsertDate_InScope(Collection<java.sql.Timestamp> insertDateList) { doSetInsertDate_InScope(insertDateList); } protected void doSetInsertDate_InScope(Collection<java.sql.Timestamp> insertDateList) { regINS(CK_INS, cTL(insertDateList), getCValueInsertDate(), "INSERTDATE"); } /** * NotInScope {not in ('1965-03-03', '1966-09-15')}. And NullIgnored, NullElementIgnored, SeveralRegistered. <br /> * INSERTDATE: {NotNull, TIMESTAMP(6)(11, 6)} * @param insertDateList The collection of insertDate as notInScope. */ public void setInsertDate_NotInScope(Collection<java.sql.Timestamp> insertDateList) { doSetInsertDate_NotInScope(insertDateList); } protected void doSetInsertDate_NotInScope(Collection<java.sql.Timestamp> insertDateList) { regINS(CK_NINS, cTL(insertDateList), getCValueInsertDate(), "INSERTDATE"); } protected void regInsertDate(ConditionKey k, Object v) { regQ(k, v, getCValueInsertDate(), "INSERTDATE"); } abstract protected ConditionValue getCValueInsertDate(); /** * Equal(=). And NullIgnored, OnlyOnceRegistered. <br /> * DELETEDATE: {NotNull, TIMESTAMP(6)(11, 6)} * @param deleteDate The value of deleteDate as equal. */ public void setDeleteDate_Equal(java.sql.Timestamp deleteDate) { regDeleteDate(CK_EQ, deleteDate); } /** * GreaterThan(&gt;). And NullIgnored, OnlyOnceRegistered. <br /> * DELETEDATE: {NotNull, TIMESTAMP(6)(11, 6)} * @param deleteDate The value of deleteDate as greaterThan. */ public void setDeleteDate_GreaterThan(java.sql.Timestamp deleteDate) { regDeleteDate(CK_GT, deleteDate); } /** * LessThan(&lt;). And NullIgnored, OnlyOnceRegistered. <br /> * DELETEDATE: {NotNull, TIMESTAMP(6)(11, 6)} * @param deleteDate The value of deleteDate as lessThan. */ public void setDeleteDate_LessThan(java.sql.Timestamp deleteDate) { regDeleteDate(CK_LT, deleteDate); } /** * GreaterEqual(&gt;=). And NullIgnored, OnlyOnceRegistered. <br /> * DELETEDATE: {NotNull, TIMESTAMP(6)(11, 6)} * @param deleteDate The value of deleteDate as greaterEqual. */ public void setDeleteDate_GreaterEqual(java.sql.Timestamp deleteDate) { regDeleteDate(CK_GE, deleteDate); } /** * LessEqual(&lt;=). And NullIgnored, OnlyOnceRegistered. <br /> * DELETEDATE: {NotNull, TIMESTAMP(6)(11, 6)} * @param deleteDate The value of deleteDate as lessEqual. */ public void setDeleteDate_LessEqual(java.sql.Timestamp deleteDate) { regDeleteDate(CK_LE, deleteDate); } /** * FromTo with various options. (versatile) <br /> * {(default) fromDatetime &lt;= column &lt;= toDatetime} <br /> * And NullIgnored, OnlyOnceRegistered. <br /> * DELETEDATE: {NotNull, TIMESTAMP(6)(11, 6)} * @param fromDatetime The from-datetime(yyyy/MM/dd HH:mm:ss.SSS) of deleteDate. (NullAllowed) * @param toDatetime The to-datetime(yyyy/MM/dd HH:mm:ss.SSS) of deleteDate. (NullAllowed) * @param fromToOption The option of from-to. (NotNull) */ public void setDeleteDate_FromTo(java.util.Date fromDatetime, java.util.Date toDatetime, FromToOption fromToOption) { regFTQ((fromDatetime != null ? new java.sql.Timestamp(fromDatetime.getTime()) : null), (toDatetime != null ? new java.sql.Timestamp(toDatetime.getTime()) : null), getCValueDeleteDate(), "DELETEDATE", fromToOption); } /** * DateFromTo. (Date means yyyy/MM/dd) <br /> * {fromDate &lt;= column &lt; toDate + 1 day} <br /> * And NullIgnored, OnlyOnceRegistered. <br /> * DELETEDATE: {NotNull, TIMESTAMP(6)(11, 6)} * <pre> * e.g. from:{2007/04/10 08:24:53} to:{2007/04/16 14:36:29} * --&gt; column &gt;= '2007/04/10 00:00:00' * and column <span style="color: #FD4747">&lt; '2007/04/17 00:00:00'</span> * </pre> * @param fromDate The from-date(yyyy/MM/dd) of deleteDate. (NullAllowed) * @param toDate The to-date(yyyy/MM/dd) of deleteDate. (NullAllowed) */ public void setDeleteDate_DateFromTo(java.util.Date fromDate, java.util.Date toDate) { setDeleteDate_FromTo(fromDate, toDate, new DateFromToOption()); } /** * InScope {in ('1965-03-03', '1966-09-15')}. And NullIgnored, NullElementIgnored, SeveralRegistered. <br /> * DELETEDATE: {NotNull, TIMESTAMP(6)(11, 6)} * @param deleteDateList The collection of deleteDate as inScope. */ public void setDeleteDate_InScope(Collection<java.sql.Timestamp> deleteDateList) { doSetDeleteDate_InScope(deleteDateList); } protected void doSetDeleteDate_InScope(Collection<java.sql.Timestamp> deleteDateList) { regINS(CK_INS, cTL(deleteDateList), getCValueDeleteDate(), "DELETEDATE"); } /** * NotInScope {not in ('1965-03-03', '1966-09-15')}. And NullIgnored, NullElementIgnored, SeveralRegistered. <br /> * DELETEDATE: {NotNull, TIMESTAMP(6)(11, 6)} * @param deleteDateList The collection of deleteDate as notInScope. */ public void setDeleteDate_NotInScope(Collection<java.sql.Timestamp> deleteDateList) { doSetDeleteDate_NotInScope(deleteDateList); } protected void doSetDeleteDate_NotInScope(Collection<java.sql.Timestamp> deleteDateList) { regINS(CK_NINS, cTL(deleteDateList), getCValueDeleteDate(), "DELETEDATE"); } protected void regDeleteDate(ConditionKey k, Object v) { regQ(k, v, getCValueDeleteDate(), "DELETEDATE"); } abstract protected ConditionValue getCValueDeleteDate(); // =================================================================================== // ScalarCondition // =============== /** * Prepare ScalarCondition as equal. <br /> * {where FOO = (select max(BAR) from ...) * <pre> * cb.query().<span style="color: #FD4747">scalar_Equal()</span>.max(new SubQuery&lt;BuriStateUserCB&gt;() { * public void query(BuriStateUserCB subCB) { * subCB.specify().setXxx... <span style="color: #3F7E5E">// derived column for function</span> * subCB.query().setYyy... * } * }); * </pre> * @return The object to set up a function. (NotNull) */ public HpSSQFunction<BuriStateUserCB> scalar_Equal() { return xcreateSSQFunction(CK_EQ.getOperand()); } /** * Prepare ScalarCondition as equal. <br /> * {where FOO &lt;&gt; (select max(BAR) from ...) * <pre> * cb.query().<span style="color: #FD4747">scalar_NotEqual()</span>.max(new SubQuery&lt;BuriStateUserCB&gt;() { * public void query(BuriStateUserCB subCB) { * subCB.specify().setXxx... <span style="color: #3F7E5E">// derived column for function</span> * subCB.query().setYyy... * } * }); * </pre> * @return The object to set up a function. (NotNull) */ public HpSSQFunction<BuriStateUserCB> scalar_NotEqual() { return xcreateSSQFunction(CK_NES.getOperand()); } /** * Prepare ScalarCondition as greaterThan. <br /> * {where FOO &gt; (select max(BAR) from ...) * <pre> * cb.query().<span style="color: #FD4747">scalar_GreaterThan()</span>.max(new SubQuery&lt;BuriStateUserCB&gt;() { * public void query(BuriStateUserCB subCB) { * subCB.specify().setFoo... <span style="color: #3F7E5E">// derived column for function</span> * subCB.query().setBar... * } * }); * </pre> * @return The object to set up a function. (NotNull) */ public HpSSQFunction<BuriStateUserCB> scalar_GreaterThan() { return xcreateSSQFunction(CK_GT.getOperand()); } /** * Prepare ScalarCondition as lessThan. <br /> * {where FOO &lt; (select max(BAR) from ...) * <pre> * cb.query().<span style="color: #FD4747">scalar_LessThan()</span>.max(new SubQuery&lt;BuriStateUserCB&gt;() { * public void query(BuriStateUserCB subCB) { * subCB.specify().setFoo... <span style="color: #3F7E5E">// derived column for function</span> * subCB.query().setBar... * } * }); * </pre> * @return The object to set up a function. (NotNull) */ public HpSSQFunction<BuriStateUserCB> scalar_LessThan() { return xcreateSSQFunction(CK_LT.getOperand()); } /** * Prepare ScalarCondition as greaterEqual. <br /> * {where FOO &gt;= (select max(BAR) from ...) * <pre> * cb.query().<span style="color: #FD4747">scalar_GreaterEqual()</span>.max(new SubQuery&lt;BuriStateUserCB&gt;() { * public void query(BuriStateUserCB subCB) { * subCB.specify().setFoo... <span style="color: #3F7E5E">// derived column for function</span> * subCB.query().setBar... * } * }); * </pre> * @return The object to set up a function. (NotNull) */ public HpSSQFunction<BuriStateUserCB> scalar_GreaterEqual() { return xcreateSSQFunction(CK_GE.getOperand()); } /** * Prepare ScalarCondition as lessEqual. <br /> * {where FOO &lt;= (select max(BAR) from ...) * <pre> * cb.query().<span style="color: #FD4747">scalar_LessEqual()</span>.max(new SubQuery&lt;BuriStateUserCB&gt;() { * public void query(BuriStateUserCB subCB) { * subCB.specify().setFoo... <span style="color: #3F7E5E">// derived column for function</span> * subCB.query().setBar... * } * }); * </pre> * @return The object to set up a function. (NotNull) */ public HpSSQFunction<BuriStateUserCB> scalar_LessEqual() { return xcreateSSQFunction(CK_LE.getOperand()); } protected HpSSQFunction<BuriStateUserCB> xcreateSSQFunction(final String operand) { return new HpSSQFunction<BuriStateUserCB>(new HpSSQSetupper<BuriStateUserCB>() { public void setup(String function, SubQuery<BuriStateUserCB> subQuery, HpSSQOption<BuriStateUserCB> option) { xscalarCondition(function, subQuery, operand, option); } }); } protected void xscalarCondition(String function, SubQuery<BuriStateUserCB> subQuery, String operand, HpSSQOption<BuriStateUserCB> option) { assertObjectNotNull("subQuery<BuriStateUserCB>", subQuery); BuriStateUserCB cb = xcreateScalarConditionCB(); subQuery.query(cb); String subQueryPropertyName = keepScalarCondition(cb.query()); // for saving query-value option.setPartitionByCBean(xcreateScalarConditionPartitionByCB()); // for using partition-by registerScalarCondition(function, cb.query(), subQueryPropertyName, operand, option); } public abstract String keepScalarCondition(BuriStateUserCQ subQuery); protected BuriStateUserCB xcreateScalarConditionCB() { BuriStateUserCB cb = new BuriStateUserCB(); cb.xsetupForScalarCondition(this); return cb; } protected BuriStateUserCB xcreateScalarConditionPartitionByCB() { BuriStateUserCB cb = new BuriStateUserCB(); cb.xsetupForScalarConditionPartitionBy(this); return cb; } // =================================================================================== // MyselfDerived // ============= public void xsmyselfDerive(String function, SubQuery<BuriStateUserCB> subQuery, String aliasName, DerivedReferrerOption option) { assertObjectNotNull("subQuery<BuriStateUserCB>", subQuery); BuriStateUserCB cb = new BuriStateUserCB(); cb.xsetupForDerivedReferrer(this); subQuery.query(cb); String subQueryPropertyName = keepSpecifyMyselfDerived(cb.query()); // for saving query-value. registerSpecifyMyselfDerived(function, cb.query(), "STATEUSERID", "STATEUSERID", subQueryPropertyName, "myselfDerived", aliasName, option); } public abstract String keepSpecifyMyselfDerived(BuriStateUserCQ subQuery); /** * Prepare for (Query)MyselfDerived (SubQuery). * @return The object to set up a function for myself table. (NotNull) */ public HpQDRFunction<BuriStateUserCB> myselfDerived() { return xcreateQDRFunctionMyselfDerived(); } protected HpQDRFunction<BuriStateUserCB> xcreateQDRFunctionMyselfDerived() { return new HpQDRFunction<BuriStateUserCB>(new HpQDRSetupper<BuriStateUserCB>() { public void setup(String function, SubQuery<BuriStateUserCB> subQuery, String operand, Object value, DerivedReferrerOption option) { xqderiveMyselfDerived(function, subQuery, operand, value, option); } }); } public void xqderiveMyselfDerived(String function, SubQuery<BuriStateUserCB> subQuery, String operand, Object value, DerivedReferrerOption option) { assertObjectNotNull("subQuery<BuriStateUserCB>", subQuery); BuriStateUserCB cb = new BuriStateUserCB(); cb.xsetupForDerivedReferrer(this); subQuery.query(cb); String subQueryPropertyName = keepQueryMyselfDerived(cb.query()); // for saving query-value. String parameterPropertyName = keepQueryMyselfDerivedParameter(value); registerQueryMyselfDerived(function, cb.query(), "STATEUSERID", "STATEUSERID", subQueryPropertyName, "myselfDerived", operand, value, parameterPropertyName, option); } public abstract String keepQueryMyselfDerived(BuriStateUserCQ subQuery); public abstract String keepQueryMyselfDerivedParameter(Object parameterValue); // =================================================================================== // MyselfExists // ============ /** * Prepare for MyselfExists (SubQuery). * @param subQuery The implementation of sub query. (NotNull) */ public void myselfExists(SubQuery<BuriStateUserCB> subQuery) { assertObjectNotNull("subQuery<BuriStateUserCB>", subQuery); BuriStateUserCB cb = new BuriStateUserCB(); cb.xsetupForMyselfExists(this); subQuery.query(cb); String subQueryPropertyName = keepMyselfExists(cb.query()); // for saving query-value. registerMyselfExists(cb.query(), subQueryPropertyName); } public abstract String keepMyselfExists(BuriStateUserCQ subQuery); // =================================================================================== // MyselfInScope // ============= /** * Prepare for MyselfInScope (SubQuery). * @param subQuery The implementation of sub query. (NotNull) */ public void myselfInScope(SubQuery<BuriStateUserCB> subQuery) { assertObjectNotNull("subQuery<BuriStateUserCB>", subQuery); BuriStateUserCB cb = new BuriStateUserCB(); cb.xsetupForMyselfInScope(this); subQuery.query(cb); String subQueryPropertyName = keepMyselfInScope(cb.query()); // for saving query-value. registerMyselfInScope(cb.query(), subQueryPropertyName); } public abstract String keepMyselfInScope(BuriStateUserCQ subQuery); // =================================================================================== // Very Internal // ============= // very internal (for suppressing warn about 'Not Use Import') protected String xabCB() { return BuriStateUserCB.class.getName(); } protected String xabCQ() { return BuriStateUserCQ.class.getName(); } protected String xabLSO() { return LikeSearchOption.class.getName(); } protected String xabSSQS() { return HpSSQSetupper.class.getName(); } }
37,554
0.612798
0.602892
828
43.355072
36.424324
222
false
false
0
0
0
0
83
0.019891
0.713768
false
false
14
6e7d26e8fc97e19ce85e25446b1cb441df754592
22,926,535,432,757
f6748c453d728aecf6bc1da360c6c0d1ebe652ee
/sansecurekeyboard/src/test/java/com/globile/santander/mobisec/securekeyboard/SanKeyboardViewTest.java
4f0e25e256ae71fbebd8b8062ad9e20e71d84505
[]
no_license
mateus-pinheiro/securekeyboard-integration
https://github.com/mateus-pinheiro/securekeyboard-integration
d18a00a6dae0305823f24aa3ef549fe2903ea3b6
c459292dca92f987e5f962b7f4cc54f2d786f5ae
refs/heads/master
2021-01-06T05:48:52.401000
2020-02-17T23:14:01
2020-02-17T23:14:01
241,227,349
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.globile.santander.mobisec.securekeyboard; import static junit.framework.TestCase.assertEquals; import static junit.framework.TestCase.assertTrue; import static org.junit.Assert.assertFalse; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.spy; import static org.powermock.api.mockito.PowerMockito.verifyPrivate; import static org.powermock.api.mockito.PowerMockito.when; import android.text.Editable; import android.view.InflateException; import android.view.MotionEvent; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputConnection; import android.widget.ListView; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import com.globile.santander.mobisec.securekeyboard.aosp.KeyboardAOSP; import com.globile.santander.mobisec.securekeyboard.enums.ShiftMode; import com.globile.santander.mobisec.securekeyboard.enums.TopRowButtonsOptions; import com.globile.santander.mobisec.securekeyboard.keyboard.SanKeyboard; import com.globile.santander.mobisec.securekeyboard.keyboard.SanKeyboardManager; import com.globile.santander.mobisec.securekeyboard.keyboard.SanKeyboardType; import com.globile.santander.mobisec.securekeyboard.listeners.SanEventCallbacks; import com.globile.santander.mobisec.securekeyboard.listeners.SanTapJackedCallback; import com.globile.santander.mobisec.securekeyboard.utils.SanKeyboardUtils; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunnerDelegate; import org.powermock.reflect.Whitebox; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.android.controller.ActivityController; import org.robolectric.annotation.Config; @Config(sdk = 28) @RunWith(PowerMockRunner.class) @PowerMockRunnerDelegate(RobolectricTestRunner.class) //@PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "android.*"}) @PowerMockIgnore({"org.robolectric.*", "android.*"}) @PrepareForTest({SanKeyboardView.class, SelectLanguageDialog.class}) //@FixMethodOrder(MethodSorters.NAME_ASCENDING) // Not necessary only for OnShift public class SanKeyboardViewTest { // Robolectric > Mock Activity (mock context from real one for accesing resources) private ActivityController<AppCompatActivity> activityController; private AppCompatActivity activity; private SanKeyboardView sanKeyboardView; private SanKeyboard sanKeyboard; private SanKeyboardManager sanKeyboardManager; @Mock private MotionEvent motionEvent; @Mock private SanTapJackedCallback sanTapJackedCallback; @Mock private BaseSecureEditText secureEditText; @Mock private AlertDialog selectLanguageDialog; @Mock private ListView selectLanguageListOptionsView; @Mock private SanKeyboardView.SanKeyboardCallback sanKeyboardCallback; @Mock private InputConnection inputConnection; public SanKeyboardViewTest() { } @Before public void setupSanKeyboard() { // Init Mockito MockitoAnnotations.initMocks(this); setupMocks(); SanKeyboardManager.setSanTapJackedCallback(sanTapJackedCallback); sanKeyboardView = SanKeyboardUtils.createKeyboardView( activity.getWindow().getDecorView().findViewById(android.R.id.content)); sanKeyboardManager = new SanKeyboardManager(activity); sanKeyboard = sanKeyboardManager.getKeyboardForType(SanKeyboardType.ALPHA, TopRowButtonsOptions.NONE); sanKeyboardView.setKeyboard(sanKeyboard); } private void setupMocks() { activityController = Robolectric.buildActivity(AppCompatActivity.class); activity = activityController.get(); when(secureEditText.getKeyboardType()).thenReturn(SanKeyboardType.ALPHA); when(secureEditText.getTopRowButtons()).thenReturn(TopRowButtonsOptions.NONE); when(secureEditText.getText()).thenReturn(Editable.Factory.getInstance().newEditable("abc ")); when(secureEditText.onCreateInputConnection(any(EditorInfo.class))).thenReturn(inputConnection); } @Test(expected = InflateException.class) public void test_setTapJackedCallbackNull() { // Original exception is IllegalStateException because SanTapJackedCallback is null, but this exception // generates InflateException because Keyboard cannot be inflated ActivityController<AppCompatActivity> activityController = Robolectric.buildActivity(AppCompatActivity.class); AppCompatActivity activity = activityController.get(); SanKeyboardManager.setSanTapJackedCallback(null); SanKeyboardView sanKeyboardView = SanKeyboardUtils.createKeyboardView( activity.getWindow().getDecorView().findViewById(android.R.id.content)); SanKeyboardManager sanKeyboardManager = new SanKeyboardManager(activity); SanKeyboard sanKeyboard = sanKeyboardManager.getKeyboardForType(SanKeyboardType.ALPHA, TopRowButtonsOptions.NONE); sanKeyboardView.setKeyboard(sanKeyboard); } @Test public void test_OnKey_InputConnectioNull() { sanKeyboardView.onKey(119, new int[0]); verify(inputConnection, never()).commitText(eq("q"), eq(1)); } @Test public void test001_setKeyboard_Success() { sanKeyboardView.setKeyboard(sanKeyboard); assertEquals(sanKeyboard, sanKeyboardView.getKeyboard()); } @Test(expected = IllegalArgumentException.class) public void test002_setKeyboard_Fail() { sanKeyboardView.setKeyboard(mock(KeyboardAOSP.class)); } @Test public void test003_onFilterTouchEvent() { boolean touchEventDispatched = sanKeyboardView.onFilterTouchEventForSecurity(motionEvent); verify(sanTapJackedCallback, times(0)).onObscuredTouchEvent(motionEvent); assertTrue(touchEventDispatched); } @Test public void test004_onFilterTouchEvent_WindowIsObscured() { when(motionEvent.getFlags()).thenReturn(MotionEvent.FLAG_WINDOW_IS_OBSCURED); boolean touchEventDispatched = sanKeyboardView.onFilterTouchEventForSecurity(motionEvent); verify(sanTapJackedCallback, times(1)).onObscuredTouchEvent(motionEvent); assertFalse(touchEventDispatched); } @Test public void test005_onTouchEvent_DeletePressed() { SanKeyboard spy = spy(sanKeyboard); sanKeyboardView.setKeyboard(spy); sanKeyboardView.onPress(KeyboardAOSP.KEYCODE_DELETE); verify(spy, times(1)).getKeyByCode(KeyboardAOSP.KEYCODE_DELETE); when(motionEvent.getAction()).thenReturn(MotionEvent.ACTION_UP); sanKeyboardView.onTouchEvent(motionEvent); verify(spy, times(2)).getKeyByCode(KeyboardAOSP.KEYCODE_DELETE); } @Test public void test006_onTouchEvent_SpacePressed() { SanKeyboard spy = spy(sanKeyboard); sanKeyboardView.setKeyboard(spy); when(motionEvent.getAction()).thenReturn(MotionEvent.ACTION_UP); Whitebox.setInternalState(sanKeyboardView, "isSpacePressed", true); sanKeyboardView.onTouchEvent(motionEvent); verify(spy, times(1)).getKeyByCode(SanKeyboard.KEYCODE_SPACE); } // TODO: @Test public void test007_onTouchEvent_SpacePressed_Long() throws Exception { SanKeyboardView spyView = spy(sanKeyboardView); spyView.setKeyboard(sanKeyboard); // TODO: Remove this mock. It's to suppress calling to create and show Language Dialog becuase // Robolectric crash test on AlerDialog.Builder.create() line when(spyView, "getActivity").thenReturn(null); when(motionEvent.getAction()).thenReturn(MotionEvent.ACTION_UP); Whitebox.setInternalState(spyView, "isSpacePressed", true); sanKeyboard.getKeyByCode(SanKeyboard.KEYCODE_SPACE).pressed = true; // spyView.invalidateKey(0); // TODO: Fix NPE on getPaddingLeft() Whitebox.setInternalState(spyView, "isSpacePressed", true); /* // TODO: Make Robolectric totally compatible with PowerMockito in order to mock static method // that creates the Select Language Dialog. Right now, seems compatible, but @PrepareForTest // annotation is not working or is ignored and "mockStatic()" doesn't work mockStatic(SelectLanguageDialog.class); // Not working because @PrepareForTest is ignored ¿? doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { return null; } }).when(SelectLanguageDialog.class, "showSelectLanguageDialog"); Keyboard.Key spaceKey = spy.getKeyByCode(SanKeyboard.KEYCODE_SPACE); Whitebox.invokeMethod(spyView, "startLanguageDialog", spaceKey); */ } @Test public void test008_selectLanguageDialog_OnLanguageSelected() throws Exception { SanKeyboardView spyView = spy(sanKeyboardView); spyView.setKeyboard(sanKeyboard); when(selectLanguageDialog.getListView()).thenReturn(selectLanguageListOptionsView); when(selectLanguageListOptionsView.getCheckedItemPosition()).thenReturn(1); spyView.setInputConnection(secureEditText); Whitebox.invokeMethod(spyView, "onLanguageSelected", selectLanguageDialog); verifyPrivate(spyView, times(3)).invoke("changeModeTo", any()); } @Test public void test009_selectLanguageDialog_OnDismiss() throws Exception { sanKeyboardView.setInputConnection(secureEditText); Whitebox.invokeMethod(sanKeyboardView, "undoInsertSpace"); verify(secureEditText, times(2)).getText(); verify(secureEditText, times(1)).setText("abc"); } @Test public void test010_OnKey_Shift() { SanKeyboard sanKeyboard = new SanKeyboard(activity, R.xml.keyboard_alphanumeric); SanKeyboardView sanKeyboardView = SanKeyboardUtils.createKeyboardView( activity.getWindow().getDecorView().findViewById(android.R.id.content)); sanKeyboardView.setKeyboard(sanKeyboard); sanKeyboardView.setInputConnection(secureEditText); SanKeyboardView spyView = spy(sanKeyboardView); spyView.onKey(KeyboardAOSP.KEYCODE_SHIFT, new int[0]); // verifyPrivate(spyView).invoke("shiftTo", ShiftMode.class); } @Test public void test011_OnKey_ModeChange_Default() throws Exception { sanKeyboardView.setInputConnection(secureEditText); sanKeyboardView.slideIn(); SanKeyboardView spyView = spy(sanKeyboardView); spyView.onKey(KeyboardAOSP.KEYCODE_MODE_CHANGE, new int[0]); verifyPrivate(spyView, times(1)).invoke("changeModeTo", any()); } @Test public void test012_OnKey_ModeChange_SpecialChar() { when(secureEditText.getKeyboardType()).thenReturn(SanKeyboardType.SPECIAL_CHARACTER); sanKeyboard = sanKeyboardManager.getKeyboardForType(SanKeyboardType.SPECIAL_CHARACTER, TopRowButtonsOptions.NONE); sanKeyboardView.setKeyboard(sanKeyboard); assertEquals(sanKeyboardManager.getKeyboardType(), SanKeyboardType.SPECIAL_CHARACTER); Whitebox.setInternalState(sanKeyboardView, "keyboardsManager", sanKeyboardManager); sanKeyboardView.setInputConnection(secureEditText); SanKeyboardView spyView = spy(sanKeyboardView); spyView.onKey(KeyboardAOSP.KEYCODE_MODE_CHANGE, new int[0]); // verifyPrivate(spyView, times(1)).invoke("changeModeTo", any()); assertEquals(sanKeyboardManager.getKeyboardType(), SanKeyboardType.ALPHA); } @Test public void test013_OnKey_SpecialChange_Default() throws Exception { sanKeyboardView.setInputConnection(secureEditText); SanKeyboardView spyView = spy(sanKeyboardView); spyView.onKey(SanKeyboard.KEYCODE_SPECIAL_CHANGE, new int[0]); verifyPrivate(spyView, times(1)).invoke("changeModeTo", any()); } @Test public void test014_OnKey_SpecialChange_SpecialChars() { when(secureEditText.getKeyboardType()).thenReturn(SanKeyboardType.SPECIAL_CHARACTER); sanKeyboard = sanKeyboardManager.getKeyboardForType(SanKeyboardType.SPECIAL_CHARACTER, TopRowButtonsOptions.NONE); sanKeyboardView.setKeyboard(sanKeyboard); assertEquals(sanKeyboardManager.getKeyboardType(), SanKeyboardType.SPECIAL_CHARACTER); sanKeyboardView.setInputConnection(secureEditText); SanKeyboardView spyView = spy(sanKeyboardView); spyView.onKey(SanKeyboard.KEYCODE_SPECIAL_CHANGE, new int[0]); // verifyPrivate(spyView, times(1)).invoke("changeModeTo", any()); assertEquals(sanKeyboardView.getKeyboardType(), SanKeyboardType.SPECIAL_CHARACTER_NEXT); } @Test public void test015_OnKey_SpecialChange_SpecialCharsNext() { when(secureEditText.getKeyboardType()).thenReturn(SanKeyboardType.SPECIAL_CHARACTER_NEXT); sanKeyboard = sanKeyboardManager.getKeyboardForType(SanKeyboardType.SPECIAL_CHARACTER_NEXT, TopRowButtonsOptions.NONE); sanKeyboardView.setKeyboard(sanKeyboard); assertEquals(sanKeyboardManager.getKeyboardType(), SanKeyboardType.SPECIAL_CHARACTER_NEXT); sanKeyboardView.setInputConnection(secureEditText); SanKeyboardView spyView = spy(sanKeyboardView); spyView.onKey(SanKeyboard.KEYCODE_SPECIAL_CHANGE, new int[0]); // verifyPrivate(spyView, times(1)).invoke("changeModeTo", any()); assertEquals(sanKeyboardView.getKeyboardType(), SanKeyboardType.SPECIAL_CHARACTER); } @Test public void test016_OnKey_Cancel() { sanKeyboardView.setInputConnection(secureEditText); sanKeyboardView.setSanKeyboardCallback(sanKeyboardCallback); sanKeyboardView.slideIn(); SanKeyboardView spyView = spy(sanKeyboardView); spyView.onKey(SanKeyboard.KEYCODE_CANCEL, new int[0]); //verifyPrivate(spyView, times(1)).invoke("hide"); verify(sanKeyboardCallback, times(1)).onCancelClick(); } @Test public void test017_OnKey_Continue() { sanKeyboardView.setInputConnection(secureEditText); sanKeyboardView.setSanKeyboardCallback(sanKeyboardCallback); sanKeyboardView.slideIn(); SanKeyboardView spyView = spy(sanKeyboardView); spyView.onKey(SanKeyboard.KEYCODE_CONTINUE, new int[0]); // verifyPrivate(spyView, times(1)).invoke("hide"); verify(sanKeyboardCallback, times(1)).onContinueClick(); } @Test public void test018_OnKey_Done() throws Exception { sanKeyboardView.setInputConnection(secureEditText); SanKeyboardView spyView = spy(sanKeyboardView); spyView.onKey(SanKeyboard.KEYCODE_DONE, new int[0]); verifyPrivate(spyView, times(1)).invoke("hide"); } @Test public void test019_OnKey_Delete() { sanKeyboardView.setInputConnection(secureEditText); SanKeyboardView spyView = spy(sanKeyboardView); spyView.onKey(SanKeyboard.KEYCODE_DELETE, new int[0]); verify(inputConnection, times(1)).deleteSurroundingText(1, 0); } @Test public void test020_OnKey_Delete_WithSelectedText() { when(inputConnection.getSelectedText(0)).thenReturn("abc"); sanKeyboardView.setInputConnection(secureEditText); SanKeyboardView spyView = spy(sanKeyboardView); spyView.onKey(SanKeyboard.KEYCODE_DELETE, new int[0]); verify(inputConnection, times(1)).commitText("", 1); } @Test public void test021_OnKey_SecureKeyboard() { sanKeyboardView.setInputConnection(secureEditText); SanKeyboardView spyView = spy(sanKeyboardView); spyView.onKey(SanKeyboard.KEYCODE_SECURE_KEYBOARD, new int[0]); // This key has no action, so nothing to verify o assert } @Test public void test022_OnKey_DecimalPoint_AlphanumericKeyboard() throws Exception { sanKeyboardView.setInputConnection(secureEditText); SanKeyboardView spyView = spy(sanKeyboardView); spyView.onKey(SanKeyboard.KEYCODE_DECIMAL_POINT, new int[0]); verifyPrivate(spyView, times(1)).invoke("processRegularChar", SanKeyboard.KEYCODE_DECIMAL_POINT); } @Test public void test023_OnKey_DecimalPoint_DecimalKeyboard() throws Exception { when(secureEditText.getKeyboardType()).thenReturn(SanKeyboardType.DECIMAL); when(secureEditText.getText()).thenReturn(Editable.Factory.getInstance().newEditable("123")); sanKeyboard = sanKeyboardManager.getKeyboardForType(SanKeyboardType.DECIMAL, TopRowButtonsOptions.NONE); sanKeyboardView.setKeyboard(sanKeyboard); sanKeyboardView.setInputConnection(secureEditText); SanKeyboardView spyView = spy(sanKeyboardView); spyView.onKey(SanKeyboard.KEYCODE_DECIMAL_POINT, new int[0]); verifyPrivate(spyView, times(1)).invoke("processRegularChar", SanKeyboard.KEYCODE_DECIMAL_POINT); } @Test public void test024_OnKey_DecimalPoint_DecimalKeyboard_AlreadyHasPoint() { when(secureEditText.getKeyboardType()).thenReturn(SanKeyboardType.DECIMAL); when(secureEditText.getText()).thenReturn(Editable.Factory.getInstance().newEditable("123.45")); sanKeyboard = sanKeyboardManager.getKeyboardForType(SanKeyboardType.DECIMAL, TopRowButtonsOptions.NONE); sanKeyboardView.setKeyboard(sanKeyboard); sanKeyboardView.setInputConnection(secureEditText); SanKeyboardView spyView = spy(sanKeyboardView); spyView.onKey(SanKeyboard.KEYCODE_DECIMAL_POINT, new int[0]); verify(secureEditText, times(2)).getText(); /* // TODO: Not working: // Wanted but not invoked: // sanKeyboardView.isShifted(); // -> at com.globile.santander.mobisec.securekeyboard.SanKeyboardView.processRegularChar(SanKeyboardView.java:581) // // However, there were exactly 2 interactions with this mock: verifyPrivate(spyView).invoke("processRegularChar", SanKeyboard.KEYCODE_DECIMAL_POINT); */ } @Test public void test025_OnKey_RegularKey() throws Exception { sanKeyboardView.setInputConnection(secureEditText); SanKeyboardView spyView = spy(sanKeyboardView); spyView.onKey(119, new int[0]); verifyPrivate(spyView, times(1)).invoke("processRegularChar", 119); } @Test public void test026_processRegularChar_UpperCaseShifted() throws Exception { sanKeyboardView.setInputConnection(secureEditText); sanKeyboardView.setShifted(true); sanKeyboard.setInitialShift(ShiftMode.UPPER_CASE_SINGLE); sanKeyboardView.setKeyboard(sanKeyboard); Whitebox.invokeMethod(sanKeyboardView, "processRegularChar", 119); } @Test public void test027_OnKeyActionEvents() { sanKeyboardView.onRelease(1); sanKeyboardView.onText(""); sanKeyboardView.swipeLeft(); sanKeyboardView.swipeRight(); sanKeyboardView.swipeUp(); sanKeyboardView.swipeDown(); // These methods have no actions, so nothing to verify or to assert assertTrue(true); } @Test public void test028_slideIn() throws Exception { SanKeyboardView spyView = spy(sanKeyboardView); spyView.slideIn(); verifyPrivate(spyView).invoke("startAnimation", any()); } @Test public void test029_slideOut() throws Exception { SanKeyboardView spyView = spy(sanKeyboardView); spyView.slideOut(); verifyPrivate(spyView).invoke("startAnimation", any()); } @Test public void test030_onAnimationStart() { sanKeyboardView.onAnimationStart(); assertTrue(sanKeyboardView.isAnimating()); } @Test public void test031_onAnimationEnd() { sanKeyboardView.onAnimationEnd(); assertFalse(sanKeyboardView.isAnimating()); } @Test public void test031_onLongPress() { sanKeyboardView.setInputConnection(secureEditText); sanKeyboardView.setKeyboard(sanKeyboard); KeyboardAOSP.Key aKey = sanKeyboardView.getKeyboard().getKeyByCode(97); sanKeyboardView.onLongPress(aKey); assertTrue((Boolean) Whitebox.getInternalState(sanKeyboardView, "isLongPressDownDetected")); } @Test public void test032_setEventListener() { SanEventCallbacks sanEventCallbacks = mock(SanEventCallbacks.class); sanKeyboardView.setEventListener(sanEventCallbacks); assertEquals(sanEventCallbacks, sanKeyboardView.getEventListener()); } @Test public void test033_onTouchEvent_LongPressOnA() { when(motionEvent.getAction()).thenReturn(MotionEvent.ACTION_UP); sanKeyboardView.setInputConnection(secureEditText); sanKeyboardView.setKeyboard(sanKeyboard); assertFalse((Boolean) Whitebox.getInternalState(sanKeyboardView, "isLongPressDownDetected")); assertFalse((Boolean) Whitebox.getInternalState(sanKeyboardView, "isLongPressUpDetected")); KeyboardAOSP.Key aKey = sanKeyboardView.getKeyboard().getKeyByCode(97); sanKeyboardView.onLongPress(aKey); assertTrue((Boolean) Whitebox.getInternalState(sanKeyboardView, "isLongPressDownDetected")); assertFalse((Boolean) Whitebox.getInternalState(sanKeyboardView, "isLongPressUpDetected")); sanKeyboardView.onTouchEvent(motionEvent); assertTrue((Boolean) Whitebox.getInternalState(sanKeyboardView, "isLongPressDownDetected")); assertTrue((Boolean) Whitebox.getInternalState(sanKeyboardView, "isLongPressUpDetected")); assertTrue(sanKeyboardView.onTouchEvent(motionEvent)); assertFalse((Boolean) Whitebox.getInternalState(sanKeyboardView, "isLongPressDownDetected")); assertFalse((Boolean) Whitebox.getInternalState(sanKeyboardView, "isLongPressUpDetected")); } }
UTF-8
Java
22,587
java
SanKeyboardViewTest.java
Java
[]
null
[]
package com.globile.santander.mobisec.securekeyboard; import static junit.framework.TestCase.assertEquals; import static junit.framework.TestCase.assertTrue; import static org.junit.Assert.assertFalse; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.spy; import static org.powermock.api.mockito.PowerMockito.verifyPrivate; import static org.powermock.api.mockito.PowerMockito.when; import android.text.Editable; import android.view.InflateException; import android.view.MotionEvent; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputConnection; import android.widget.ListView; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import com.globile.santander.mobisec.securekeyboard.aosp.KeyboardAOSP; import com.globile.santander.mobisec.securekeyboard.enums.ShiftMode; import com.globile.santander.mobisec.securekeyboard.enums.TopRowButtonsOptions; import com.globile.santander.mobisec.securekeyboard.keyboard.SanKeyboard; import com.globile.santander.mobisec.securekeyboard.keyboard.SanKeyboardManager; import com.globile.santander.mobisec.securekeyboard.keyboard.SanKeyboardType; import com.globile.santander.mobisec.securekeyboard.listeners.SanEventCallbacks; import com.globile.santander.mobisec.securekeyboard.listeners.SanTapJackedCallback; import com.globile.santander.mobisec.securekeyboard.utils.SanKeyboardUtils; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunnerDelegate; import org.powermock.reflect.Whitebox; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.android.controller.ActivityController; import org.robolectric.annotation.Config; @Config(sdk = 28) @RunWith(PowerMockRunner.class) @PowerMockRunnerDelegate(RobolectricTestRunner.class) //@PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "android.*"}) @PowerMockIgnore({"org.robolectric.*", "android.*"}) @PrepareForTest({SanKeyboardView.class, SelectLanguageDialog.class}) //@FixMethodOrder(MethodSorters.NAME_ASCENDING) // Not necessary only for OnShift public class SanKeyboardViewTest { // Robolectric > Mock Activity (mock context from real one for accesing resources) private ActivityController<AppCompatActivity> activityController; private AppCompatActivity activity; private SanKeyboardView sanKeyboardView; private SanKeyboard sanKeyboard; private SanKeyboardManager sanKeyboardManager; @Mock private MotionEvent motionEvent; @Mock private SanTapJackedCallback sanTapJackedCallback; @Mock private BaseSecureEditText secureEditText; @Mock private AlertDialog selectLanguageDialog; @Mock private ListView selectLanguageListOptionsView; @Mock private SanKeyboardView.SanKeyboardCallback sanKeyboardCallback; @Mock private InputConnection inputConnection; public SanKeyboardViewTest() { } @Before public void setupSanKeyboard() { // Init Mockito MockitoAnnotations.initMocks(this); setupMocks(); SanKeyboardManager.setSanTapJackedCallback(sanTapJackedCallback); sanKeyboardView = SanKeyboardUtils.createKeyboardView( activity.getWindow().getDecorView().findViewById(android.R.id.content)); sanKeyboardManager = new SanKeyboardManager(activity); sanKeyboard = sanKeyboardManager.getKeyboardForType(SanKeyboardType.ALPHA, TopRowButtonsOptions.NONE); sanKeyboardView.setKeyboard(sanKeyboard); } private void setupMocks() { activityController = Robolectric.buildActivity(AppCompatActivity.class); activity = activityController.get(); when(secureEditText.getKeyboardType()).thenReturn(SanKeyboardType.ALPHA); when(secureEditText.getTopRowButtons()).thenReturn(TopRowButtonsOptions.NONE); when(secureEditText.getText()).thenReturn(Editable.Factory.getInstance().newEditable("abc ")); when(secureEditText.onCreateInputConnection(any(EditorInfo.class))).thenReturn(inputConnection); } @Test(expected = InflateException.class) public void test_setTapJackedCallbackNull() { // Original exception is IllegalStateException because SanTapJackedCallback is null, but this exception // generates InflateException because Keyboard cannot be inflated ActivityController<AppCompatActivity> activityController = Robolectric.buildActivity(AppCompatActivity.class); AppCompatActivity activity = activityController.get(); SanKeyboardManager.setSanTapJackedCallback(null); SanKeyboardView sanKeyboardView = SanKeyboardUtils.createKeyboardView( activity.getWindow().getDecorView().findViewById(android.R.id.content)); SanKeyboardManager sanKeyboardManager = new SanKeyboardManager(activity); SanKeyboard sanKeyboard = sanKeyboardManager.getKeyboardForType(SanKeyboardType.ALPHA, TopRowButtonsOptions.NONE); sanKeyboardView.setKeyboard(sanKeyboard); } @Test public void test_OnKey_InputConnectioNull() { sanKeyboardView.onKey(119, new int[0]); verify(inputConnection, never()).commitText(eq("q"), eq(1)); } @Test public void test001_setKeyboard_Success() { sanKeyboardView.setKeyboard(sanKeyboard); assertEquals(sanKeyboard, sanKeyboardView.getKeyboard()); } @Test(expected = IllegalArgumentException.class) public void test002_setKeyboard_Fail() { sanKeyboardView.setKeyboard(mock(KeyboardAOSP.class)); } @Test public void test003_onFilterTouchEvent() { boolean touchEventDispatched = sanKeyboardView.onFilterTouchEventForSecurity(motionEvent); verify(sanTapJackedCallback, times(0)).onObscuredTouchEvent(motionEvent); assertTrue(touchEventDispatched); } @Test public void test004_onFilterTouchEvent_WindowIsObscured() { when(motionEvent.getFlags()).thenReturn(MotionEvent.FLAG_WINDOW_IS_OBSCURED); boolean touchEventDispatched = sanKeyboardView.onFilterTouchEventForSecurity(motionEvent); verify(sanTapJackedCallback, times(1)).onObscuredTouchEvent(motionEvent); assertFalse(touchEventDispatched); } @Test public void test005_onTouchEvent_DeletePressed() { SanKeyboard spy = spy(sanKeyboard); sanKeyboardView.setKeyboard(spy); sanKeyboardView.onPress(KeyboardAOSP.KEYCODE_DELETE); verify(spy, times(1)).getKeyByCode(KeyboardAOSP.KEYCODE_DELETE); when(motionEvent.getAction()).thenReturn(MotionEvent.ACTION_UP); sanKeyboardView.onTouchEvent(motionEvent); verify(spy, times(2)).getKeyByCode(KeyboardAOSP.KEYCODE_DELETE); } @Test public void test006_onTouchEvent_SpacePressed() { SanKeyboard spy = spy(sanKeyboard); sanKeyboardView.setKeyboard(spy); when(motionEvent.getAction()).thenReturn(MotionEvent.ACTION_UP); Whitebox.setInternalState(sanKeyboardView, "isSpacePressed", true); sanKeyboardView.onTouchEvent(motionEvent); verify(spy, times(1)).getKeyByCode(SanKeyboard.KEYCODE_SPACE); } // TODO: @Test public void test007_onTouchEvent_SpacePressed_Long() throws Exception { SanKeyboardView spyView = spy(sanKeyboardView); spyView.setKeyboard(sanKeyboard); // TODO: Remove this mock. It's to suppress calling to create and show Language Dialog becuase // Robolectric crash test on AlerDialog.Builder.create() line when(spyView, "getActivity").thenReturn(null); when(motionEvent.getAction()).thenReturn(MotionEvent.ACTION_UP); Whitebox.setInternalState(spyView, "isSpacePressed", true); sanKeyboard.getKeyByCode(SanKeyboard.KEYCODE_SPACE).pressed = true; // spyView.invalidateKey(0); // TODO: Fix NPE on getPaddingLeft() Whitebox.setInternalState(spyView, "isSpacePressed", true); /* // TODO: Make Robolectric totally compatible with PowerMockito in order to mock static method // that creates the Select Language Dialog. Right now, seems compatible, but @PrepareForTest // annotation is not working or is ignored and "mockStatic()" doesn't work mockStatic(SelectLanguageDialog.class); // Not working because @PrepareForTest is ignored ¿? doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { return null; } }).when(SelectLanguageDialog.class, "showSelectLanguageDialog"); Keyboard.Key spaceKey = spy.getKeyByCode(SanKeyboard.KEYCODE_SPACE); Whitebox.invokeMethod(spyView, "startLanguageDialog", spaceKey); */ } @Test public void test008_selectLanguageDialog_OnLanguageSelected() throws Exception { SanKeyboardView spyView = spy(sanKeyboardView); spyView.setKeyboard(sanKeyboard); when(selectLanguageDialog.getListView()).thenReturn(selectLanguageListOptionsView); when(selectLanguageListOptionsView.getCheckedItemPosition()).thenReturn(1); spyView.setInputConnection(secureEditText); Whitebox.invokeMethod(spyView, "onLanguageSelected", selectLanguageDialog); verifyPrivate(spyView, times(3)).invoke("changeModeTo", any()); } @Test public void test009_selectLanguageDialog_OnDismiss() throws Exception { sanKeyboardView.setInputConnection(secureEditText); Whitebox.invokeMethod(sanKeyboardView, "undoInsertSpace"); verify(secureEditText, times(2)).getText(); verify(secureEditText, times(1)).setText("abc"); } @Test public void test010_OnKey_Shift() { SanKeyboard sanKeyboard = new SanKeyboard(activity, R.xml.keyboard_alphanumeric); SanKeyboardView sanKeyboardView = SanKeyboardUtils.createKeyboardView( activity.getWindow().getDecorView().findViewById(android.R.id.content)); sanKeyboardView.setKeyboard(sanKeyboard); sanKeyboardView.setInputConnection(secureEditText); SanKeyboardView spyView = spy(sanKeyboardView); spyView.onKey(KeyboardAOSP.KEYCODE_SHIFT, new int[0]); // verifyPrivate(spyView).invoke("shiftTo", ShiftMode.class); } @Test public void test011_OnKey_ModeChange_Default() throws Exception { sanKeyboardView.setInputConnection(secureEditText); sanKeyboardView.slideIn(); SanKeyboardView spyView = spy(sanKeyboardView); spyView.onKey(KeyboardAOSP.KEYCODE_MODE_CHANGE, new int[0]); verifyPrivate(spyView, times(1)).invoke("changeModeTo", any()); } @Test public void test012_OnKey_ModeChange_SpecialChar() { when(secureEditText.getKeyboardType()).thenReturn(SanKeyboardType.SPECIAL_CHARACTER); sanKeyboard = sanKeyboardManager.getKeyboardForType(SanKeyboardType.SPECIAL_CHARACTER, TopRowButtonsOptions.NONE); sanKeyboardView.setKeyboard(sanKeyboard); assertEquals(sanKeyboardManager.getKeyboardType(), SanKeyboardType.SPECIAL_CHARACTER); Whitebox.setInternalState(sanKeyboardView, "keyboardsManager", sanKeyboardManager); sanKeyboardView.setInputConnection(secureEditText); SanKeyboardView spyView = spy(sanKeyboardView); spyView.onKey(KeyboardAOSP.KEYCODE_MODE_CHANGE, new int[0]); // verifyPrivate(spyView, times(1)).invoke("changeModeTo", any()); assertEquals(sanKeyboardManager.getKeyboardType(), SanKeyboardType.ALPHA); } @Test public void test013_OnKey_SpecialChange_Default() throws Exception { sanKeyboardView.setInputConnection(secureEditText); SanKeyboardView spyView = spy(sanKeyboardView); spyView.onKey(SanKeyboard.KEYCODE_SPECIAL_CHANGE, new int[0]); verifyPrivate(spyView, times(1)).invoke("changeModeTo", any()); } @Test public void test014_OnKey_SpecialChange_SpecialChars() { when(secureEditText.getKeyboardType()).thenReturn(SanKeyboardType.SPECIAL_CHARACTER); sanKeyboard = sanKeyboardManager.getKeyboardForType(SanKeyboardType.SPECIAL_CHARACTER, TopRowButtonsOptions.NONE); sanKeyboardView.setKeyboard(sanKeyboard); assertEquals(sanKeyboardManager.getKeyboardType(), SanKeyboardType.SPECIAL_CHARACTER); sanKeyboardView.setInputConnection(secureEditText); SanKeyboardView spyView = spy(sanKeyboardView); spyView.onKey(SanKeyboard.KEYCODE_SPECIAL_CHANGE, new int[0]); // verifyPrivate(spyView, times(1)).invoke("changeModeTo", any()); assertEquals(sanKeyboardView.getKeyboardType(), SanKeyboardType.SPECIAL_CHARACTER_NEXT); } @Test public void test015_OnKey_SpecialChange_SpecialCharsNext() { when(secureEditText.getKeyboardType()).thenReturn(SanKeyboardType.SPECIAL_CHARACTER_NEXT); sanKeyboard = sanKeyboardManager.getKeyboardForType(SanKeyboardType.SPECIAL_CHARACTER_NEXT, TopRowButtonsOptions.NONE); sanKeyboardView.setKeyboard(sanKeyboard); assertEquals(sanKeyboardManager.getKeyboardType(), SanKeyboardType.SPECIAL_CHARACTER_NEXT); sanKeyboardView.setInputConnection(secureEditText); SanKeyboardView spyView = spy(sanKeyboardView); spyView.onKey(SanKeyboard.KEYCODE_SPECIAL_CHANGE, new int[0]); // verifyPrivate(spyView, times(1)).invoke("changeModeTo", any()); assertEquals(sanKeyboardView.getKeyboardType(), SanKeyboardType.SPECIAL_CHARACTER); } @Test public void test016_OnKey_Cancel() { sanKeyboardView.setInputConnection(secureEditText); sanKeyboardView.setSanKeyboardCallback(sanKeyboardCallback); sanKeyboardView.slideIn(); SanKeyboardView spyView = spy(sanKeyboardView); spyView.onKey(SanKeyboard.KEYCODE_CANCEL, new int[0]); //verifyPrivate(spyView, times(1)).invoke("hide"); verify(sanKeyboardCallback, times(1)).onCancelClick(); } @Test public void test017_OnKey_Continue() { sanKeyboardView.setInputConnection(secureEditText); sanKeyboardView.setSanKeyboardCallback(sanKeyboardCallback); sanKeyboardView.slideIn(); SanKeyboardView spyView = spy(sanKeyboardView); spyView.onKey(SanKeyboard.KEYCODE_CONTINUE, new int[0]); // verifyPrivate(spyView, times(1)).invoke("hide"); verify(sanKeyboardCallback, times(1)).onContinueClick(); } @Test public void test018_OnKey_Done() throws Exception { sanKeyboardView.setInputConnection(secureEditText); SanKeyboardView spyView = spy(sanKeyboardView); spyView.onKey(SanKeyboard.KEYCODE_DONE, new int[0]); verifyPrivate(spyView, times(1)).invoke("hide"); } @Test public void test019_OnKey_Delete() { sanKeyboardView.setInputConnection(secureEditText); SanKeyboardView spyView = spy(sanKeyboardView); spyView.onKey(SanKeyboard.KEYCODE_DELETE, new int[0]); verify(inputConnection, times(1)).deleteSurroundingText(1, 0); } @Test public void test020_OnKey_Delete_WithSelectedText() { when(inputConnection.getSelectedText(0)).thenReturn("abc"); sanKeyboardView.setInputConnection(secureEditText); SanKeyboardView spyView = spy(sanKeyboardView); spyView.onKey(SanKeyboard.KEYCODE_DELETE, new int[0]); verify(inputConnection, times(1)).commitText("", 1); } @Test public void test021_OnKey_SecureKeyboard() { sanKeyboardView.setInputConnection(secureEditText); SanKeyboardView spyView = spy(sanKeyboardView); spyView.onKey(SanKeyboard.KEYCODE_SECURE_KEYBOARD, new int[0]); // This key has no action, so nothing to verify o assert } @Test public void test022_OnKey_DecimalPoint_AlphanumericKeyboard() throws Exception { sanKeyboardView.setInputConnection(secureEditText); SanKeyboardView spyView = spy(sanKeyboardView); spyView.onKey(SanKeyboard.KEYCODE_DECIMAL_POINT, new int[0]); verifyPrivate(spyView, times(1)).invoke("processRegularChar", SanKeyboard.KEYCODE_DECIMAL_POINT); } @Test public void test023_OnKey_DecimalPoint_DecimalKeyboard() throws Exception { when(secureEditText.getKeyboardType()).thenReturn(SanKeyboardType.DECIMAL); when(secureEditText.getText()).thenReturn(Editable.Factory.getInstance().newEditable("123")); sanKeyboard = sanKeyboardManager.getKeyboardForType(SanKeyboardType.DECIMAL, TopRowButtonsOptions.NONE); sanKeyboardView.setKeyboard(sanKeyboard); sanKeyboardView.setInputConnection(secureEditText); SanKeyboardView spyView = spy(sanKeyboardView); spyView.onKey(SanKeyboard.KEYCODE_DECIMAL_POINT, new int[0]); verifyPrivate(spyView, times(1)).invoke("processRegularChar", SanKeyboard.KEYCODE_DECIMAL_POINT); } @Test public void test024_OnKey_DecimalPoint_DecimalKeyboard_AlreadyHasPoint() { when(secureEditText.getKeyboardType()).thenReturn(SanKeyboardType.DECIMAL); when(secureEditText.getText()).thenReturn(Editable.Factory.getInstance().newEditable("123.45")); sanKeyboard = sanKeyboardManager.getKeyboardForType(SanKeyboardType.DECIMAL, TopRowButtonsOptions.NONE); sanKeyboardView.setKeyboard(sanKeyboard); sanKeyboardView.setInputConnection(secureEditText); SanKeyboardView spyView = spy(sanKeyboardView); spyView.onKey(SanKeyboard.KEYCODE_DECIMAL_POINT, new int[0]); verify(secureEditText, times(2)).getText(); /* // TODO: Not working: // Wanted but not invoked: // sanKeyboardView.isShifted(); // -> at com.globile.santander.mobisec.securekeyboard.SanKeyboardView.processRegularChar(SanKeyboardView.java:581) // // However, there were exactly 2 interactions with this mock: verifyPrivate(spyView).invoke("processRegularChar", SanKeyboard.KEYCODE_DECIMAL_POINT); */ } @Test public void test025_OnKey_RegularKey() throws Exception { sanKeyboardView.setInputConnection(secureEditText); SanKeyboardView spyView = spy(sanKeyboardView); spyView.onKey(119, new int[0]); verifyPrivate(spyView, times(1)).invoke("processRegularChar", 119); } @Test public void test026_processRegularChar_UpperCaseShifted() throws Exception { sanKeyboardView.setInputConnection(secureEditText); sanKeyboardView.setShifted(true); sanKeyboard.setInitialShift(ShiftMode.UPPER_CASE_SINGLE); sanKeyboardView.setKeyboard(sanKeyboard); Whitebox.invokeMethod(sanKeyboardView, "processRegularChar", 119); } @Test public void test027_OnKeyActionEvents() { sanKeyboardView.onRelease(1); sanKeyboardView.onText(""); sanKeyboardView.swipeLeft(); sanKeyboardView.swipeRight(); sanKeyboardView.swipeUp(); sanKeyboardView.swipeDown(); // These methods have no actions, so nothing to verify or to assert assertTrue(true); } @Test public void test028_slideIn() throws Exception { SanKeyboardView spyView = spy(sanKeyboardView); spyView.slideIn(); verifyPrivate(spyView).invoke("startAnimation", any()); } @Test public void test029_slideOut() throws Exception { SanKeyboardView spyView = spy(sanKeyboardView); spyView.slideOut(); verifyPrivate(spyView).invoke("startAnimation", any()); } @Test public void test030_onAnimationStart() { sanKeyboardView.onAnimationStart(); assertTrue(sanKeyboardView.isAnimating()); } @Test public void test031_onAnimationEnd() { sanKeyboardView.onAnimationEnd(); assertFalse(sanKeyboardView.isAnimating()); } @Test public void test031_onLongPress() { sanKeyboardView.setInputConnection(secureEditText); sanKeyboardView.setKeyboard(sanKeyboard); KeyboardAOSP.Key aKey = sanKeyboardView.getKeyboard().getKeyByCode(97); sanKeyboardView.onLongPress(aKey); assertTrue((Boolean) Whitebox.getInternalState(sanKeyboardView, "isLongPressDownDetected")); } @Test public void test032_setEventListener() { SanEventCallbacks sanEventCallbacks = mock(SanEventCallbacks.class); sanKeyboardView.setEventListener(sanEventCallbacks); assertEquals(sanEventCallbacks, sanKeyboardView.getEventListener()); } @Test public void test033_onTouchEvent_LongPressOnA() { when(motionEvent.getAction()).thenReturn(MotionEvent.ACTION_UP); sanKeyboardView.setInputConnection(secureEditText); sanKeyboardView.setKeyboard(sanKeyboard); assertFalse((Boolean) Whitebox.getInternalState(sanKeyboardView, "isLongPressDownDetected")); assertFalse((Boolean) Whitebox.getInternalState(sanKeyboardView, "isLongPressUpDetected")); KeyboardAOSP.Key aKey = sanKeyboardView.getKeyboard().getKeyByCode(97); sanKeyboardView.onLongPress(aKey); assertTrue((Boolean) Whitebox.getInternalState(sanKeyboardView, "isLongPressDownDetected")); assertFalse((Boolean) Whitebox.getInternalState(sanKeyboardView, "isLongPressUpDetected")); sanKeyboardView.onTouchEvent(motionEvent); assertTrue((Boolean) Whitebox.getInternalState(sanKeyboardView, "isLongPressDownDetected")); assertTrue((Boolean) Whitebox.getInternalState(sanKeyboardView, "isLongPressUpDetected")); assertTrue(sanKeyboardView.onTouchEvent(motionEvent)); assertFalse((Boolean) Whitebox.getInternalState(sanKeyboardView, "isLongPressDownDetected")); assertFalse((Boolean) Whitebox.getInternalState(sanKeyboardView, "isLongPressUpDetected")); } }
22,587
0.728549
0.720446
696
31.451149
33.928642
127
false
false
0
0
0
0
0
0
0.545977
false
false
14
02fb6bc931b67990e7133685f6ad3575da52b704
30,837,865,190,191
a981f76061ce09510b195b3a8af908495545a2b8
/smsSemProject/src/java/rest/Rest.java
c2dfb4c00b31fb6060b0ad1acd065ae5b3e2192d
[]
no_license
Schultzz/smsSemProject
https://github.com/Schultzz/smsSemProject
22b5ae09a5acfda994a87e37ef850b4a7608b915
d4b36055b223b7bb6f90129952918d85f0881f51
refs/heads/master
2021-01-17T08:17:48.403000
2015-05-13T11:19:09
2015-05-13T11:19:09
35,089,950
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 rest; import datalayer.DBFacade; import entity.exceptions.FlightNotFoundException; import java.util.logging.Level; import java.util.logging.Logger; import javax.ws.rs.core.Context; import javax.ws.rs.core.UriInfo; import javax.ws.rs.PathParam; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.Produces; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; /** * REST Web Service * * @author Søren */ @Path("flights") public class Rest { @Context private UriInfo context; private static DBFacade dbf; /** * Creates a new instance of Rest */ public Rest() { dbf = DBFacade.getInstance(); } /** * Retrieves any given flight within the date given in the input params * * @param sAirport * @param date * @return an JSON object with all the flighs found * @throws entity.exceptions.FlightNotFoundException */ @GET @Produces("application/json") @Path("/{startAirport}/{date}") public String getAllFlights(@PathParam("startAirport") String sAirport, @PathParam("date") String date) throws FlightNotFoundException { //Date format: "yyyy.mm.dd" return dbf.getFlightsByDates(sAirport, date); } /** * Retrieves all Flights when given a start- and end destination, and a data * * @param startAirport * @param endAirport * @param sDate * @return an JSON object with all the flighs found * @throws entity.exceptions.FlightNotFoundException */ @GET @Produces("application/json") @Path("/{startAirport}/{endAirport}/{sDate}") public String getAllFlightsFromRoutes(@PathParam("startAirport") String startAirport, @PathParam("endAirport") String endAirport, @PathParam("sDate") String sDate) throws FlightNotFoundException { //Date format: "yyyy.mm.dd" //Airport codes are made uppercase to match the database return dbf.getFligtsByDatesAndAirpots(startAirport.toUpperCase(), endAirport.toUpperCase(), sDate); } /** * Retrieves a Flights when given a resevationId * * @param reservationId * @return an JSON object with the flight found */ @GET @Produces("application/json") @Path("/{reservationId}") public String getReservation(@PathParam("reservationId") String reservationId) { return dbf.getReservation(reservationId); } /** * Consumes a ReservationPayload object * * @param content * @param fId * @return a Reservation JSON object */ @POST @Consumes("application/json") @Produces("application/json") @Path("/{flightId}") public String addPerson(String content, @PathParam("flightId") String fId) { return dbf.flightReservation(content, fId); } /** * Consumes a ReservationPayload object * * @param content * @return a Reservation object * */ @DELETE @Consumes("application/json") @Produces("application/json") public String deletePerson(String content) { return dbf.deleteReservationById(content); } }
UTF-8
Java
3,356
java
Rest.java
Java
[ { "context": "ws.rs.Path;\n\n/**\n * REST Web Service\n *\n * @author Søren\n */\n@Path(\"flights\")\npublic class Rest {\n\n @Co", "end": 641, "score": 0.9997808337211609, "start": 636, "tag": "NAME", "value": "Søren" } ]
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 rest; import datalayer.DBFacade; import entity.exceptions.FlightNotFoundException; import java.util.logging.Level; import java.util.logging.Logger; import javax.ws.rs.core.Context; import javax.ws.rs.core.UriInfo; import javax.ws.rs.PathParam; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.Produces; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; /** * REST Web Service * * @author Søren */ @Path("flights") public class Rest { @Context private UriInfo context; private static DBFacade dbf; /** * Creates a new instance of Rest */ public Rest() { dbf = DBFacade.getInstance(); } /** * Retrieves any given flight within the date given in the input params * * @param sAirport * @param date * @return an JSON object with all the flighs found * @throws entity.exceptions.FlightNotFoundException */ @GET @Produces("application/json") @Path("/{startAirport}/{date}") public String getAllFlights(@PathParam("startAirport") String sAirport, @PathParam("date") String date) throws FlightNotFoundException { //Date format: "yyyy.mm.dd" return dbf.getFlightsByDates(sAirport, date); } /** * Retrieves all Flights when given a start- and end destination, and a data * * @param startAirport * @param endAirport * @param sDate * @return an JSON object with all the flighs found * @throws entity.exceptions.FlightNotFoundException */ @GET @Produces("application/json") @Path("/{startAirport}/{endAirport}/{sDate}") public String getAllFlightsFromRoutes(@PathParam("startAirport") String startAirport, @PathParam("endAirport") String endAirport, @PathParam("sDate") String sDate) throws FlightNotFoundException { //Date format: "yyyy.mm.dd" //Airport codes are made uppercase to match the database return dbf.getFligtsByDatesAndAirpots(startAirport.toUpperCase(), endAirport.toUpperCase(), sDate); } /** * Retrieves a Flights when given a resevationId * * @param reservationId * @return an JSON object with the flight found */ @GET @Produces("application/json") @Path("/{reservationId}") public String getReservation(@PathParam("reservationId") String reservationId) { return dbf.getReservation(reservationId); } /** * Consumes a ReservationPayload object * * @param content * @param fId * @return a Reservation JSON object */ @POST @Consumes("application/json") @Produces("application/json") @Path("/{flightId}") public String addPerson(String content, @PathParam("flightId") String fId) { return dbf.flightReservation(content, fId); } /** * Consumes a ReservationPayload object * * @param content * @return a Reservation object * */ @DELETE @Consumes("application/json") @Produces("application/json") public String deletePerson(String content) { return dbf.deleteReservationById(content); } }
3,356
0.664978
0.664978
119
27.193277
26.449024
140
false
false
0
0
0
0
0
0
0.285714
false
false
14
c91393f79360f668ba15236b0348bbf5e1ac16e2
29,300,266,901,751
c1d39da2a8d0b3c1fa45c428a42d89b28f28238f
/Java BootCamp/src/bootcamplab/Lab1A.java
cde57a6b7ac90a0052b6cb4bd5b947484100a573
[]
no_license
CupofJoe3/BootMain
https://github.com/CupofJoe3/BootMain
f97cf8141562d5bbfe321767c3dec77b89a71c1e
d3b7a7409fff113f73fe9d9e3c94d9c41351b2fc
refs/heads/main
2023-08-02T02:02:11.552000
2021-09-17T05:22:35
2021-09-17T05:22:35
401,420,782
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package bootcamplab; public class Lab1A { public static void main(String[] args) { int numberone = 5; int numbertwo = 10; int numberthree = 2; int total = numberone + numbertwo + numberthree; int largestnumber = max3(numberone, numbertwo, numberthree); int smallestnumber = min3(numberone, numbertwo, numberthree); int mediannumber = median3(total, smallestnumber, largestnumber); if (numberone == numbertwo || numbertwo == numberthree || numberone == numberthree) { System.out.println("Enter three integers that are not equal in value."); } else {System.out.println("The largest number is: " + largestnumber); System.out.println("The smallest number is: " + smallestnumber); System.out.println("The median number is: " + mediannumber);} } public static int max3( int numberone, int numbertwo, int numberthree) { int largestnumber = 0; if ( numberone > numbertwo && numberone > numberthree) { largestnumber = numberone; } else if ( numbertwo > numberone && numbertwo > numberthree) { largestnumber = numbertwo; } else if ( numberthree > numbertwo && numberthree > numberone) { largestnumber = numberthree; } return largestnumber; } public static int min3( int numberone, int numbertwo, int numberthree) { int smallestnumber = 0; if ( numberone < numbertwo && numberone < numberthree) { smallestnumber = numberone; } else if ( numbertwo < numberone && numbertwo < numberthree) { smallestnumber = numbertwo; } else if ( numberthree < numbertwo && numberthree < numberone) { smallestnumber = numberthree; } return smallestnumber; } public static int median3( int total, int smallestnumber, int largestnumber ) { int mediannumber = total - (smallestnumber + largestnumber); return mediannumber; } }
UTF-8
Java
1,800
java
Lab1A.java
Java
[]
null
[]
package bootcamplab; public class Lab1A { public static void main(String[] args) { int numberone = 5; int numbertwo = 10; int numberthree = 2; int total = numberone + numbertwo + numberthree; int largestnumber = max3(numberone, numbertwo, numberthree); int smallestnumber = min3(numberone, numbertwo, numberthree); int mediannumber = median3(total, smallestnumber, largestnumber); if (numberone == numbertwo || numbertwo == numberthree || numberone == numberthree) { System.out.println("Enter three integers that are not equal in value."); } else {System.out.println("The largest number is: " + largestnumber); System.out.println("The smallest number is: " + smallestnumber); System.out.println("The median number is: " + mediannumber);} } public static int max3( int numberone, int numbertwo, int numberthree) { int largestnumber = 0; if ( numberone > numbertwo && numberone > numberthree) { largestnumber = numberone; } else if ( numbertwo > numberone && numbertwo > numberthree) { largestnumber = numbertwo; } else if ( numberthree > numbertwo && numberthree > numberone) { largestnumber = numberthree; } return largestnumber; } public static int min3( int numberone, int numbertwo, int numberthree) { int smallestnumber = 0; if ( numberone < numbertwo && numberone < numberthree) { smallestnumber = numberone; } else if ( numbertwo < numberone && numbertwo < numberthree) { smallestnumber = numbertwo; } else if ( numberthree < numbertwo && numberthree < numberone) { smallestnumber = numberthree; } return smallestnumber; } public static int median3( int total, int smallestnumber, int largestnumber ) { int mediannumber = total - (smallestnumber + largestnumber); return mediannumber; } }
1,800
0.706667
0.699444
53
32.962265
35.276249
198
false
false
0
0
0
0
0
0
2.584906
false
false
14
ec1f60d0de358e6843991a7486f7e558a7b365f0
29,300,266,902,427
ce17c491aad33d67c4be98ade208caf5d12d3738
/jdi-light-mobile/src/main/java/com/epam/jdi/light/mobile/asserts/SearchViewFieldAssert.java
0dffd65d798acce6a341ced6e5d2646949873b41
[ "MIT" ]
permissive
jdi-testing/jdi-light
https://github.com/jdi-testing/jdi-light
2b1a0026b0bb87d93c828c206ee7d4dd8cf86878
cfe696c8288fea9254e31bf672a027d00a28a97c
refs/heads/master
2023-08-31T18:12:25.357000
2023-08-25T04:48:39
2023-08-25T04:48:39
127,065,400
117
63
MIT
false
2023-09-14T20:04:59
2018-03-28T01:20:16
2023-09-12T11:07:50
2023-09-14T20:04:58
167,134
101
48
274
Java
false
false
package com.epam.jdi.light.mobile.asserts; import com.epam.jdi.light.asserts.generic.UIAssert; import com.epam.jdi.light.common.JDIAction; import com.epam.jdi.light.mobile.asserts.generic.ISearchViewFieldAssert; import com.epam.jdi.light.mobile.elements.common.app.ISearchViewField; import org.hamcrest.Matchers; import static com.epam.jdi.light.asserts.core.SoftAssert.jdiAssert; public class SearchViewFieldAssert extends UIAssert<SearchViewFieldAssert, ISearchViewField> implements ISearchViewFieldAssert<SearchViewFieldAssert> { @JDIAction("Assert that '{name}' is enabled") @Override public SearchViewFieldAssert enabled() { jdiAssert(element.get().isEnabled(), Matchers.is(true)); return this; } @JDIAction("Assert that '{name}' is expanded") @Override public SearchViewFieldAssert expanded() { jdiAssert(element.get().isExpanded(), Matchers.is(true)); return this; } @JDIAction("Assert that '{name}' text {0}") @Override public SearchViewFieldAssert text(String expected) { jdiAssert(element().getValue(), Matchers.is(expected)); return this; } }
UTF-8
Java
1,156
java
SearchViewFieldAssert.java
Java
[]
null
[]
package com.epam.jdi.light.mobile.asserts; import com.epam.jdi.light.asserts.generic.UIAssert; import com.epam.jdi.light.common.JDIAction; import com.epam.jdi.light.mobile.asserts.generic.ISearchViewFieldAssert; import com.epam.jdi.light.mobile.elements.common.app.ISearchViewField; import org.hamcrest.Matchers; import static com.epam.jdi.light.asserts.core.SoftAssert.jdiAssert; public class SearchViewFieldAssert extends UIAssert<SearchViewFieldAssert, ISearchViewField> implements ISearchViewFieldAssert<SearchViewFieldAssert> { @JDIAction("Assert that '{name}' is enabled") @Override public SearchViewFieldAssert enabled() { jdiAssert(element.get().isEnabled(), Matchers.is(true)); return this; } @JDIAction("Assert that '{name}' is expanded") @Override public SearchViewFieldAssert expanded() { jdiAssert(element.get().isExpanded(), Matchers.is(true)); return this; } @JDIAction("Assert that '{name}' text {0}") @Override public SearchViewFieldAssert text(String expected) { jdiAssert(element().getValue(), Matchers.is(expected)); return this; } }
1,156
0.730104
0.729239
33
34.030304
32.330196
151
false
false
0
0
0
0
0
0
0.515152
false
false
14
6054e1e73c42002e20161f2438c49cfd5aa4c06c
17,076,789,980,078
9d8252f8acc01ee9117ed3178947a0341fd776b0
/app/src/main/java/com/xparticle/notes/MainActivity.java
9d11b17b38e0224655fe9f6cd8c82777ef5d0970
[]
no_license
Dhananjaypathak27/Notes
https://github.com/Dhananjaypathak27/Notes
976af8192543b9a82dfbf96f02607bd4cf1f66e0
4770c9919ef3831e0bae341ddbafa182b142aa20
refs/heads/master
2022-12-12T17:42:59.548000
2020-09-18T06:29:39
2020-09-18T06:29:39
296,533,569
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xparticle.notes; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.lifecycle.Observer; import androidx.recyclerview.widget.ItemTouchHelper; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.StaggeredGridLayoutManager; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.xparticle.notes.adapters.NotesRecyclerAdapter; import com.xparticle.notes.models.Note; import com.xparticle.notes.persistence.NoteRepository; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity implements NotesRecyclerAdapter.onNoteListener, View.OnClickListener { //ui private static final String TAG = "MainActivity"; private RecyclerView mRecyclerView; FloatingActionButton mFab; //variable ArrayList<Note> mNotes =new ArrayList<> (); NotesRecyclerAdapter mNotesRecyclerAdapter; private NoteRepository mNoteRepository; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.d(TAG, "onCreate: created"); mRecyclerView = findViewById(R.id.recyclerView); mFab = findViewById(R.id.fab); mFab.setOnClickListener(this); mNoteRepository = new NoteRepository(this); initRecyclerView(); // insetFakeData(); retrieveNotes(); Toolbar toolbar = findViewById(R.id.notes_toolbar); setSupportActionBar(toolbar); setTitle("Notes"); } private void retrieveNotes(){ mNoteRepository.retrieveNoteTask().observe(this, new Observer<List<Note>>() { @Override public void onChanged(List<Note> notes) { if(mNotes.size()>0){ mNotes.clear(); } if(notes != null){ mNotes.addAll(notes); } mNotesRecyclerAdapter.notifyDataSetChanged(); } }); } // // public void insetFakeData(){ // for(int i =0;i<1000;i++){ // Note note= new Note(); // note.setTitle("title"+i); // note.setContent("content"+i); // note.setTimestamp("2020 Aug"); // mNotes.add(note); // } // mNotesRecyclerAdapter.notifyDataSetChanged(); // } public void initRecyclerView(){ LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this); mRecyclerView.setLayoutManager(linearLayoutManager); new ItemTouchHelper(itemTouchCallBack).attachToRecyclerView(mRecyclerView); mNotesRecyclerAdapter = new NotesRecyclerAdapter(mNotes,this); mRecyclerView.setAdapter(mNotesRecyclerAdapter); mRecyclerView.setHasFixedSize(true); } @Override public void onNoteClick(int position) { // Log.d(TAG, "onNoteClick:"+position); Intent intent = new Intent(this,NoteActivity.class); intent.putExtra("selected_note",mNotes.get(position)); startActivity(intent); } @Override public void onClick(View v) { Intent intent= new Intent(this,NoteActivity.class); startActivity(intent); } private void deleteNote(Note note){ mNotes.remove(note); mNotesRecyclerAdapter.notifyDataSetChanged(); mNoteRepository.deleteNote(note); } private ItemTouchHelper.SimpleCallback itemTouchCallBack = new ItemTouchHelper.SimpleCallback(0,ItemTouchHelper.RIGHT) { @Override public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) { return false; } @Override public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) { deleteNote(mNotes.get(viewHolder.getAdapterPosition())); } }; }
UTF-8
Java
4,247
java
MainActivity.java
Java
[]
null
[]
package com.xparticle.notes; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.lifecycle.Observer; import androidx.recyclerview.widget.ItemTouchHelper; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.StaggeredGridLayoutManager; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.xparticle.notes.adapters.NotesRecyclerAdapter; import com.xparticle.notes.models.Note; import com.xparticle.notes.persistence.NoteRepository; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity implements NotesRecyclerAdapter.onNoteListener, View.OnClickListener { //ui private static final String TAG = "MainActivity"; private RecyclerView mRecyclerView; FloatingActionButton mFab; //variable ArrayList<Note> mNotes =new ArrayList<> (); NotesRecyclerAdapter mNotesRecyclerAdapter; private NoteRepository mNoteRepository; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.d(TAG, "onCreate: created"); mRecyclerView = findViewById(R.id.recyclerView); mFab = findViewById(R.id.fab); mFab.setOnClickListener(this); mNoteRepository = new NoteRepository(this); initRecyclerView(); // insetFakeData(); retrieveNotes(); Toolbar toolbar = findViewById(R.id.notes_toolbar); setSupportActionBar(toolbar); setTitle("Notes"); } private void retrieveNotes(){ mNoteRepository.retrieveNoteTask().observe(this, new Observer<List<Note>>() { @Override public void onChanged(List<Note> notes) { if(mNotes.size()>0){ mNotes.clear(); } if(notes != null){ mNotes.addAll(notes); } mNotesRecyclerAdapter.notifyDataSetChanged(); } }); } // // public void insetFakeData(){ // for(int i =0;i<1000;i++){ // Note note= new Note(); // note.setTitle("title"+i); // note.setContent("content"+i); // note.setTimestamp("2020 Aug"); // mNotes.add(note); // } // mNotesRecyclerAdapter.notifyDataSetChanged(); // } public void initRecyclerView(){ LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this); mRecyclerView.setLayoutManager(linearLayoutManager); new ItemTouchHelper(itemTouchCallBack).attachToRecyclerView(mRecyclerView); mNotesRecyclerAdapter = new NotesRecyclerAdapter(mNotes,this); mRecyclerView.setAdapter(mNotesRecyclerAdapter); mRecyclerView.setHasFixedSize(true); } @Override public void onNoteClick(int position) { // Log.d(TAG, "onNoteClick:"+position); Intent intent = new Intent(this,NoteActivity.class); intent.putExtra("selected_note",mNotes.get(position)); startActivity(intent); } @Override public void onClick(View v) { Intent intent= new Intent(this,NoteActivity.class); startActivity(intent); } private void deleteNote(Note note){ mNotes.remove(note); mNotesRecyclerAdapter.notifyDataSetChanged(); mNoteRepository.deleteNote(note); } private ItemTouchHelper.SimpleCallback itemTouchCallBack = new ItemTouchHelper.SimpleCallback(0,ItemTouchHelper.RIGHT) { @Override public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) { return false; } @Override public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) { deleteNote(mNotes.get(viewHolder.getAdapterPosition())); } }; }
4,247
0.680009
0.677419
127
32.448818
26.851505
153
false
false
0
0
0
0
0
0
0.629921
false
false
14
9f5a9542aaddbc5a4b4178053e87f909d846046d
2,138,893,725,857
d411055fec43717eeb39797f217718c6e48991cf
/EPG_Example/src/com/example/epg_try/dtv/DvbManager.java
b1f78ab1e68b05cdf305ce230fb871f6cf7d2d0a
[ "Apache-2.0" ]
permissive
BaneP/CustomViews
https://github.com/BaneP/CustomViews
f10ed6b98b57b5605bb9151dd5468a8525747aa8
12230c03254bd804ed568d4ab520c94577fec5ef
refs/heads/master
2021-06-23T16:05:58.244000
2014-12-25T10:28:06
2014-12-25T10:28:06
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.epg_try.dtv; import android.net.ParseException; import android.os.RemoteException; import android.util.Log; import com.iwedia.dtv.dtvmanager.DTVManager; import com.iwedia.dtv.dtvmanager.IDTVManager; import com.iwedia.dtv.epg.EpgEvent; import com.iwedia.dtv.epg.EpgServiceFilter; import com.iwedia.dtv.epg.EpgTimeFilter; import com.iwedia.dtv.route.broadcast.IBroadcastRouteControl; import com.iwedia.dtv.route.broadcast.RouteDemuxDescriptor; import com.iwedia.dtv.route.broadcast.RouteFrontendDescriptor; import com.iwedia.dtv.route.broadcast.RouteFrontendType; import com.iwedia.dtv.route.broadcast.RouteMassStorageDescriptor; import com.iwedia.dtv.route.common.ICommonRouteControl; import com.iwedia.dtv.route.common.RouteDecoderDescriptor; import com.iwedia.dtv.route.common.RouteInputOutputDescriptor; import com.iwedia.dtv.service.IServiceControl; import com.iwedia.dtv.service.ServiceDescriptor; import com.iwedia.dtv.service.SourceType; import com.iwedia.dtv.types.InternalException; import com.iwedia.dtv.types.TimeDate; import java.util.ArrayList; import java.util.Calendar; import java.util.EnumSet; public class DvbManager { private static final String TAG = "DVB MANAGER"; private IDTVManager mDTVManager = null; /** DVB Manager Instance. */ private static DvbManager sInstance = null; /** EPG Filter ID */ private int mEPGFilterID = -1; private EpgCallback mEPGCallBack; /** * Routes */ private int mCurrentLiveRoute = -1; private int mLiveRouteSat = -1; private int mLiveRouteTer = -1; private int mLiveRouteCab = -1; private int mLiveRouteIp = -1; private int mPlaybackRouteIDMain = -1; private int mRecordRouteTer = -1; private int mRecordRouteCab = -1; private int mRecordRouteSat = -1; private int mRecordRouteIp = -1; private int mCurrentRecordRoute = -1; /** Currently active list in Comedia. */ private int mCurrentListIndex = 0; public static DvbManager getInstance() { if (sInstance == null) { sInstance = new DvbManager(); } return sInstance; } private DvbManager() { mDTVManager = new DTVManager(); try { initializeDTVService(); } catch (InternalException e) { e.printStackTrace(); } } /** * Initialize Service. * * @throws InternalException */ public void initializeDTVService() throws InternalException { initializeRouteId(); mEPGFilterID = mDTVManager.getEpgControl().createEventList(); mEPGCallBack = new EpgCallback(); mDTVManager.getEpgControl() .registerCallback(mEPGCallBack, mEPGFilterID); } /** * Initialize Descriptors For Live Route. */ private void initializeRouteId() { IBroadcastRouteControl broadcastRouteControl = mDTVManager .getBroadcastRouteControl(); ICommonRouteControl commonRouteControl = mDTVManager .getCommonRouteControl(); /** * RETRIEVE DEMUX DESCRIPTOR. */ RouteDemuxDescriptor demuxDescriptor = broadcastRouteControl .getDemuxDescriptor(0); /** * RETRIEVE DECODER DESCRIPTOR. */ RouteDecoderDescriptor decoderDescriptor = commonRouteControl .getDecoderDescriptor(0); /** * RETRIEVING OUTPUT DESCRIPTOR. */ RouteInputOutputDescriptor outputDescriptor = commonRouteControl .getInputOutputDescriptor(0); /** * RETRIEVING MASS STORAGE DESCRIPTOR. */ RouteMassStorageDescriptor massStorageDescriptor = new RouteMassStorageDescriptor(); massStorageDescriptor = broadcastRouteControl .getMassStorageDescriptor(0); /** * GET NUMBER OF FRONTENDS. */ int numberOfFrontends = broadcastRouteControl.getFrontendNumber(); /** * FIND DVB and IP front-end descriptors. */ EnumSet<RouteFrontendType> frontendTypes = null; for (int i = 0; i < numberOfFrontends; i++) { RouteFrontendDescriptor frontendDescriptor = broadcastRouteControl .getFrontendDescriptor(i); frontendTypes = frontendDescriptor.getFrontendType(); for (RouteFrontendType frontendType : frontendTypes) { switch (frontendType) { case SAT: { if (mLiveRouteSat == -1) { mLiveRouteSat = getLiveRouteId(frontendDescriptor, demuxDescriptor, decoderDescriptor, outputDescriptor, broadcastRouteControl); } /** * RETRIEVE RECORD ROUTES */ if (mRecordRouteSat == -1) { mRecordRouteSat = broadcastRouteControl .getRecordRoute(frontendDescriptor .getFrontendId(), demuxDescriptor .getDemuxId(), massStorageDescriptor .getMassStorageId()); } break; } case CAB: { if (mLiveRouteCab == -1) { mLiveRouteCab = getLiveRouteId(frontendDescriptor, demuxDescriptor, decoderDescriptor, outputDescriptor, broadcastRouteControl); } /** * RETRIEVE RECORD ROUTES */ if (mRecordRouteCab == -1) { mRecordRouteCab = broadcastRouteControl .getRecordRoute(frontendDescriptor .getFrontendId(), demuxDescriptor .getDemuxId(), massStorageDescriptor .getMassStorageId()); } break; } case TER: { if (mLiveRouteTer == -1) { mLiveRouteTer = getLiveRouteId(frontendDescriptor, demuxDescriptor, decoderDescriptor, outputDescriptor, broadcastRouteControl); } /** * RETRIEVE RECORD ROUTES */ if (mRecordRouteTer == -1) { mRecordRouteTer = broadcastRouteControl .getRecordRoute(frontendDescriptor .getFrontendId(), demuxDescriptor .getDemuxId(), massStorageDescriptor .getMassStorageId()); } break; } case IP: { if (mLiveRouteIp == -1) { mLiveRouteIp = getLiveRouteId(frontendDescriptor, demuxDescriptor, decoderDescriptor, outputDescriptor, broadcastRouteControl); } /** * RETRIEVE RECORD ROUTES */ if (mRecordRouteIp == -1) { mRecordRouteIp = broadcastRouteControl .getRecordRoute(frontendDescriptor .getFrontendId(), demuxDescriptor .getDemuxId(), massStorageDescriptor .getMassStorageId()); } break; } default: break; } } } /** * RETRIEVE PLAYBACK ROUTE */ mPlaybackRouteIDMain = broadcastRouteControl.getPlaybackRoute( massStorageDescriptor.getMassStorageId(), demuxDescriptor.getDemuxId(), decoderDescriptor.getDecoderId()); if (mLiveRouteIp != -1 && (mLiveRouteCab != -1 || mLiveRouteSat != -1 || mLiveRouteTer != -1)) { // ipAndSomeOtherTunerType = true; } Log.d(TAG, "mLiveRouteTer=" + mLiveRouteTer + ", mLiveRouteCab=" + mLiveRouteCab + ", mLiveRouteIp=" + mLiveRouteIp); } /** * Get Live Route From Descriptors. * * @param fDescriptor * @param mDemuxDescriptor * @param mDecoderDescriptor * @param mOutputDescriptor */ private int getLiveRouteId(RouteFrontendDescriptor fDescriptor, RouteDemuxDescriptor mDemuxDescriptor, RouteDecoderDescriptor mDecoderDescriptor, RouteInputOutputDescriptor mOutputDescriptor, IBroadcastRouteControl routeControl) { return routeControl.getLiveRoute(fDescriptor.getFrontendId(), mDemuxDescriptor.getDemuxId(), mDecoderDescriptor.getDecoderId()); } /** * Stop MW video playback. * * @throws InternalException */ public void stopDTV() throws InternalException { mDTVManager.getEpgControl().releaseEventList(mEPGFilterID); mDTVManager.getEpgControl().unregisterCallback(mEPGCallBack, mEPGFilterID); mDTVManager.getServiceControl().stopService(mCurrentLiveRoute); sInstance = null; } /** * Change Channel by Number. * * @return Channel Info Object or null if error occurred. * @throws IllegalArgumentException * @throws InternalException */ public void changeChannelByNumber(int channelNumber) throws InternalException { int listSize = getChannelListSize(); if (listSize == 0) { return; } channelNumber = (channelNumber + listSize) % listSize; ServiceDescriptor desiredService = mDTVManager.getServiceControl() .getServiceDescriptor(mCurrentListIndex, channelNumber); int route = getActiveRouteByServiceType(desiredService.getSourceType()); if (route == -1) { return; } mCurrentLiveRoute = route; mDTVManager.getServiceControl().startService(route, mCurrentListIndex, channelNumber); } /** * Return route by service type. * * @param serviceType * Service type to check. * @return Desired route, or 0 if service type is undefined. */ private int getActiveRouteByServiceType(SourceType sourceType) { switch (sourceType) { case CAB: { return mLiveRouteCab; } case TER: { return mLiveRouteTer; } case SAT: { return mLiveRouteSat; } case IP: { return mLiveRouteIp; } default: return -1; } } /** * Get Size of Channel List. */ public int getChannelListSize() { int serviceCount = mDTVManager.getServiceControl().getServiceListCount( mCurrentListIndex); return serviceCount; } /** * Get Channel Names. */ public ArrayList<String> getChannelNames() { ArrayList<String> channelNames = new ArrayList<String>(); String channelName = ""; int channelListSize = getChannelListSize(); IServiceControl serviceControl = mDTVManager.getServiceControl(); for (int i = 0; i < channelListSize; i++) { channelName = serviceControl.getServiceDescriptor( mCurrentListIndex, i).getName(); channelNames.add(channelName); } return channelNames; } /** * Get Current Channel Number. */ public int getCurrentChannelNumber() { return (int) (mDTVManager.getServiceControl().getActiveService( mCurrentLiveRoute).getServiceIndex()); } public TimeDate getTimeFromStream() { return mDTVManager.getSetupControl().getTimeDate(); } /** * Load Events From MW. * * @param day * -Load EPG for previous or current or next day. * @param channelListSize * Number of services in channel list * @throws ParseException * @throws RemoteException */ public synchronized ArrayList<EpgEvent> loadEvents(int channelNumber, int oneMinutePixelWidth, int day) throws ParseException, IllegalArgumentException { int count = getChannelListSize(); if (channelNumber < 0 || channelNumber >= count) { throw new IllegalArgumentException("Channel number cant be: " + channelNumber + ", service list size is: " + count); } ArrayList<EpgEvent> events = new ArrayList<EpgEvent>(); EpgEvent lEvent = null; int lEpgEventsSize = 0; TimeDate lCurrentTime = mDTVManager.getSetupControl().getTimeDate(); Calendar lCalendar = lCurrentTime.getCalendar(); lCalendar.add(Calendar.DATE, day); TimeDate lEpgStartTime = new TimeDate(1, 1, 0, lCalendar.get(Calendar.DAY_OF_MONTH), lCalendar.get(Calendar.MONTH) + 1, lCalendar.get(Calendar.YEAR)); TimeDate lEpgEndTime = new TimeDate(0, 0, 0, lCalendar.get(Calendar.DAY_OF_MONTH), lCalendar.get(Calendar.MONTH) + 1, lCalendar.get(Calendar.YEAR)); /** Create Time Filter */ EpgTimeFilter lEpgTimeFilter = new EpgTimeFilter(); lEpgTimeFilter.setTime(lEpgStartTime, lEpgEndTime); /** Make filter list by time. */ mDTVManager.getEpgControl().setFilter(mEPGFilterID, lEpgTimeFilter); int indexInMasterList = mDTVManager.getServiceControl() .getServiceDescriptor(mCurrentListIndex, channelNumber) .getMasterIndex(); /** Create Service Filter. */ EpgServiceFilter lEpgServiceFilter = new EpgServiceFilter(); lEpgServiceFilter.setServiceIndex(indexInMasterList); /** Set Service Filter. */ mDTVManager.getEpgControl().setFilter(mEPGFilterID, lEpgServiceFilter); mDTVManager.getEpgControl().startAcquisition(mEPGFilterID); lEpgEventsSize = mDTVManager.getEpgControl().getAvailableEventsNumber( mEPGFilterID, indexInMasterList); for (int eventIndex = 0; eventIndex < lEpgEventsSize; eventIndex++) { lEvent = mDTVManager.getEpgControl().getRequestedEvent( mEPGFilterID, indexInMasterList, eventIndex); events.add(lEvent); } mDTVManager.getEpgControl().stopAcquisition(mEPGFilterID); return events; } }
UTF-8
Java
15,559
java
DvbManager.java
Java
[]
null
[]
package com.example.epg_try.dtv; import android.net.ParseException; import android.os.RemoteException; import android.util.Log; import com.iwedia.dtv.dtvmanager.DTVManager; import com.iwedia.dtv.dtvmanager.IDTVManager; import com.iwedia.dtv.epg.EpgEvent; import com.iwedia.dtv.epg.EpgServiceFilter; import com.iwedia.dtv.epg.EpgTimeFilter; import com.iwedia.dtv.route.broadcast.IBroadcastRouteControl; import com.iwedia.dtv.route.broadcast.RouteDemuxDescriptor; import com.iwedia.dtv.route.broadcast.RouteFrontendDescriptor; import com.iwedia.dtv.route.broadcast.RouteFrontendType; import com.iwedia.dtv.route.broadcast.RouteMassStorageDescriptor; import com.iwedia.dtv.route.common.ICommonRouteControl; import com.iwedia.dtv.route.common.RouteDecoderDescriptor; import com.iwedia.dtv.route.common.RouteInputOutputDescriptor; import com.iwedia.dtv.service.IServiceControl; import com.iwedia.dtv.service.ServiceDescriptor; import com.iwedia.dtv.service.SourceType; import com.iwedia.dtv.types.InternalException; import com.iwedia.dtv.types.TimeDate; import java.util.ArrayList; import java.util.Calendar; import java.util.EnumSet; public class DvbManager { private static final String TAG = "DVB MANAGER"; private IDTVManager mDTVManager = null; /** DVB Manager Instance. */ private static DvbManager sInstance = null; /** EPG Filter ID */ private int mEPGFilterID = -1; private EpgCallback mEPGCallBack; /** * Routes */ private int mCurrentLiveRoute = -1; private int mLiveRouteSat = -1; private int mLiveRouteTer = -1; private int mLiveRouteCab = -1; private int mLiveRouteIp = -1; private int mPlaybackRouteIDMain = -1; private int mRecordRouteTer = -1; private int mRecordRouteCab = -1; private int mRecordRouteSat = -1; private int mRecordRouteIp = -1; private int mCurrentRecordRoute = -1; /** Currently active list in Comedia. */ private int mCurrentListIndex = 0; public static DvbManager getInstance() { if (sInstance == null) { sInstance = new DvbManager(); } return sInstance; } private DvbManager() { mDTVManager = new DTVManager(); try { initializeDTVService(); } catch (InternalException e) { e.printStackTrace(); } } /** * Initialize Service. * * @throws InternalException */ public void initializeDTVService() throws InternalException { initializeRouteId(); mEPGFilterID = mDTVManager.getEpgControl().createEventList(); mEPGCallBack = new EpgCallback(); mDTVManager.getEpgControl() .registerCallback(mEPGCallBack, mEPGFilterID); } /** * Initialize Descriptors For Live Route. */ private void initializeRouteId() { IBroadcastRouteControl broadcastRouteControl = mDTVManager .getBroadcastRouteControl(); ICommonRouteControl commonRouteControl = mDTVManager .getCommonRouteControl(); /** * RETRIEVE DEMUX DESCRIPTOR. */ RouteDemuxDescriptor demuxDescriptor = broadcastRouteControl .getDemuxDescriptor(0); /** * RETRIEVE DECODER DESCRIPTOR. */ RouteDecoderDescriptor decoderDescriptor = commonRouteControl .getDecoderDescriptor(0); /** * RETRIEVING OUTPUT DESCRIPTOR. */ RouteInputOutputDescriptor outputDescriptor = commonRouteControl .getInputOutputDescriptor(0); /** * RETRIEVING MASS STORAGE DESCRIPTOR. */ RouteMassStorageDescriptor massStorageDescriptor = new RouteMassStorageDescriptor(); massStorageDescriptor = broadcastRouteControl .getMassStorageDescriptor(0); /** * GET NUMBER OF FRONTENDS. */ int numberOfFrontends = broadcastRouteControl.getFrontendNumber(); /** * FIND DVB and IP front-end descriptors. */ EnumSet<RouteFrontendType> frontendTypes = null; for (int i = 0; i < numberOfFrontends; i++) { RouteFrontendDescriptor frontendDescriptor = broadcastRouteControl .getFrontendDescriptor(i); frontendTypes = frontendDescriptor.getFrontendType(); for (RouteFrontendType frontendType : frontendTypes) { switch (frontendType) { case SAT: { if (mLiveRouteSat == -1) { mLiveRouteSat = getLiveRouteId(frontendDescriptor, demuxDescriptor, decoderDescriptor, outputDescriptor, broadcastRouteControl); } /** * RETRIEVE RECORD ROUTES */ if (mRecordRouteSat == -1) { mRecordRouteSat = broadcastRouteControl .getRecordRoute(frontendDescriptor .getFrontendId(), demuxDescriptor .getDemuxId(), massStorageDescriptor .getMassStorageId()); } break; } case CAB: { if (mLiveRouteCab == -1) { mLiveRouteCab = getLiveRouteId(frontendDescriptor, demuxDescriptor, decoderDescriptor, outputDescriptor, broadcastRouteControl); } /** * RETRIEVE RECORD ROUTES */ if (mRecordRouteCab == -1) { mRecordRouteCab = broadcastRouteControl .getRecordRoute(frontendDescriptor .getFrontendId(), demuxDescriptor .getDemuxId(), massStorageDescriptor .getMassStorageId()); } break; } case TER: { if (mLiveRouteTer == -1) { mLiveRouteTer = getLiveRouteId(frontendDescriptor, demuxDescriptor, decoderDescriptor, outputDescriptor, broadcastRouteControl); } /** * RETRIEVE RECORD ROUTES */ if (mRecordRouteTer == -1) { mRecordRouteTer = broadcastRouteControl .getRecordRoute(frontendDescriptor .getFrontendId(), demuxDescriptor .getDemuxId(), massStorageDescriptor .getMassStorageId()); } break; } case IP: { if (mLiveRouteIp == -1) { mLiveRouteIp = getLiveRouteId(frontendDescriptor, demuxDescriptor, decoderDescriptor, outputDescriptor, broadcastRouteControl); } /** * RETRIEVE RECORD ROUTES */ if (mRecordRouteIp == -1) { mRecordRouteIp = broadcastRouteControl .getRecordRoute(frontendDescriptor .getFrontendId(), demuxDescriptor .getDemuxId(), massStorageDescriptor .getMassStorageId()); } break; } default: break; } } } /** * RETRIEVE PLAYBACK ROUTE */ mPlaybackRouteIDMain = broadcastRouteControl.getPlaybackRoute( massStorageDescriptor.getMassStorageId(), demuxDescriptor.getDemuxId(), decoderDescriptor.getDecoderId()); if (mLiveRouteIp != -1 && (mLiveRouteCab != -1 || mLiveRouteSat != -1 || mLiveRouteTer != -1)) { // ipAndSomeOtherTunerType = true; } Log.d(TAG, "mLiveRouteTer=" + mLiveRouteTer + ", mLiveRouteCab=" + mLiveRouteCab + ", mLiveRouteIp=" + mLiveRouteIp); } /** * Get Live Route From Descriptors. * * @param fDescriptor * @param mDemuxDescriptor * @param mDecoderDescriptor * @param mOutputDescriptor */ private int getLiveRouteId(RouteFrontendDescriptor fDescriptor, RouteDemuxDescriptor mDemuxDescriptor, RouteDecoderDescriptor mDecoderDescriptor, RouteInputOutputDescriptor mOutputDescriptor, IBroadcastRouteControl routeControl) { return routeControl.getLiveRoute(fDescriptor.getFrontendId(), mDemuxDescriptor.getDemuxId(), mDecoderDescriptor.getDecoderId()); } /** * Stop MW video playback. * * @throws InternalException */ public void stopDTV() throws InternalException { mDTVManager.getEpgControl().releaseEventList(mEPGFilterID); mDTVManager.getEpgControl().unregisterCallback(mEPGCallBack, mEPGFilterID); mDTVManager.getServiceControl().stopService(mCurrentLiveRoute); sInstance = null; } /** * Change Channel by Number. * * @return Channel Info Object or null if error occurred. * @throws IllegalArgumentException * @throws InternalException */ public void changeChannelByNumber(int channelNumber) throws InternalException { int listSize = getChannelListSize(); if (listSize == 0) { return; } channelNumber = (channelNumber + listSize) % listSize; ServiceDescriptor desiredService = mDTVManager.getServiceControl() .getServiceDescriptor(mCurrentListIndex, channelNumber); int route = getActiveRouteByServiceType(desiredService.getSourceType()); if (route == -1) { return; } mCurrentLiveRoute = route; mDTVManager.getServiceControl().startService(route, mCurrentListIndex, channelNumber); } /** * Return route by service type. * * @param serviceType * Service type to check. * @return Desired route, or 0 if service type is undefined. */ private int getActiveRouteByServiceType(SourceType sourceType) { switch (sourceType) { case CAB: { return mLiveRouteCab; } case TER: { return mLiveRouteTer; } case SAT: { return mLiveRouteSat; } case IP: { return mLiveRouteIp; } default: return -1; } } /** * Get Size of Channel List. */ public int getChannelListSize() { int serviceCount = mDTVManager.getServiceControl().getServiceListCount( mCurrentListIndex); return serviceCount; } /** * Get Channel Names. */ public ArrayList<String> getChannelNames() { ArrayList<String> channelNames = new ArrayList<String>(); String channelName = ""; int channelListSize = getChannelListSize(); IServiceControl serviceControl = mDTVManager.getServiceControl(); for (int i = 0; i < channelListSize; i++) { channelName = serviceControl.getServiceDescriptor( mCurrentListIndex, i).getName(); channelNames.add(channelName); } return channelNames; } /** * Get Current Channel Number. */ public int getCurrentChannelNumber() { return (int) (mDTVManager.getServiceControl().getActiveService( mCurrentLiveRoute).getServiceIndex()); } public TimeDate getTimeFromStream() { return mDTVManager.getSetupControl().getTimeDate(); } /** * Load Events From MW. * * @param day * -Load EPG for previous or current or next day. * @param channelListSize * Number of services in channel list * @throws ParseException * @throws RemoteException */ public synchronized ArrayList<EpgEvent> loadEvents(int channelNumber, int oneMinutePixelWidth, int day) throws ParseException, IllegalArgumentException { int count = getChannelListSize(); if (channelNumber < 0 || channelNumber >= count) { throw new IllegalArgumentException("Channel number cant be: " + channelNumber + ", service list size is: " + count); } ArrayList<EpgEvent> events = new ArrayList<EpgEvent>(); EpgEvent lEvent = null; int lEpgEventsSize = 0; TimeDate lCurrentTime = mDTVManager.getSetupControl().getTimeDate(); Calendar lCalendar = lCurrentTime.getCalendar(); lCalendar.add(Calendar.DATE, day); TimeDate lEpgStartTime = new TimeDate(1, 1, 0, lCalendar.get(Calendar.DAY_OF_MONTH), lCalendar.get(Calendar.MONTH) + 1, lCalendar.get(Calendar.YEAR)); TimeDate lEpgEndTime = new TimeDate(0, 0, 0, lCalendar.get(Calendar.DAY_OF_MONTH), lCalendar.get(Calendar.MONTH) + 1, lCalendar.get(Calendar.YEAR)); /** Create Time Filter */ EpgTimeFilter lEpgTimeFilter = new EpgTimeFilter(); lEpgTimeFilter.setTime(lEpgStartTime, lEpgEndTime); /** Make filter list by time. */ mDTVManager.getEpgControl().setFilter(mEPGFilterID, lEpgTimeFilter); int indexInMasterList = mDTVManager.getServiceControl() .getServiceDescriptor(mCurrentListIndex, channelNumber) .getMasterIndex(); /** Create Service Filter. */ EpgServiceFilter lEpgServiceFilter = new EpgServiceFilter(); lEpgServiceFilter.setServiceIndex(indexInMasterList); /** Set Service Filter. */ mDTVManager.getEpgControl().setFilter(mEPGFilterID, lEpgServiceFilter); mDTVManager.getEpgControl().startAcquisition(mEPGFilterID); lEpgEventsSize = mDTVManager.getEpgControl().getAvailableEventsNumber( mEPGFilterID, indexInMasterList); for (int eventIndex = 0; eventIndex < lEpgEventsSize; eventIndex++) { lEvent = mDTVManager.getEpgControl().getRequestedEvent( mEPGFilterID, indexInMasterList, eventIndex); events.add(lEvent); } mDTVManager.getEpgControl().stopAcquisition(mEPGFilterID); return events; } }
15,559
0.553892
0.550935
395
38.389874
23.511374
92
false
false
0
0
0
0
0
0
0.521519
false
false
14
e055bf3be0928607134dd9e0092a9fe67fb21286
2,869,038,167,329
dd76d0b680549acb07278b2ecd387cb05ec84d64
/divestory-CFR/com/google/android/material/floatingactionbutton/BaseMotionStrategy.java
832a42fb62be83d737dc658979df8e1cdd741d09
[]
no_license
ryangardner/excursion-decompiling
https://github.com/ryangardner/excursion-decompiling
43c99a799ce75a417e636da85bddd5d1d9a9109c
4b6d11d6f118cdab31328c877c268f3d56b95c58
refs/heads/master
2023-07-02T13:32:30.872000
2021-08-09T19:33:37
2021-08-09T19:33:37
299,657,052
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Decompiled with CFR <Could not determine version>. * * Could not load the following classes: * android.animation.Animator * android.animation.Animator$AnimatorListener * android.animation.AnimatorSet * android.animation.ObjectAnimator * android.content.Context * android.util.Property * android.view.View */ package com.google.android.material.floatingactionbutton; import android.animation.Animator; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.content.Context; import android.util.Property; import android.view.View; import androidx.core.util.Preconditions; import com.google.android.material.animation.AnimatorSetCompat; import com.google.android.material.animation.MotionSpec; import com.google.android.material.floatingactionbutton.AnimatorTracker; import com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton; import com.google.android.material.floatingactionbutton.MotionStrategy; import java.util.ArrayList; import java.util.List; abstract class BaseMotionStrategy implements MotionStrategy { private final Context context; private MotionSpec defaultMotionSpec; private final ExtendedFloatingActionButton fab; private final ArrayList<Animator.AnimatorListener> listeners = new ArrayList(); private MotionSpec motionSpec; private final AnimatorTracker tracker; BaseMotionStrategy(ExtendedFloatingActionButton extendedFloatingActionButton, AnimatorTracker animatorTracker) { this.fab = extendedFloatingActionButton; this.context = extendedFloatingActionButton.getContext(); this.tracker = animatorTracker; } @Override public final void addAnimationListener(Animator.AnimatorListener animatorListener) { this.listeners.add(animatorListener); } @Override public AnimatorSet createAnimator() { return this.createAnimator(this.getCurrentMotionSpec()); } AnimatorSet createAnimator(MotionSpec motionSpec) { ArrayList<Animator> arrayList = new ArrayList<Animator>(); if (motionSpec.hasPropertyValues("opacity")) { arrayList.add((Animator)motionSpec.getAnimator("opacity", this.fab, View.ALPHA)); } if (motionSpec.hasPropertyValues("scale")) { arrayList.add((Animator)motionSpec.getAnimator("scale", this.fab, View.SCALE_Y)); arrayList.add((Animator)motionSpec.getAnimator("scale", this.fab, View.SCALE_X)); } if (motionSpec.hasPropertyValues("width")) { arrayList.add((Animator)motionSpec.getAnimator("width", this.fab, ExtendedFloatingActionButton.WIDTH)); } if (motionSpec.hasPropertyValues("height")) { arrayList.add((Animator)motionSpec.getAnimator("height", this.fab, ExtendedFloatingActionButton.HEIGHT)); } motionSpec = new AnimatorSet(); AnimatorSetCompat.playTogether((AnimatorSet)motionSpec, arrayList); return motionSpec; } @Override public final MotionSpec getCurrentMotionSpec() { MotionSpec motionSpec = this.motionSpec; if (motionSpec != null) { return motionSpec; } if (this.defaultMotionSpec != null) return Preconditions.checkNotNull(this.defaultMotionSpec); this.defaultMotionSpec = MotionSpec.createFromResource(this.context, this.getDefaultMotionSpecResource()); return Preconditions.checkNotNull(this.defaultMotionSpec); } @Override public final List<Animator.AnimatorListener> getListeners() { return this.listeners; } @Override public MotionSpec getMotionSpec() { return this.motionSpec; } @Override public void onAnimationCancel() { this.tracker.clear(); } @Override public void onAnimationEnd() { this.tracker.clear(); } @Override public void onAnimationStart(Animator animator2) { this.tracker.onNextAnimationStart(animator2); } @Override public final void removeAnimationListener(Animator.AnimatorListener animatorListener) { this.listeners.remove((Object)animatorListener); } @Override public final void setMotionSpec(MotionSpec motionSpec) { this.motionSpec = motionSpec; } }
UTF-8
Java
4,290
java
BaseMotionStrategy.java
Java
[]
null
[]
/* * Decompiled with CFR <Could not determine version>. * * Could not load the following classes: * android.animation.Animator * android.animation.Animator$AnimatorListener * android.animation.AnimatorSet * android.animation.ObjectAnimator * android.content.Context * android.util.Property * android.view.View */ package com.google.android.material.floatingactionbutton; import android.animation.Animator; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.content.Context; import android.util.Property; import android.view.View; import androidx.core.util.Preconditions; import com.google.android.material.animation.AnimatorSetCompat; import com.google.android.material.animation.MotionSpec; import com.google.android.material.floatingactionbutton.AnimatorTracker; import com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton; import com.google.android.material.floatingactionbutton.MotionStrategy; import java.util.ArrayList; import java.util.List; abstract class BaseMotionStrategy implements MotionStrategy { private final Context context; private MotionSpec defaultMotionSpec; private final ExtendedFloatingActionButton fab; private final ArrayList<Animator.AnimatorListener> listeners = new ArrayList(); private MotionSpec motionSpec; private final AnimatorTracker tracker; BaseMotionStrategy(ExtendedFloatingActionButton extendedFloatingActionButton, AnimatorTracker animatorTracker) { this.fab = extendedFloatingActionButton; this.context = extendedFloatingActionButton.getContext(); this.tracker = animatorTracker; } @Override public final void addAnimationListener(Animator.AnimatorListener animatorListener) { this.listeners.add(animatorListener); } @Override public AnimatorSet createAnimator() { return this.createAnimator(this.getCurrentMotionSpec()); } AnimatorSet createAnimator(MotionSpec motionSpec) { ArrayList<Animator> arrayList = new ArrayList<Animator>(); if (motionSpec.hasPropertyValues("opacity")) { arrayList.add((Animator)motionSpec.getAnimator("opacity", this.fab, View.ALPHA)); } if (motionSpec.hasPropertyValues("scale")) { arrayList.add((Animator)motionSpec.getAnimator("scale", this.fab, View.SCALE_Y)); arrayList.add((Animator)motionSpec.getAnimator("scale", this.fab, View.SCALE_X)); } if (motionSpec.hasPropertyValues("width")) { arrayList.add((Animator)motionSpec.getAnimator("width", this.fab, ExtendedFloatingActionButton.WIDTH)); } if (motionSpec.hasPropertyValues("height")) { arrayList.add((Animator)motionSpec.getAnimator("height", this.fab, ExtendedFloatingActionButton.HEIGHT)); } motionSpec = new AnimatorSet(); AnimatorSetCompat.playTogether((AnimatorSet)motionSpec, arrayList); return motionSpec; } @Override public final MotionSpec getCurrentMotionSpec() { MotionSpec motionSpec = this.motionSpec; if (motionSpec != null) { return motionSpec; } if (this.defaultMotionSpec != null) return Preconditions.checkNotNull(this.defaultMotionSpec); this.defaultMotionSpec = MotionSpec.createFromResource(this.context, this.getDefaultMotionSpecResource()); return Preconditions.checkNotNull(this.defaultMotionSpec); } @Override public final List<Animator.AnimatorListener> getListeners() { return this.listeners; } @Override public MotionSpec getMotionSpec() { return this.motionSpec; } @Override public void onAnimationCancel() { this.tracker.clear(); } @Override public void onAnimationEnd() { this.tracker.clear(); } @Override public void onAnimationStart(Animator animator2) { this.tracker.onNextAnimationStart(animator2); } @Override public final void removeAnimationListener(Animator.AnimatorListener animatorListener) { this.listeners.remove((Object)animatorListener); } @Override public final void setMotionSpec(MotionSpec motionSpec) { this.motionSpec = motionSpec; } }
4,290
0.727972
0.727506
120
34.741665
30.060909
117
false
false
0
0
0
0
0
0
0.5
false
false
14
bf852bb6c7d992d285e8bcbb1f4ef21a6065f41c
11,922,829,226,504
963738bc478a942799096f0c9d652cfde36e7552
/iniciante/Uri_1049.java
119cb38cb5a157c1450a92d02ede0e45d4e230df
[]
no_license
Zaqueu-exe/urionlinejudge
https://github.com/Zaqueu-exe/urionlinejudge
541d0b4001db9b39bafdebc4c44bec6388421b8b
e4133df959356fbff6be0004b41d8256397af82f
refs/heads/main
2023-07-14T22:05:03.039000
2022-02-21T01:37:53
2022-02-21T01:37:53
376,390,135
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package iniciante; import java.util.Scanner; public class Uri_1049 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String aux, aux1, aux2; aux = scan.next(); aux1 = scan.next(); aux2 = scan.next(); switch(aux){ case "vertebrado" : switch(aux1){ case "ave" : switch(aux2){ case "carnivoro" : System.out.println("aguia"); break; case "onivoro" : System.out.println("pomba"); break; }break; case "mamifero" : switch(aux2){ case "onivoro" : System.out.println("homem"); break; case "herbivoro" : System.out.println("vaca"); break; } } case "invertebrado" : switch(aux1){ case "inseto" : switch(aux2){ case "hematofago" : System.out.println("pulga"); break; case "herbivoro" : System.out.println("lagarta"); break; }break; case "anelideo" : switch(aux2){ case "hematofago" : System.out.println("sanguessuga"); break; case "onivoro" : System.out.println("minhoca"); break; } } } } }
UTF-8
Java
1,348
java
Uri_1049.java
Java
[]
null
[]
package iniciante; import java.util.Scanner; public class Uri_1049 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String aux, aux1, aux2; aux = scan.next(); aux1 = scan.next(); aux2 = scan.next(); switch(aux){ case "vertebrado" : switch(aux1){ case "ave" : switch(aux2){ case "carnivoro" : System.out.println("aguia"); break; case "onivoro" : System.out.println("pomba"); break; }break; case "mamifero" : switch(aux2){ case "onivoro" : System.out.println("homem"); break; case "herbivoro" : System.out.println("vaca"); break; } } case "invertebrado" : switch(aux1){ case "inseto" : switch(aux2){ case "hematofago" : System.out.println("pulga"); break; case "herbivoro" : System.out.println("lagarta"); break; }break; case "anelideo" : switch(aux2){ case "hematofago" : System.out.println("sanguessuga"); break; case "onivoro" : System.out.println("minhoca"); break; } } } } }
1,348
0.469585
0.459199
35
36.514286
24.780605
81
false
false
0
0
0
0
0
0
0.771429
false
false
14
d03d0aeb194eb9bf173d0f2ace21be9c3576288b
27,427,661,165,540
e6f5358a0ba481e5175e2c5be0ebf9ddd780184f
/backend/java/mybatis-demo/src/main/java/com/jay/mapper/WorkCardMapper.java
ba22b848c845d7286067f521447b2d352a625175
[]
no_license
Jaykin/legend-demo
https://github.com/Jaykin/legend-demo
ae6dced8cf71684267be20cecbe069f366d21a3a
9a15f3d4af927e5ce79c92a3047a17a36194345d
refs/heads/master
2023-03-09T00:39:33.599000
2022-08-26T08:34:47
2022-08-26T08:34:47
179,935,499
1
0
null
false
2023-03-03T01:31:04
2019-04-07T08:09:22
2022-01-27T02:01:23
2023-03-03T01:31:03
17,657
1
0
22
JavaScript
false
false
package com.jay.mapper; import com.jay.entity.WorkCard; import org.apache.ibatis.annotations.Param; public interface WorkCardMapper { WorkCard getWorkCardByEmpid(@Param("empId") Long empId); }
UTF-8
Java
199
java
WorkCardMapper.java
Java
[]
null
[]
package com.jay.mapper; import com.jay.entity.WorkCard; import org.apache.ibatis.annotations.Param; public interface WorkCardMapper { WorkCard getWorkCardByEmpid(@Param("empId") Long empId); }
199
0.78392
0.78392
8
23.875
20.82329
60
false
false
0
0
0
0
0
0
0.5
false
false
14
2085fae8bfcadb0447cbe6ae2e87edca5188e889
3,418,793,982,324
cf936cd86f8c9bd83d18ec0bb88e82d8b1bc82b2
/src/numberlist/shared/BroadcastListener.java
7d3e3d572069ec95a4506cc456332f74b9fc7381
[]
no_license
KlausBogestrand/RMI
https://github.com/KlausBogestrand/RMI
751728bc36ce359e965fb9eced92e0e7ba4540ca
33d9188d7b2ed96f0381d8e28200d78a10393855
refs/heads/master
2021-05-17T00:26:59.783000
2020-03-27T12:54:57
2020-03-27T12:54:57
250,535,464
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package numberlist.shared; import java.rmi.Remote; import java.rmi.RemoteException; public interface BroadcastListener extends Remote { void listFull() throws RemoteException; }
UTF-8
Java
192
java
BroadcastListener.java
Java
[]
null
[]
package numberlist.shared; import java.rmi.Remote; import java.rmi.RemoteException; public interface BroadcastListener extends Remote { void listFull() throws RemoteException; }
192
0.770833
0.770833
8
22
18.734995
51
false
false
0
0
0
0
0
0
0.5
false
false
14
722bcce8de390515f96453c5339455288edcbb98
32,968,168,980,511
3b813e558a726574acf7e32fc4dad8e0c93e510f
/src/main/java/cz/stechy/drd/annotation/ColumnInfo.java
d2c8abf2912a5eb6f5fc7e088e3d126e60a971fb
[ "Apache-2.0" ]
permissive
japanoronha/drd
https://github.com/japanoronha/drd
ac9ed0b47c2173d804a580f50026d9c3d3234f30
aafd3975dbe5f5bb6f27870f6617c3a69d63c64e
refs/heads/master
2020-04-01T15:32:43.245000
2018-09-24T18:56:12
2018-09-24T18:56:12
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cz.stechy.drd.annotation; /** * Přepravka obsahující informace o daném sloupečku */ public class ColumnInfo { final String name; final Class clazz; public ColumnInfo(String name, Class clazz) { this.name = name; this.clazz = clazz; } }
UTF-8
Java
286
java
ColumnInfo.java
Java
[]
null
[]
package cz.stechy.drd.annotation; /** * Přepravka obsahující informace o daném sloupečku */ public class ColumnInfo { final String name; final Class clazz; public ColumnInfo(String name, Class clazz) { this.name = name; this.clazz = clazz; } }
286
0.654804
0.654804
15
17.733334
17.058592
51
false
false
0
0
0
0
0
0
0.4
false
false
14
0703efb4352fde784f18fde1b4941f601d948586
32,358,283,622,354
c0ab6310d1af55bca609f273e606d4f7cffbcc47
/AndroidUtils/src/main/java/com/bhaskar/views/AndWebView.java
91ee09347eaf1b4130fce7d3f0ebd45a8386bed2
[]
no_license
GajendraVish/DSE
https://github.com/GajendraVish/DSE
17503fc1b153eb8557f272bb77c9fdea756371dd
01c60e99e37dd7b37b6c5682d1bae5ca946ba8ce
refs/heads/master
2022-11-12T05:27:34.372000
2020-07-03T03:00:51
2020-07-03T03:00:51
276,672,471
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bhaskar.views; import android.content.Context; import android.util.AttributeSet; import android.webkit.WebView; public class AndWebView extends WebView { public AndWebView(Context context) { super(context); } public AndWebView(Context context, AttributeSet attrs) { super(context, attrs); } public AndWebView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public AndWebView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } /*@Override public boolean onCheckIsTextEditor() { return true; }*/ }
UTF-8
Java
722
java
AndWebView.java
Java
[]
null
[]
package com.bhaskar.views; import android.content.Context; import android.util.AttributeSet; import android.webkit.WebView; public class AndWebView extends WebView { public AndWebView(Context context) { super(context); } public AndWebView(Context context, AttributeSet attrs) { super(context, attrs); } public AndWebView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public AndWebView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } /*@Override public boolean onCheckIsTextEditor() { return true; }*/ }
722
0.695291
0.695291
29
23.896551
25.05765
95
false
false
0
0
0
0
0
0
0.724138
false
false
14
dcda475dc7867a1bf3906977ae829ef8ac66282e
27,315,992,030,957
309ba9bf6ef7d6261f795037cc7ceaa834ffe6cd
/Struts2Demo/src/com/demo/struts/service/LoginService.java
3a742e7261d697dcd2702a16aa06ba5a5134d999
[]
no_license
wzfzlw/MyCoding
https://github.com/wzfzlw/MyCoding
a1221c0390f2c86f27182cbbfec4787f9b64b179
3a3687972e6754b6d6a7ad23b8fb260ccf2b111f
refs/heads/master
2016-04-02T18:48:00.870000
2015-02-03T09:31:49
2015-02-04T16:29:30
26,112,109
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.demo.struts.service; /** * Created by wz on 2015/2/3. */ public interface LoginService { public boolean isLogin(String username,String password); }
UTF-8
Java
170
java
LoginService.java
Java
[ { "context": "ackage com.demo.struts.service;\n\n/**\n * Created by wz on 2015/2/3.\n */\npublic interface LoginService {\n", "end": 54, "score": 0.9995508193969727, "start": 52, "tag": "USERNAME", "value": "wz" } ]
null
[]
package com.demo.struts.service; /** * Created by wz on 2015/2/3. */ public interface LoginService { public boolean isLogin(String username,String password); }
170
0.711765
0.676471
11
14.454545
19.41585
60
false
false
0
0
0
0
0
0
0.272727
false
false
14
80399bed4f55c307b09be579d061e8c73a4511a8
14,525,579,420,973
5f11e9778657a02e699de184f7ed5961b0627ca0
/src/main/java/com/bitcup/dropboxfoldercreator/actor/FolderCreatorActor.java
b1e12cfd08bca22bee260610fa109595f890d0dc
[]
no_license
bitcup/dropbox-folder-creator
https://github.com/bitcup/dropbox-folder-creator
8d627c9fb38f7bbb168a34cb319ad04ac3ca4f4f
42ed49335cbf4bb7a768968d9dbdcc2e5aa21255
refs/heads/master
2021-01-19T00:25:20.877000
2016-11-08T00:55:52
2016-11-08T00:55:52
73,029,234
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bitcup.dropboxfoldercreator.actor; import akka.actor.ActorRef; import akka.actor.UntypedActor; import akka.event.Logging; import akka.event.LoggingAdapter; import com.bitcup.dropboxfoldercreator.config.Config; import com.bitcup.dropboxfoldercreator.domain.Student; import com.bitcup.dropboxfoldercreator.dropbox.DropboxClient; import com.bitcup.dropboxfoldercreator.message.CreateFolders; import com.bitcup.dropboxfoldercreator.message.CreationResult; import com.bitcup.dropboxfoldercreator.message.RecordRetry; import com.dropbox.core.DbxException; import com.dropbox.core.RetryException; import com.dropbox.core.v2.files.FolderMetadata; import com.dropbox.core.v2.sharing.AccessLevel; import scala.Option; import java.util.Random; /** * Creates folders for a single student. * * @author bitcup */ public class FolderCreatorActor extends UntypedActor { private LoggingAdapter log = Logging.getLogger(getContext().system(), this); private DropboxClient dropboxClient = DropboxClient.getInstance(); private Student student; private ActorRef supervisor; private Random random = new Random(); public FolderCreatorActor(Student student, ActorRef supervisor) { this.student = student; this.supervisor = supervisor; } @Override public void onReceive(Object message) throws Throwable { if (message instanceof CreateFolders) { createFolders(); } else { unhandled(message); log.info("unhandled message {}", message); } } @Override public void preRestart(Throwable reason, Option<Object> message) throws Exception { log.debug("pre-restart - reason: {}, message: {}", reason.getMessage(), message.getClass()); // tell supervisor that we're retrying this student supervisor.tell(new RecordRetry(student), getSelf()); // re-send the same message to ourselves in order to retry creating the folders getSelf().tell(message.get(), supervisor); super.preRestart(reason, message); } private void createFolders() throws DbxException { try { String topFolderLink = "link goes here"; if (Config.val("invoke.dbx").equals("true")) { FolderMetadata studentFolder = dropboxClient.createFolderIfNotExists(student.getStudentFolderName(), Config.val("dropbox.top.folder")); dropboxClient.createFolderIfNotExists(Config.val("dropbox.sub1.folder"), studentFolder.getPathDisplay()); dropboxClient.createFolderIfNotExists(Config.val("dropbox.sub2.folder"), studentFolder.getPathDisplay()); topFolderLink = dropboxClient.shareFolderAndGetUrl(studentFolder, student.getEmail(), AccessLevel.EDITOR); } else { int r = random.nextInt(3); if (r == 0) { throw new RetryException("", "intermittent dbx failure: could not create folders for " + student.getStudentFolderName()); } if (r == 1) { throw new IllegalArgumentException("irrecoverable failure: could not create folders for " + student.getStudentFolderName()); } } log.info("success: folders created for: {}", student.getStudentFolderName()); supervisor.tell(new CreationResult.Success(student, topFolderLink), getSelf()); } catch (IllegalArgumentException e) { // we tell supervisor about failure supervisor.tell(new CreationResult.Failure(student), getSelf()); throw e; } } }
UTF-8
Java
3,621
java
FolderCreatorActor.java
Java
[ { "context": "reates folders for a single student.\n *\n * @author bitcup\n */\npublic class FolderCreatorActor extends Untyp", "end": 813, "score": 0.9996182918548584, "start": 807, "tag": "USERNAME", "value": "bitcup" } ]
null
[]
package com.bitcup.dropboxfoldercreator.actor; import akka.actor.ActorRef; import akka.actor.UntypedActor; import akka.event.Logging; import akka.event.LoggingAdapter; import com.bitcup.dropboxfoldercreator.config.Config; import com.bitcup.dropboxfoldercreator.domain.Student; import com.bitcup.dropboxfoldercreator.dropbox.DropboxClient; import com.bitcup.dropboxfoldercreator.message.CreateFolders; import com.bitcup.dropboxfoldercreator.message.CreationResult; import com.bitcup.dropboxfoldercreator.message.RecordRetry; import com.dropbox.core.DbxException; import com.dropbox.core.RetryException; import com.dropbox.core.v2.files.FolderMetadata; import com.dropbox.core.v2.sharing.AccessLevel; import scala.Option; import java.util.Random; /** * Creates folders for a single student. * * @author bitcup */ public class FolderCreatorActor extends UntypedActor { private LoggingAdapter log = Logging.getLogger(getContext().system(), this); private DropboxClient dropboxClient = DropboxClient.getInstance(); private Student student; private ActorRef supervisor; private Random random = new Random(); public FolderCreatorActor(Student student, ActorRef supervisor) { this.student = student; this.supervisor = supervisor; } @Override public void onReceive(Object message) throws Throwable { if (message instanceof CreateFolders) { createFolders(); } else { unhandled(message); log.info("unhandled message {}", message); } } @Override public void preRestart(Throwable reason, Option<Object> message) throws Exception { log.debug("pre-restart - reason: {}, message: {}", reason.getMessage(), message.getClass()); // tell supervisor that we're retrying this student supervisor.tell(new RecordRetry(student), getSelf()); // re-send the same message to ourselves in order to retry creating the folders getSelf().tell(message.get(), supervisor); super.preRestart(reason, message); } private void createFolders() throws DbxException { try { String topFolderLink = "link goes here"; if (Config.val("invoke.dbx").equals("true")) { FolderMetadata studentFolder = dropboxClient.createFolderIfNotExists(student.getStudentFolderName(), Config.val("dropbox.top.folder")); dropboxClient.createFolderIfNotExists(Config.val("dropbox.sub1.folder"), studentFolder.getPathDisplay()); dropboxClient.createFolderIfNotExists(Config.val("dropbox.sub2.folder"), studentFolder.getPathDisplay()); topFolderLink = dropboxClient.shareFolderAndGetUrl(studentFolder, student.getEmail(), AccessLevel.EDITOR); } else { int r = random.nextInt(3); if (r == 0) { throw new RetryException("", "intermittent dbx failure: could not create folders for " + student.getStudentFolderName()); } if (r == 1) { throw new IllegalArgumentException("irrecoverable failure: could not create folders for " + student.getStudentFolderName()); } } log.info("success: folders created for: {}", student.getStudentFolderName()); supervisor.tell(new CreationResult.Success(student, topFolderLink), getSelf()); } catch (IllegalArgumentException e) { // we tell supervisor about failure supervisor.tell(new CreationResult.Failure(student), getSelf()); throw e; } } }
3,621
0.682408
0.680475
86
41.104652
36.056812
151
false
false
0
0
0
0
0
0
0.732558
false
false
14
cc1976cfd0febb432afb1bd4e6196fb1444f0859
24,627,342,498,038
a1bb564eb3defacc32245cd90b69e7eed87ba91d
/app/src/main/java/com/example/gallery/ImageAdapter.java
3fa34f8c16a45f84c5d57d3a2d2d69dc7d0c99c9
[]
no_license
vitham/vit-gallery
https://github.com/vitham/vit-gallery
486e041e633ee7e5aa323d0b2797a0811ef97b6f
c27d36dfbf68e32ea6e4d20de621bc899c000710
refs/heads/master
2020-05-22T21:41:48.262000
2019-05-14T02:50:10
2019-05-14T02:50:10
186,532,824
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.gallery; import android.content.Context; import android.graphics.Bitmap; import android.net.Uri; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.io.IOException; import java.util.ArrayList; public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ViewHolder> { private Context mContext; private ArrayList<Image> mImages; private OnImageListener mListener; public void setListener(OnImageListener listener) { mListener = listener; } public ImageAdapter(ArrayList<Image> images) { mImages = images; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { mContext = viewGroup.getContext(); View view = LayoutInflater.from(mContext).inflate(R.layout.image_item_layout, viewGroup, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) { viewHolder.bindData(mImages.get(i)); } @Override public int getItemCount() { return mImages == null ? 0 : mImages.size(); } public class ViewHolder extends RecyclerView.ViewHolder implements View.OnLongClickListener, View.OnClickListener { private ImageView mImageSmall; private TextView mTextDate; public ViewHolder(@NonNull View itemView) { super(itemView); initViews(itemView); registerEvents(); } private void registerEvents() { itemView.setOnLongClickListener(this); itemView.setOnClickListener(this); } private void initViews(View itemView) { mImageSmall = itemView.findViewById(R.id.image_crop); mTextDate = itemView.findViewById(R.id.text_create_date); } public void bindData(Image image) { mTextDate.setText(image.getDate()); try { Bitmap bitmap = MediaStore.Images.Media.getBitmap(mContext.getContentResolver(), Uri.parse(image.getPath())); mImageSmall.setImageBitmap(bitmap); } catch (IOException e) { e.printStackTrace(); } // Glide.with(mContext) // .load(image.getPath()) // .into(mImageSmall); } @Override public boolean onLongClick(View v) { mListener.onLongClickListener(mImages.get(getAdapterPosition())); return true; } @Override public void onClick(View v) { mListener.onClickListener(mImages.get(getAdapterPosition())); } } public void update(ArrayList<Image> images) { mImages.addAll(images); notifyDataSetChanged(); } public interface OnImageListener { void onLongClickListener(Image image); void onClickListener(Image image); } }
UTF-8
Java
3,179
java
ImageAdapter.java
Java
[]
null
[]
package com.example.gallery; import android.content.Context; import android.graphics.Bitmap; import android.net.Uri; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.io.IOException; import java.util.ArrayList; public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ViewHolder> { private Context mContext; private ArrayList<Image> mImages; private OnImageListener mListener; public void setListener(OnImageListener listener) { mListener = listener; } public ImageAdapter(ArrayList<Image> images) { mImages = images; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { mContext = viewGroup.getContext(); View view = LayoutInflater.from(mContext).inflate(R.layout.image_item_layout, viewGroup, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) { viewHolder.bindData(mImages.get(i)); } @Override public int getItemCount() { return mImages == null ? 0 : mImages.size(); } public class ViewHolder extends RecyclerView.ViewHolder implements View.OnLongClickListener, View.OnClickListener { private ImageView mImageSmall; private TextView mTextDate; public ViewHolder(@NonNull View itemView) { super(itemView); initViews(itemView); registerEvents(); } private void registerEvents() { itemView.setOnLongClickListener(this); itemView.setOnClickListener(this); } private void initViews(View itemView) { mImageSmall = itemView.findViewById(R.id.image_crop); mTextDate = itemView.findViewById(R.id.text_create_date); } public void bindData(Image image) { mTextDate.setText(image.getDate()); try { Bitmap bitmap = MediaStore.Images.Media.getBitmap(mContext.getContentResolver(), Uri.parse(image.getPath())); mImageSmall.setImageBitmap(bitmap); } catch (IOException e) { e.printStackTrace(); } // Glide.with(mContext) // .load(image.getPath()) // .into(mImageSmall); } @Override public boolean onLongClick(View v) { mListener.onLongClickListener(mImages.get(getAdapterPosition())); return true; } @Override public void onClick(View v) { mListener.onClickListener(mImages.get(getAdapterPosition())); } } public void update(ArrayList<Image> images) { mImages.addAll(images); notifyDataSetChanged(); } public interface OnImageListener { void onLongClickListener(Image image); void onClickListener(Image image); } }
3,179
0.647373
0.646744
108
28.435184
25.334894
125
false
false
0
0
0
0
0
0
0.472222
false
false
14
5b26f7fd2fa4deae0fe9b93fd5d39d3a754e1dbf
17,738,214,953,064
5201b5350d2f47a510184abaf24057f832dc9499
/gehr/src/hris/J/J03JobCreate/J03RequireLevelData.java
69fe7d6f792828e63376bfad1d08dd390162dfb7
[]
no_license
haneul9/LG_CHEM
https://github.com/haneul9/LG_CHEM
a70f361a53c906ec99a7ae40ce719e6597d014ea
211a7c1e2bb4230f5f217c21b32fb016ae3993e3
refs/heads/master
2020-04-14T15:49:37.183000
2019-01-03T07:44:40
2019-01-03T07:44:40
163,938,280
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package hris.J.J03JobCreate; /** * J03RequireLevelData.java * 생성시 리턴되는 작업 Message Data * [관련 RFC] : ZHRH_RFC_GET_REQUIRE_LEVEL, * * @author 원도연 * @version 1.0, 2003/06/16 */ public class J03RequireLevelData extends com.sns.jdf.EntityData { // L_RESUTL(ZHRH109S) public String SCALE_ID ; // 스케일 ID public String RATING ; // 품질범위숙련도 public String PSTEXT ; // 숙련도텍스트 스케일 }
UHC
Java
506
java
J03RequireLevelData.java
Java
[ { "context": "C] : ZHRH_RFC_GET_REQUIRE_LEVEL,\r\n * \r\n * @author 원도연\r\n * @version 1.0, 2003/06/16\r\n */\r\npublic class J", "end": 158, "score": 0.999211311340332, "start": 155, "tag": "NAME", "value": "원도연" } ]
null
[]
package hris.J.J03JobCreate; /** * J03RequireLevelData.java * 생성시 리턴되는 작업 Message Data * [관련 RFC] : ZHRH_RFC_GET_REQUIRE_LEVEL, * * @author 원도연 * @version 1.0, 2003/06/16 */ public class J03RequireLevelData extends com.sns.jdf.EntityData { // L_RESUTL(ZHRH109S) public String SCALE_ID ; // 스케일 ID public String RATING ; // 품질범위숙련도 public String PSTEXT ; // 숙련도텍스트 스케일 }
506
0.606818
0.563636
17
23.117647
19.186031
65
false
false
0
0
0
0
0
0
0.352941
false
false
14
acc1da6242c82e36ca4e650cfd12c18e680ee1e3
19,679,540,177,155
0881fe31966bb947445b4b5ec927bc6e68396f39
/src/main/java/parser/other/XmlCharacterHandler.java
0a086819f4cde5b3ee3298b781ac0b6802373e87
[]
no_license
MARudnicki/in-xml-csv-parser
https://github.com/MARudnicki/in-xml-csv-parser
cca70125020dfd9c5d74701e7fcb25a2e4f554f5
dfe276a773e0aa2b790abb4a8b7ace2d10e8dfac
refs/heads/master
2020-02-27T06:01:54.117000
2017-03-10T12:59:54
2017-03-10T12:59:54
84,066,575
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package parser.other; import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.Properties; import java.util.regex.Pattern; import java.util.stream.Collectors; /** * Handler for replacing special characters like & into &apos; */ public class XmlCharacterHandler { /** * Path to properties. */ private static final String PROPERTIES_PATH = "exceptionCharacters.properties"; /** * Properties entity. */ private static Properties properties; /** * */ private static Pattern pattern; /** * Static initiation of properties. */ static { properties = new Properties(); InputStream input = ExceptionWordsService.class.getClassLoader().getResourceAsStream(PROPERTIES_PATH); try { properties.load(input); pattern = Pattern.compile(String.join("", "[", properties.keySet().stream().map(String::valueOf).collect (Collectors.joining("")),"’", "]")); } catch (IOException e) { throw new RuntimeException("Can't read properties file " + PROPERTIES_PATH); } } /** * handle special character e.g replace & into &apos; or ’ into ' * * @param line sentence with words */ public static String handleSpecialCharacters(String line) { if(pattern.matcher(line).find()){ line = line.replace("’", "'"); //right apostrophe handling for (Map.Entry entry : properties.entrySet()) { line = line.replace((String) entry.getKey(), (String) entry.getValue()); } } return line; } }
UTF-8
Java
1,680
java
XmlCharacterHandler.java
Java
[]
null
[]
package parser.other; import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.Properties; import java.util.regex.Pattern; import java.util.stream.Collectors; /** * Handler for replacing special characters like & into &apos; */ public class XmlCharacterHandler { /** * Path to properties. */ private static final String PROPERTIES_PATH = "exceptionCharacters.properties"; /** * Properties entity. */ private static Properties properties; /** * */ private static Pattern pattern; /** * Static initiation of properties. */ static { properties = new Properties(); InputStream input = ExceptionWordsService.class.getClassLoader().getResourceAsStream(PROPERTIES_PATH); try { properties.load(input); pattern = Pattern.compile(String.join("", "[", properties.keySet().stream().map(String::valueOf).collect (Collectors.joining("")),"’", "]")); } catch (IOException e) { throw new RuntimeException("Can't read properties file " + PROPERTIES_PATH); } } /** * handle special character e.g replace & into &apos; or ’ into ' * * @param line sentence with words */ public static String handleSpecialCharacters(String line) { if(pattern.matcher(line).find()){ line = line.replace("’", "'"); //right apostrophe handling for (Map.Entry entry : properties.entrySet()) { line = line.replace((String) entry.getKey(), (String) entry.getValue()); } } return line; } }
1,680
0.606332
0.606332
60
26.9
28.681992
116
false
false
0
0
0
0
0
0
0.433333
false
false
14
5c8c751f330a2347056eaf8dc07f86d64d31b511
27,496,380,658,792
7d346b6e1020bb46557bbd2e6d84f228c59e523c
/core-db/src/main/java/com/system/db/repository/specification/builder/EntitySpecificationBuilder.java
0b0225ab6a27e8eb9bfa3f2c24f07063ad2fd32e
[]
no_license
ampopp04/system
https://github.com/ampopp04/system
68be6c30debd2c58a30d50094a54f588cc9f5acd
68cdc2b670512901d85366e66efa37f231143521
refs/heads/master
2020-03-10T02:11:52.255000
2018-04-11T18:16:33
2018-04-11T18:16:33
129,130,219
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright 2018, Andrew Popp, All rights reserved. Email ampopp04@gmail.com for commercial licensing use and pricing */ package com.system.db.repository.specification.builder; import com.system.db.repository.search.criteria.SearchCriteria; import com.system.db.repository.specification.EntitySpecification; import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.domain.Specifications; import java.util.ArrayList; import java.util.List; /** * The <interface>EntitySpecification</interface> defines the * base database search predicate specification. * * @author Andrew * @see Specification */ public class EntitySpecificationBuilder<T> { /////////////////////////////////////////////////////////////////////// //////// Properties ////////// ///////////////////////////////////////////////////////////////////// private final List<SearchCriteria> params; private Integer searchDepth; /////////////////////////////////////////////////////////////////////// //////// Constructor ////////// ////////////////////////////////////////////////////////////////////// public EntitySpecificationBuilder(Integer searchDepth) { params = new ArrayList<>(); this.searchDepth = searchDepth; } /////////////////////////////////////////////////////////////////////// //////// Implementation ////////// ////////////////////////////////////////////////////////////////////// public EntitySpecificationBuilder with(String key, String operation, String value) { params.add(new SearchCriteria(key, operation, value)); return this; } public Specification<T> build() { if (params.size() == 0) { return null; } List<Specification<T>> specs = new ArrayList<>(); for (SearchCriteria param : params) { specs.add(new EntitySpecification<>(param, searchDepth)); } Specification<T> result = specs.get(0); for (int i = 1; i < specs.size(); i++) { result = Specifications.where(result).and(specs.get(i)); } return result; } }
UTF-8
Java
2,473
java
EntitySpecificationBuilder.java
Java
[ { "context": "/*\n * Copyright 2018, Andrew Popp, All rights reserved. Email ampopp04@gmail.com fo", "end": 33, "score": 0.999843418598175, "start": 22, "tag": "NAME", "value": "Andrew Popp" }, { "context": "ight 2018, Andrew Popp, All rights reserved. Email ampopp04@gmail.com for commercial licensing use and pricing\n */\n\npac", "end": 80, "score": 0.9999287128448486, "start": 62, "tag": "EMAIL", "value": "ampopp04@gmail.com" }, { "context": "base search predicate specification.\n *\n * @author Andrew\n * @see Specification\n */\npublic class EntitySpec", "end": 620, "score": 0.7854766845703125, "start": 614, "tag": "NAME", "value": "Andrew" } ]
null
[]
/* * Copyright 2018, <NAME>, All rights reserved. Email <EMAIL> for commercial licensing use and pricing */ package com.system.db.repository.specification.builder; import com.system.db.repository.search.criteria.SearchCriteria; import com.system.db.repository.specification.EntitySpecification; import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.domain.Specifications; import java.util.ArrayList; import java.util.List; /** * The <interface>EntitySpecification</interface> defines the * base database search predicate specification. * * @author Andrew * @see Specification */ public class EntitySpecificationBuilder<T> { /////////////////////////////////////////////////////////////////////// //////// Properties ////////// ///////////////////////////////////////////////////////////////////// private final List<SearchCriteria> params; private Integer searchDepth; /////////////////////////////////////////////////////////////////////// //////// Constructor ////////// ////////////////////////////////////////////////////////////////////// public EntitySpecificationBuilder(Integer searchDepth) { params = new ArrayList<>(); this.searchDepth = searchDepth; } /////////////////////////////////////////////////////////////////////// //////// Implementation ////////// ////////////////////////////////////////////////////////////////////// public EntitySpecificationBuilder with(String key, String operation, String value) { params.add(new SearchCriteria(key, operation, value)); return this; } public Specification<T> build() { if (params.size() == 0) { return null; } List<Specification<T>> specs = new ArrayList<>(); for (SearchCriteria param : params) { specs.add(new EntitySpecification<>(param, searchDepth)); } Specification<T> result = specs.get(0); for (int i = 1; i < specs.size(); i++) { result = Specifications.where(result).and(specs.get(i)); } return result; } }
2,457
0.456935
0.453296
67
35.910446
36.748737
140
false
false
0
0
0
0
73
0.175091
0.41791
false
false
14
e894cfa4b608dd4e64038d2b78a6236cb582648d
29,746,943,524,869
47e3676edfd1ebefa74f231e66447f631f017cef
/src/android/Ipfs.java
ca06fb9acfbd6f2f90a4110655e66acef005efae
[ "Apache-2.0" ]
permissive
xSkyripper/cordova-plugin-ipfs
https://github.com/xSkyripper/cordova-plugin-ipfs
39e02c3c93e1ea4cbe0166ee98e91ba263a66f3c
520814d3921aa071d8c98be5faa8cafe2ae07c86
refs/heads/master
2021-01-20T13:21:33.992000
2017-06-29T21:18:12
2017-06-29T21:18:12
90,473,832
5
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.apache.cordova.ipfs; import android.util.Log; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaWebView; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.rauschig.jarchivelib.ArchiveFormat; import org.rauschig.jarchivelib.Archiver; import org.rauschig.jarchivelib.ArchiverFactory; import org.rauschig.jarchivelib.CompressionType; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.concurrent.Future; /** * This class extends the CordovaPlugin and provides a wrap for go-ipfs arm binaries * which can be used is Cordova projects. It consists of the basic functionalities like * downloading, extracting, initing the repo, starting / stopping the daemon * * @author xSkyripper */ public class Ipfs extends CordovaPlugin { private URL ipfsArchiveSrc; private String appFilesDir; private String ipfsBinPath; private String ipfsRepo; private Process ipfsDaemonProcess = null; private Future ipfsDaemonThreadFuture = null; private String LOG_TAG = "#######CIP######"; /** * Function for starting a system process that will "shell execute" the given command(s) * in the cmdArray, using the environment variables provided in envArray. The process will be * waited to finish * If ignoreExc is true, the error output of the command will be ignored. * * @param cmdArray the array of shell commands * @param envArray the array of environment variables * @param ignoreExc if true, the error output is ignores; else, and IOException will be thrown * @throws IOException thrown if something happens with the process or if the error output is * not ignored * @throws InterruptedException thrown if something happens on waiting the process to finish */ private void execShell(final String[] cmdArray, final String[] envArray, Boolean ignoreExc, String workingDir) throws IOException, InterruptedException { Log.d(LOG_TAG, Arrays.toString(cmdArray)); Process proc; if (workingDir != null) proc = Runtime.getRuntime().exec(cmdArray, envArray, new File(workingDir)); else proc = Runtime.getRuntime().exec(cmdArray, envArray); StringBuilder procOutput = new StringBuilder(); StringBuilder procError = new StringBuilder(); String line; BufferedReader procOutputReader = new BufferedReader(new InputStreamReader(proc.getInputStream())); while ((line = procOutputReader.readLine()) != null) { procOutput.append(line).append("\n"); Log.d(LOG_TAG, line); } BufferedReader procErrorReader = new BufferedReader(new InputStreamReader(proc.getErrorStream())); while ((line = procErrorReader.readLine()) != null) { procError.append(line).append("\n"); Log.d(LOG_TAG, line); } //Log.d(LOG_TAG, procOutput.toString()); if (!ignoreExc) if (!procError.toString().equals("")) { Log.d(LOG_TAG, "Tried:" + Arrays.toString(cmdArray)); throw new IOException(procError.toString()); } proc.waitFor(); } /** * Deletes a file or a directory recursively; if the delete returns 'false' (some file could * not be deleted), it simply logs a messages * * @param fileOrDirectory the file / dir to be deleted */ private void deleteRecursive(File fileOrDirectory) { if (fileOrDirectory.isDirectory()) for (File child : fileOrDirectory.listFiles()) deleteRecursive(child); if (!(fileOrDirectory.delete())) Log.d(LOG_TAG, "File " + fileOrDirectory.getName() + " couldn't be deleted !"); } /** * Checks if a process is running by trying to access the exitValue; if an exception is thrown * then the process is still running; otherwise, it finished running and it has an exit value * * @param process the process to be checked * @return true if the process is running; false otherwise */ private Boolean isRunning(Process process) { try { process.exitValue(); return false; } catch (Exception e) { return true; } } /** * Download the go-ipfs archive from the ipfsArchiveSrc provided at "init" * The method open the connection to the URL provided, checks if the connection * returns HTTP "200", else it throws an exception; It also checks if the archive already exists * and it has the same size as the archive existing at the URL provided; * * @throws Exception if something happens (connection couldn't be initiated, the source server * returned something else than "200", stream exceptions) */ private void downloadIpfs() throws Exception { InputStream input; OutputStream output; HttpURLConnection conn; int archiveFileLength; long totalDownloaded = 0; byte block[] = new byte[4096]; int blockSize; Log.d(LOG_TAG, "STARTING DOWNLOAD"); conn = (HttpURLConnection) ipfsArchiveSrc.openConnection(); Log.d(LOG_TAG, "OPENED CONN"); conn.connect(); Log.d(LOG_TAG, "CONNECTED TO SRC"); if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new Exception("Server returned HTTP " + conn.getResponseCode() + " " + conn.getResponseMessage()); } Log.d(LOG_TAG, "GOT 200 FROM SRC"); archiveFileLength = conn.getContentLength(); File oldArchive = new File(appFilesDir + "go-ipfs.tar.gz"); // archive exists and has the same size (TODO: HASH CHECKING) if (oldArchive.exists() && oldArchive.length() == archiveFileLength) { Log.d(LOG_TAG, "archive exists and has the same length"); return; } input = conn.getInputStream(); output = new FileOutputStream(appFilesDir + "go-ipfs.tar.gz"); int lastDownTotal = -1; while ((blockSize = input.read(block)) != -1) { totalDownloaded += blockSize; if (archiveFileLength > 0) { if (((int) (totalDownloaded * 100 / archiveFileLength)) % 10 == 0) if (((int) (totalDownloaded * 100 / archiveFileLength)) != lastDownTotal) { lastDownTotal = (int) (totalDownloaded * 100 / archiveFileLength); Log.d(LOG_TAG, "Downloaded " + lastDownTotal + "%"); } } output.write(block, 0, blockSize); } Log.d(LOG_TAG, "FINISHED DOWNLOADING"); input.close(); output.close(); conn.disconnect(); } /** * Extracts the archive downloaded by downloadIpfs using the custom jar included in the project * to the same directory, tries to make the binary executable and * finally deletes the archive for "space reasons" * * @throws Exception an exception is thrown if the IPFS binary couldn't be made executable */ private void extractIpfs() throws Exception { Log.d(LOG_TAG, "STARTING EXTRACT"); Archiver archiver = ArchiverFactory.createArchiver(ArchiveFormat.TAR, CompressionType.GZIP); archiver.extract(new File(appFilesDir + "go-ipfs.tar.gz"), new File(appFilesDir)); if (!(new File(ipfsBinPath).setExecutable(true, true))) { throw new Exception("IPFS Bin " + ipfsBinPath + " cannot be set executable !"); } this.deleteRecursive(new File(appFilesDir + "go-ipfs.tar.gz")); Log.d(LOG_TAG, "FINISHED EXTRACT"); } /** * Calls the 2 methods that "prepare" go-ipfs ARM: downloadIpfs and extractIpfs * * @throws Exception exceptions are re-thrown from these 2 functions */ private void prepareIpfs() throws Exception { this.downloadIpfs(); this.extractIpfs(); } /** * Reads the IPFS config file and adds the next permissions on HTTPHeaders for API connections * API.HTTPHeaders.Access-Control-Allow-Origin "[\"*\"]" * API.HTTPHeaders.Access-Control-Allow-Credentials "[\"true\"]" * * @throws IOException if the config file doesn't exist or other problem * @throws JSONException if the json data cannot be parse or other problem */ private void configAPI() throws IOException, JSONException { int num; char[] buffer = new char[1024]; BufferedReader input; StringBuilder content = new StringBuilder(); input = new BufferedReader( new InputStreamReader( new FileInputStream(ipfsRepo + "config") ) ); while ((num = input.read(buffer)) > 0) { content.append(buffer, 0, num); } JSONObject jsonConfig = new JSONObject(content.toString()); jsonConfig.getJSONObject("API").put("HTTPHeaders", new JSONObject("{" + "\"Access-Control-Allow-Credentials\": [" + "\"true\"" + "]," + "\"Access-Control-Allow-Origin\": [" + "\"*\"" + "]" + "}")); input.close(); FileWriter file = new FileWriter(ipfsRepo + "config"); file.write(jsonConfig.toString(4)); file.close(); Log.d(LOG_TAG, "FINISHED CONFIGING FOR API !"); } /** * Deletes the current IPFS Repo folder and tries to recreate it using "ipfs init" exec shell * taking into account possible errors on initing * * @throws Exception thrown by exec shell ('ipfs init') if something happens during initialization */ private void initRepo() throws Exception { Log.d(LOG_TAG, "INITING IF REPO RESET OR REPO NOT EXISTS"); this.deleteRecursive(new File(ipfsRepo)); this.execShell( new String[]{ipfsBinPath, "init"}, new String[]{"IPFS_PATH=" + this.ipfsRepo}, false, null); Log.d(LOG_TAG, "INITING FINISHED"); } /** * 'init' plugin function exposed to JS interface, ran asynchronously * Parses the arguments provided, saves them. builds the path of the repo and the binary * and tries to prepare the IPF if the binary doesn't exist * and to init the repo if the IPFS repo dir doesn't exists or if resetRepo option is 'true' * * @param args JSONArray arguments provided from the call; expected to find * 'appFilesDir' the path to the app's files/files dir, * 'src' the URL of the go-ipfs ARM tar.gz archive * 'resetRepo' boolean used for reseting the repo * @param cbCtx callback context used to call succes or error callbacks */ private void init(final JSONArray args, final CallbackContext cbCtx) { final Runnable initAsync = new Runnable() { @Override public void run() { Boolean resetRepo; try { JSONObject config = args.getJSONObject(0); appFilesDir = config.getString("appFilesDir"); ipfsArchiveSrc = new URL(config.getString("src")); ipfsBinPath = appFilesDir.concat("go-ipfs/ipfs"); ipfsRepo = appFilesDir.concat(".ipfs/"); resetRepo = config.getBoolean("resetRepo"); Log.d(LOG_TAG, "ipfsBinPath: " + ipfsBinPath); Log.d(LOG_TAG, "ipfsArchiveSrc: " + ipfsArchiveSrc); Log.d(LOG_TAG, "appFilesDir: " + appFilesDir); Log.d(LOG_TAG, "ipfsRepo: " + ipfsRepo); Log.d(LOG_TAG, "resetRepo: " + resetRepo); } catch (JSONException e) { e.printStackTrace(); cbCtx.error("Cordova IPFS Plugin (init): \n" + e.toString()); return; } catch (MalformedURLException e) { e.printStackTrace(); cbCtx.error("Cordova IPFS Plugin (init): \n" + e.toString()); return; } if (!(new File(ipfsBinPath).exists())) try { prepareIpfs(); } catch (Exception e) { e.printStackTrace(); cbCtx.error("Cordova IPFS Plugin (init): \n" + e.toString()); return; } if (resetRepo || !(new File(ipfsRepo).exists())) try { initRepo(); } catch (IOException e) { e.printStackTrace(); cbCtx.error("Cordova IPFS Plugin (init): \n" + e.toString()); return; } catch (InterruptedException e) { e.printStackTrace(); cbCtx.error("Cordova IPFS Plugin (init): \n" + e.toString()); return; } catch (Exception e) { e.printStackTrace(); cbCtx.error("Cordova IPFS Plugin (init): \n" + e.toString()); return; } cbCtx.success("Cordova IPFS Plugin (init): IPFS was prepared & inited !"); } }; cordova.getThreadPool().execute(initAsync); } /** * 'start' plugin function exposed to JS interface, ran asynchronously * Checks if the IPFS binary and the IPFS repo dir exist, throwing an error of they don't * Tries to set through exec shell the IPFS config access control * Starts the IPFS daemon with 'pubsub' in a new process * contained by a thread if it's not already running and sets the local Future of the thread * * @param cbCtx callback context used to call success or error callbacks */ private void startDaemon(final CallbackContext cbCtx) { //> ipfs config --json API.HTTPHeaders.Access-Control-Allow-Credentials "[\"true\"]" //> ipfs config --json API.HTTPHeaders.Access-Control-Allow-Origin "[\"*\"]" final Runnable ipfsDaemonThread = new Runnable() { @Override public void run() { if (!(new File(ipfsBinPath).exists())) { cbCtx.error("Cordova IPFS Plugin (start): \n" + "The IPFS was not prepared (binary not found)" + " Run init first or wait for init to finish !"); return; } if (!(new File(ipfsRepo).exists())) { cbCtx.error("Cordova IPFS Plugin (start): \n" + "The IPFS repo was not initialized (" + ipfsRepo + " not found)" + " Run init first or wait for init to finish !"); return; } try { configAPI(); } catch (IOException e) { e.printStackTrace(); cbCtx.error("Cordova IPFS Plugin (start): \n" + e.toString()); return; } catch (JSONException e) { e.printStackTrace(); cbCtx.error("Cordova IPFS Plugin (start): \n" + e.toString()); return; } try { StringBuilder ipfsDaemonProcOutput = new StringBuilder(); StringBuilder ipfsDaemonProcError = new StringBuilder(); String line; ipfsDaemonProcess = Runtime.getRuntime().exec( new String[]{ipfsBinPath, "daemon", "--enable-pubsub-experiment"}, new String[]{"IPFS_PATH=" + ipfsRepo} ); BufferedReader ipfsDaemonProcOutputReader = new BufferedReader(new InputStreamReader(ipfsDaemonProcess.getInputStream())); while ((line = ipfsDaemonProcOutputReader.readLine()) != null) { ipfsDaemonProcOutput.append(line).append("\n"); if (line.contains("Daemon is ready")) { cbCtx.success("Cordova IPFS Plugin (start): \n Started"); } Log.d(LOG_TAG, line); } BufferedReader ipfsDaemonProcErrorReader = new BufferedReader(new InputStreamReader(ipfsDaemonProcess.getErrorStream())); while ((line = ipfsDaemonProcErrorReader.readLine()) != null) { ipfsDaemonProcError.append(line).append("\n"); Log.d(LOG_TAG, line); } Log.d(LOG_TAG, "IPFS daemon exit val: " + ipfsDaemonProcess.waitFor()); Log.d(LOG_TAG, "IPFS daemon out : " + ipfsDaemonProcOutput.toString()); Log.d(LOG_TAG, "IPFS daemon err : " + ipfsDaemonProcError.toString()); } catch (IOException e) { e.printStackTrace(); cbCtx.error("Cordova IPFS Plugin (start): \n" + e.toString()); } catch (InterruptedException e) { e.printStackTrace(); cbCtx.error("Cordova IPFS Plugin (start): \n" + e.toString()); } } }; if (ipfsDaemonThreadFuture == null) ipfsDaemonThreadFuture = cordova.getThreadPool().submit(ipfsDaemonThread); else if (ipfsDaemonThreadFuture.isCancelled() || ipfsDaemonThreadFuture.isDone()) { ipfsDaemonThreadFuture = cordova.getThreadPool().submit(ipfsDaemonThread); } else { cbCtx.success("Cordova IPFS Plugin (start): Daemon is already running"); } } /** * 'stop' plugin function exposed to JS interface * Stops the IPFS daemon if it's running and waits for the process to exit * * @param cbCtx callback context used to call succes or error callbacks */ private void stopDaemon(final CallbackContext cbCtx) { if (this.ipfsDaemonThreadFuture != null) if (this.ipfsDaemonThreadFuture.isDone()) { Log.d(LOG_TAG, "IPFS daemon thread is STOPPED"); } else { Log.d(LOG_TAG, "IPFS daemon thread is still DAEMONING"); } if (this.ipfsDaemonProcess != null) if (this.isRunning(this.ipfsDaemonProcess)) { this.ipfsDaemonProcess.destroy(); try { cbCtx.success("Cordova IPFS Plugin (stop): Success, exit code: " + this.ipfsDaemonProcess.waitFor()); } catch (InterruptedException e) { e.printStackTrace(); cbCtx.error("Cordova IPFS Plugin (stop): \n" + e.toString()); } return; } cbCtx.success("Cordova IPFS Plugin (stop): Success"); } @Override public void initialize(CordovaInterface cordova, CordovaWebView webView) { super.initialize(cordova, webView); } @Override public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) { if (action.equals("init")) { this.init(args, callbackContext); return true; } else if (action.equals("start")) { this.startDaemon(callbackContext); return true; } else if (action.equals("stop")) { this.stopDaemon(callbackContext); return true; } return false; } }
UTF-8
Java
20,413
java
Ipfs.java
Java
[ { "context": "repo, starting / stopping the daemon\n *\n * @author xSkyripper\n */\npublic class Ipfs extends CordovaPlugin {\n ", "end": 1203, "score": 0.9996476173400879, "start": 1193, "tag": "USERNAME", "value": "xSkyripper" } ]
null
[]
package org.apache.cordova.ipfs; import android.util.Log; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaWebView; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.rauschig.jarchivelib.ArchiveFormat; import org.rauschig.jarchivelib.Archiver; import org.rauschig.jarchivelib.ArchiverFactory; import org.rauschig.jarchivelib.CompressionType; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.concurrent.Future; /** * This class extends the CordovaPlugin and provides a wrap for go-ipfs arm binaries * which can be used is Cordova projects. It consists of the basic functionalities like * downloading, extracting, initing the repo, starting / stopping the daemon * * @author xSkyripper */ public class Ipfs extends CordovaPlugin { private URL ipfsArchiveSrc; private String appFilesDir; private String ipfsBinPath; private String ipfsRepo; private Process ipfsDaemonProcess = null; private Future ipfsDaemonThreadFuture = null; private String LOG_TAG = "#######CIP######"; /** * Function for starting a system process that will "shell execute" the given command(s) * in the cmdArray, using the environment variables provided in envArray. The process will be * waited to finish * If ignoreExc is true, the error output of the command will be ignored. * * @param cmdArray the array of shell commands * @param envArray the array of environment variables * @param ignoreExc if true, the error output is ignores; else, and IOException will be thrown * @throws IOException thrown if something happens with the process or if the error output is * not ignored * @throws InterruptedException thrown if something happens on waiting the process to finish */ private void execShell(final String[] cmdArray, final String[] envArray, Boolean ignoreExc, String workingDir) throws IOException, InterruptedException { Log.d(LOG_TAG, Arrays.toString(cmdArray)); Process proc; if (workingDir != null) proc = Runtime.getRuntime().exec(cmdArray, envArray, new File(workingDir)); else proc = Runtime.getRuntime().exec(cmdArray, envArray); StringBuilder procOutput = new StringBuilder(); StringBuilder procError = new StringBuilder(); String line; BufferedReader procOutputReader = new BufferedReader(new InputStreamReader(proc.getInputStream())); while ((line = procOutputReader.readLine()) != null) { procOutput.append(line).append("\n"); Log.d(LOG_TAG, line); } BufferedReader procErrorReader = new BufferedReader(new InputStreamReader(proc.getErrorStream())); while ((line = procErrorReader.readLine()) != null) { procError.append(line).append("\n"); Log.d(LOG_TAG, line); } //Log.d(LOG_TAG, procOutput.toString()); if (!ignoreExc) if (!procError.toString().equals("")) { Log.d(LOG_TAG, "Tried:" + Arrays.toString(cmdArray)); throw new IOException(procError.toString()); } proc.waitFor(); } /** * Deletes a file or a directory recursively; if the delete returns 'false' (some file could * not be deleted), it simply logs a messages * * @param fileOrDirectory the file / dir to be deleted */ private void deleteRecursive(File fileOrDirectory) { if (fileOrDirectory.isDirectory()) for (File child : fileOrDirectory.listFiles()) deleteRecursive(child); if (!(fileOrDirectory.delete())) Log.d(LOG_TAG, "File " + fileOrDirectory.getName() + " couldn't be deleted !"); } /** * Checks if a process is running by trying to access the exitValue; if an exception is thrown * then the process is still running; otherwise, it finished running and it has an exit value * * @param process the process to be checked * @return true if the process is running; false otherwise */ private Boolean isRunning(Process process) { try { process.exitValue(); return false; } catch (Exception e) { return true; } } /** * Download the go-ipfs archive from the ipfsArchiveSrc provided at "init" * The method open the connection to the URL provided, checks if the connection * returns HTTP "200", else it throws an exception; It also checks if the archive already exists * and it has the same size as the archive existing at the URL provided; * * @throws Exception if something happens (connection couldn't be initiated, the source server * returned something else than "200", stream exceptions) */ private void downloadIpfs() throws Exception { InputStream input; OutputStream output; HttpURLConnection conn; int archiveFileLength; long totalDownloaded = 0; byte block[] = new byte[4096]; int blockSize; Log.d(LOG_TAG, "STARTING DOWNLOAD"); conn = (HttpURLConnection) ipfsArchiveSrc.openConnection(); Log.d(LOG_TAG, "OPENED CONN"); conn.connect(); Log.d(LOG_TAG, "CONNECTED TO SRC"); if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new Exception("Server returned HTTP " + conn.getResponseCode() + " " + conn.getResponseMessage()); } Log.d(LOG_TAG, "GOT 200 FROM SRC"); archiveFileLength = conn.getContentLength(); File oldArchive = new File(appFilesDir + "go-ipfs.tar.gz"); // archive exists and has the same size (TODO: HASH CHECKING) if (oldArchive.exists() && oldArchive.length() == archiveFileLength) { Log.d(LOG_TAG, "archive exists and has the same length"); return; } input = conn.getInputStream(); output = new FileOutputStream(appFilesDir + "go-ipfs.tar.gz"); int lastDownTotal = -1; while ((blockSize = input.read(block)) != -1) { totalDownloaded += blockSize; if (archiveFileLength > 0) { if (((int) (totalDownloaded * 100 / archiveFileLength)) % 10 == 0) if (((int) (totalDownloaded * 100 / archiveFileLength)) != lastDownTotal) { lastDownTotal = (int) (totalDownloaded * 100 / archiveFileLength); Log.d(LOG_TAG, "Downloaded " + lastDownTotal + "%"); } } output.write(block, 0, blockSize); } Log.d(LOG_TAG, "FINISHED DOWNLOADING"); input.close(); output.close(); conn.disconnect(); } /** * Extracts the archive downloaded by downloadIpfs using the custom jar included in the project * to the same directory, tries to make the binary executable and * finally deletes the archive for "space reasons" * * @throws Exception an exception is thrown if the IPFS binary couldn't be made executable */ private void extractIpfs() throws Exception { Log.d(LOG_TAG, "STARTING EXTRACT"); Archiver archiver = ArchiverFactory.createArchiver(ArchiveFormat.TAR, CompressionType.GZIP); archiver.extract(new File(appFilesDir + "go-ipfs.tar.gz"), new File(appFilesDir)); if (!(new File(ipfsBinPath).setExecutable(true, true))) { throw new Exception("IPFS Bin " + ipfsBinPath + " cannot be set executable !"); } this.deleteRecursive(new File(appFilesDir + "go-ipfs.tar.gz")); Log.d(LOG_TAG, "FINISHED EXTRACT"); } /** * Calls the 2 methods that "prepare" go-ipfs ARM: downloadIpfs and extractIpfs * * @throws Exception exceptions are re-thrown from these 2 functions */ private void prepareIpfs() throws Exception { this.downloadIpfs(); this.extractIpfs(); } /** * Reads the IPFS config file and adds the next permissions on HTTPHeaders for API connections * API.HTTPHeaders.Access-Control-Allow-Origin "[\"*\"]" * API.HTTPHeaders.Access-Control-Allow-Credentials "[\"true\"]" * * @throws IOException if the config file doesn't exist or other problem * @throws JSONException if the json data cannot be parse or other problem */ private void configAPI() throws IOException, JSONException { int num; char[] buffer = new char[1024]; BufferedReader input; StringBuilder content = new StringBuilder(); input = new BufferedReader( new InputStreamReader( new FileInputStream(ipfsRepo + "config") ) ); while ((num = input.read(buffer)) > 0) { content.append(buffer, 0, num); } JSONObject jsonConfig = new JSONObject(content.toString()); jsonConfig.getJSONObject("API").put("HTTPHeaders", new JSONObject("{" + "\"Access-Control-Allow-Credentials\": [" + "\"true\"" + "]," + "\"Access-Control-Allow-Origin\": [" + "\"*\"" + "]" + "}")); input.close(); FileWriter file = new FileWriter(ipfsRepo + "config"); file.write(jsonConfig.toString(4)); file.close(); Log.d(LOG_TAG, "FINISHED CONFIGING FOR API !"); } /** * Deletes the current IPFS Repo folder and tries to recreate it using "ipfs init" exec shell * taking into account possible errors on initing * * @throws Exception thrown by exec shell ('ipfs init') if something happens during initialization */ private void initRepo() throws Exception { Log.d(LOG_TAG, "INITING IF REPO RESET OR REPO NOT EXISTS"); this.deleteRecursive(new File(ipfsRepo)); this.execShell( new String[]{ipfsBinPath, "init"}, new String[]{"IPFS_PATH=" + this.ipfsRepo}, false, null); Log.d(LOG_TAG, "INITING FINISHED"); } /** * 'init' plugin function exposed to JS interface, ran asynchronously * Parses the arguments provided, saves them. builds the path of the repo and the binary * and tries to prepare the IPF if the binary doesn't exist * and to init the repo if the IPFS repo dir doesn't exists or if resetRepo option is 'true' * * @param args JSONArray arguments provided from the call; expected to find * 'appFilesDir' the path to the app's files/files dir, * 'src' the URL of the go-ipfs ARM tar.gz archive * 'resetRepo' boolean used for reseting the repo * @param cbCtx callback context used to call succes or error callbacks */ private void init(final JSONArray args, final CallbackContext cbCtx) { final Runnable initAsync = new Runnable() { @Override public void run() { Boolean resetRepo; try { JSONObject config = args.getJSONObject(0); appFilesDir = config.getString("appFilesDir"); ipfsArchiveSrc = new URL(config.getString("src")); ipfsBinPath = appFilesDir.concat("go-ipfs/ipfs"); ipfsRepo = appFilesDir.concat(".ipfs/"); resetRepo = config.getBoolean("resetRepo"); Log.d(LOG_TAG, "ipfsBinPath: " + ipfsBinPath); Log.d(LOG_TAG, "ipfsArchiveSrc: " + ipfsArchiveSrc); Log.d(LOG_TAG, "appFilesDir: " + appFilesDir); Log.d(LOG_TAG, "ipfsRepo: " + ipfsRepo); Log.d(LOG_TAG, "resetRepo: " + resetRepo); } catch (JSONException e) { e.printStackTrace(); cbCtx.error("Cordova IPFS Plugin (init): \n" + e.toString()); return; } catch (MalformedURLException e) { e.printStackTrace(); cbCtx.error("Cordova IPFS Plugin (init): \n" + e.toString()); return; } if (!(new File(ipfsBinPath).exists())) try { prepareIpfs(); } catch (Exception e) { e.printStackTrace(); cbCtx.error("Cordova IPFS Plugin (init): \n" + e.toString()); return; } if (resetRepo || !(new File(ipfsRepo).exists())) try { initRepo(); } catch (IOException e) { e.printStackTrace(); cbCtx.error("Cordova IPFS Plugin (init): \n" + e.toString()); return; } catch (InterruptedException e) { e.printStackTrace(); cbCtx.error("Cordova IPFS Plugin (init): \n" + e.toString()); return; } catch (Exception e) { e.printStackTrace(); cbCtx.error("Cordova IPFS Plugin (init): \n" + e.toString()); return; } cbCtx.success("Cordova IPFS Plugin (init): IPFS was prepared & inited !"); } }; cordova.getThreadPool().execute(initAsync); } /** * 'start' plugin function exposed to JS interface, ran asynchronously * Checks if the IPFS binary and the IPFS repo dir exist, throwing an error of they don't * Tries to set through exec shell the IPFS config access control * Starts the IPFS daemon with 'pubsub' in a new process * contained by a thread if it's not already running and sets the local Future of the thread * * @param cbCtx callback context used to call success or error callbacks */ private void startDaemon(final CallbackContext cbCtx) { //> ipfs config --json API.HTTPHeaders.Access-Control-Allow-Credentials "[\"true\"]" //> ipfs config --json API.HTTPHeaders.Access-Control-Allow-Origin "[\"*\"]" final Runnable ipfsDaemonThread = new Runnable() { @Override public void run() { if (!(new File(ipfsBinPath).exists())) { cbCtx.error("Cordova IPFS Plugin (start): \n" + "The IPFS was not prepared (binary not found)" + " Run init first or wait for init to finish !"); return; } if (!(new File(ipfsRepo).exists())) { cbCtx.error("Cordova IPFS Plugin (start): \n" + "The IPFS repo was not initialized (" + ipfsRepo + " not found)" + " Run init first or wait for init to finish !"); return; } try { configAPI(); } catch (IOException e) { e.printStackTrace(); cbCtx.error("Cordova IPFS Plugin (start): \n" + e.toString()); return; } catch (JSONException e) { e.printStackTrace(); cbCtx.error("Cordova IPFS Plugin (start): \n" + e.toString()); return; } try { StringBuilder ipfsDaemonProcOutput = new StringBuilder(); StringBuilder ipfsDaemonProcError = new StringBuilder(); String line; ipfsDaemonProcess = Runtime.getRuntime().exec( new String[]{ipfsBinPath, "daemon", "--enable-pubsub-experiment"}, new String[]{"IPFS_PATH=" + ipfsRepo} ); BufferedReader ipfsDaemonProcOutputReader = new BufferedReader(new InputStreamReader(ipfsDaemonProcess.getInputStream())); while ((line = ipfsDaemonProcOutputReader.readLine()) != null) { ipfsDaemonProcOutput.append(line).append("\n"); if (line.contains("Daemon is ready")) { cbCtx.success("Cordova IPFS Plugin (start): \n Started"); } Log.d(LOG_TAG, line); } BufferedReader ipfsDaemonProcErrorReader = new BufferedReader(new InputStreamReader(ipfsDaemonProcess.getErrorStream())); while ((line = ipfsDaemonProcErrorReader.readLine()) != null) { ipfsDaemonProcError.append(line).append("\n"); Log.d(LOG_TAG, line); } Log.d(LOG_TAG, "IPFS daemon exit val: " + ipfsDaemonProcess.waitFor()); Log.d(LOG_TAG, "IPFS daemon out : " + ipfsDaemonProcOutput.toString()); Log.d(LOG_TAG, "IPFS daemon err : " + ipfsDaemonProcError.toString()); } catch (IOException e) { e.printStackTrace(); cbCtx.error("Cordova IPFS Plugin (start): \n" + e.toString()); } catch (InterruptedException e) { e.printStackTrace(); cbCtx.error("Cordova IPFS Plugin (start): \n" + e.toString()); } } }; if (ipfsDaemonThreadFuture == null) ipfsDaemonThreadFuture = cordova.getThreadPool().submit(ipfsDaemonThread); else if (ipfsDaemonThreadFuture.isCancelled() || ipfsDaemonThreadFuture.isDone()) { ipfsDaemonThreadFuture = cordova.getThreadPool().submit(ipfsDaemonThread); } else { cbCtx.success("Cordova IPFS Plugin (start): Daemon is already running"); } } /** * 'stop' plugin function exposed to JS interface * Stops the IPFS daemon if it's running and waits for the process to exit * * @param cbCtx callback context used to call succes or error callbacks */ private void stopDaemon(final CallbackContext cbCtx) { if (this.ipfsDaemonThreadFuture != null) if (this.ipfsDaemonThreadFuture.isDone()) { Log.d(LOG_TAG, "IPFS daemon thread is STOPPED"); } else { Log.d(LOG_TAG, "IPFS daemon thread is still DAEMONING"); } if (this.ipfsDaemonProcess != null) if (this.isRunning(this.ipfsDaemonProcess)) { this.ipfsDaemonProcess.destroy(); try { cbCtx.success("Cordova IPFS Plugin (stop): Success, exit code: " + this.ipfsDaemonProcess.waitFor()); } catch (InterruptedException e) { e.printStackTrace(); cbCtx.error("Cordova IPFS Plugin (stop): \n" + e.toString()); } return; } cbCtx.success("Cordova IPFS Plugin (stop): Success"); } @Override public void initialize(CordovaInterface cordova, CordovaWebView webView) { super.initialize(cordova, webView); } @Override public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) { if (action.equals("init")) { this.init(args, callbackContext); return true; } else if (action.equals("start")) { this.startDaemon(callbackContext); return true; } else if (action.equals("stop")) { this.stopDaemon(callbackContext); return true; } return false; } }
20,413
0.573066
0.571107
508
39.183071
31.415176
157
false
false
0
0
0
0
0
0
0.562992
false
false
14
eefd831d964847f6b132ca3886a94f4162025649
15,564,961,513,291
4526c200a8a4c5c85c8eb8554048362953838924
/CMS-09/src/cms/backend/dao/impl/ChannelDaoForIBatisImpl.java
69f54d8ae6ccb07d84bb3b9bb088dd260c6b88e2
[]
no_license
hbwy/Projects
https://github.com/hbwy/Projects
3ba6d45b708b5f3260bb6c62d03f5c96bac31151
f4733beed29880bb7e57b0241cb887a5dcad62f5
refs/heads/master
2021-01-10T11:36:50.195000
2015-08-30T13:26:03
2015-08-30T13:26:03
36,266,352
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cms.backend.dao.impl; import java.util.ArrayList; import java.util.List; import org.apache.ibatis.session.SqlSession; import cms.backend.dao.ChannelDao; import cms.model.Channel; import cms.utils.IDB; public class ChannelDaoForIBatisImpl implements ChannelDao { //添加 public void save(Channel c) { SqlSession session = IDB.getSession(); try { session.insert(Channel.class.getName()+".save", c); session.commit(); } catch (Exception e) { session.rollback(); e.printStackTrace(); }finally{ session.close(); } } //更新 public void update(Channel c) { SqlSession session = IDB.getSession(); try { session.update(Channel.class.getName()+".update", c); session.commit(); } catch (Exception e) { session.rollback(); e.printStackTrace(); }finally{ session.close(); } } //删除 public void delete(String id) { SqlSession session = IDB.getSession(); try { session.delete(Channel.class.getName()+".delete",id); session.delete(Channel.class.getName()+".deleteArticle",id); session.commit(); } catch (Exception e) { session.rollback(); e.printStackTrace(); }finally{ session.close(); } } //多查 public List<Channel> query() { SqlSession session = IDB.getSession(); List channels = new ArrayList(); try { channels = session.selectList(Channel.class.getName()+".query"); } catch (Exception e) { e.printStackTrace(); }finally{ session.close(); } return channels; } //单查 public Channel get(String id) { SqlSession session = IDB.getSession(); Channel channel = null; try { channel = (Channel)session.selectOne(Channel.class.getName()+".get",id); } catch (Exception e) { e.printStackTrace(); }finally{ session.close(); } return channel; } }
GB18030
Java
1,791
java
ChannelDaoForIBatisImpl.java
Java
[]
null
[]
package cms.backend.dao.impl; import java.util.ArrayList; import java.util.List; import org.apache.ibatis.session.SqlSession; import cms.backend.dao.ChannelDao; import cms.model.Channel; import cms.utils.IDB; public class ChannelDaoForIBatisImpl implements ChannelDao { //添加 public void save(Channel c) { SqlSession session = IDB.getSession(); try { session.insert(Channel.class.getName()+".save", c); session.commit(); } catch (Exception e) { session.rollback(); e.printStackTrace(); }finally{ session.close(); } } //更新 public void update(Channel c) { SqlSession session = IDB.getSession(); try { session.update(Channel.class.getName()+".update", c); session.commit(); } catch (Exception e) { session.rollback(); e.printStackTrace(); }finally{ session.close(); } } //删除 public void delete(String id) { SqlSession session = IDB.getSession(); try { session.delete(Channel.class.getName()+".delete",id); session.delete(Channel.class.getName()+".deleteArticle",id); session.commit(); } catch (Exception e) { session.rollback(); e.printStackTrace(); }finally{ session.close(); } } //多查 public List<Channel> query() { SqlSession session = IDB.getSession(); List channels = new ArrayList(); try { channels = session.selectList(Channel.class.getName()+".query"); } catch (Exception e) { e.printStackTrace(); }finally{ session.close(); } return channels; } //单查 public Channel get(String id) { SqlSession session = IDB.getSession(); Channel channel = null; try { channel = (Channel)session.selectOne(Channel.class.getName()+".get",id); } catch (Exception e) { e.printStackTrace(); }finally{ session.close(); } return channel; } }
1,791
0.668549
0.668549
84
20.083334
17.524954
75
false
false
0
0
0
0
0
0
2.178571
false
false
14
da1fa316632bb08040211285a2120bfe96698de8
2,044,404,440,761
b808aff50c6274381be22404d9cfe296f3751bea
/polarbrowser/src/main/java/com/polar/business/search/view/SearchResultView.java
c3ca69686a405d92af6479d55417003699934c41
[]
no_license
luzhentao/polar
https://github.com/luzhentao/polar
4dbf0d6a46f4e0fcf708018160d2ee90712f0c46
fd4f044e38acfe1e2b8e10b0f52e5d65f8206399
refs/heads/master
2020-04-12T12:59:26.529000
2017-09-04T09:22:25
2017-09-04T09:22:25
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.polar.business.search.view; import android.annotation.SuppressLint; import android.content.Context; import android.text.TextUtils; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.AbsListView; import android.widget.ListView; import android.widget.RelativeLayout; import com.polar.browser.R; import com.polar.browser.history.IHistoryItemClick; import com.polar.browser.history.ISearchResultNotifyHindeIM; import com.polar.browser.i.IHideIMListener; import com.polar.browser.manager.ThreadManager; import com.polar.browser.utils.SimpleLog; import com.polar.business.search.ISuggestCallBack; import com.polar.business.search.ISuggestUrl; import com.polar.business.search.SuggestTask2; import com.polar.business.search.adapter.RecommendAdapter; import com.polar.business.search.dao.RecommendInfo; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class SearchResultView extends RelativeLayout { private static final String TAG = "SearchResultView"; /** * 下半部分搜索结果,ListView --》 推荐网址 **/ private ListView mLvPart2; private LayoutInflater mInflater; private RecommendAdapter mAdapter; private IHistoryItemClick mClickDelegate; private ISuggestUrl mSuggestUrlDelegate; private ISearchResultNotifyHindeIM mSearchResultNotifyHindeIM; /** * 输入框输入要查询的关键字 **/ private String mKey; /** * 2、搜索推荐网址列表(C++) **/ private Runnable mSuggestTask2; /** * 推荐网址列表结果回调 **/ private ISuggestCallBack callBack2 = new ISuggestCallBack() { @Override public void callBack(final String result) { ThreadManager.getUIHandler().post(new Runnable() { @Override public void run() { if (!TextUtils.isEmpty(result) && !TextUtils.isEmpty(mKey)) { handleSuggestResult2(result); } else { SearchResultView.this.initDataPart2(null); } } }); } }; private boolean headerIsAdded; public SearchResultView(Context context) { this(context, null); } public SearchResultView(Context context, AttributeSet attrs) { super(context, attrs); mInflater = LayoutInflater.from(context); initView(); initData(); } @SuppressLint("InflateParams") private void initView() { mInflater.inflate(R.layout.view_search_result, this); mLvPart2 = (ListView) findViewById(R.id.lv_result_part2); mLvPart2.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { mSearchResultNotifyHindeIM.onNotifyHindeIM(); } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { } }); } private void initData() { mAdapter = new RecommendAdapter(getContext()); } /** * 注册下半部分数据中条目点的击事件处理 * * @param delegate */ public void registerDelegate(IHistoryItemClick delegate, ISuggestUrl urlDelegate, ISearchResultNotifyHindeIM searchResultNotifyHindeIM) { mClickDelegate = delegate; mSuggestUrlDelegate = urlDelegate; this.mSearchResultNotifyHindeIM = searchResultNotifyHindeIM; mAdapter.registerDelegate(mClickDelegate, mSuggestUrlDelegate); } /** * 设置点击键盘消失的监听 * * @param hideIMListener */ public void setHideImListener(IHideIMListener hideIMListener) { // if (mLvPart2 instanceof HideIMListView) { // ((HideIMListView) mLvPart2).setHideImListener(hideIMListener); // } } /** * 初始化下半部分数据 网址。。 */ private void initDataPart2(List<RecommendInfo> datasPart2) { if (datasPart2 == null) { datasPart2 = new ArrayList<RecommendInfo>(); // mLvPart2.setVisibility(View.GONE); } mAdapter.setKey(mKey); mAdapter.updateData(datasPart2); } public void clearResults() { mKey = null; if (mSuggestTask2 != null) { ThreadManager.getLogicHandler().removeCallbacks(mSuggestTask2); } this.initDataPart2(null); } /** * 输入框文字更改时, * 1、请求搜索推荐词 * 2、访问C++ 推荐列表 * * @param key */ public void handleTextChange(String key, boolean isUrl) { mKey = key; if (TextUtils.isEmpty(mKey)) { return; } if (mKey.length() > 2048) { mKey = mKey.substring(0, 50); } // 第二部分数据 if (mSuggestTask2 != null) { ThreadManager.getLogicHandler().removeCallbacks(mSuggestTask2); } mSuggestTask2 = new SuggestTask2(mKey, callBack2); ThreadManager.getLogicHandler().postDelayed(mSuggestTask2, 200); } /** * data part 2 * * @param result */ private void handleSuggestResult2(String result) { // 推荐列表2 //[{"title":"tieba.baidu.com","url":"http%3A%2F%2Ftieba.baidu.com%2F"}, //{"title":"爱奇艺-爱奇艺视频,高清影视剧,网络视频在线观看","url":"http://m.iqiyi.com/"}, //{"title":"手机环球网","url":"http://wap.huanqiu.com/"}, //{"title":"手机网易网","url":"http://3g.163.com/touch/"}] SimpleLog.d(TAG, "Result2 = " + result); JSONArray jsonArray; List<RecommendInfo> infos = new ArrayList<RecommendInfo>(); try { jsonArray = new JSONArray(result); for (int i = 0; i < jsonArray.length(); i++) { JSONObject item = jsonArray.getJSONObject(i); String title = item.getString("title"); String url = item.getString("url"); RecommendInfo info = new RecommendInfo(); info.title = title; info.url = url; infos.add(info); } } catch (JSONException e) { SimpleLog.e(e); } this.initDataPart2(infos); this.setVisibility(View.VISIBLE); } /** * 把搜索建议 添加到历史记录 listView header */ public void addSearchRecommendHeader(View view ) { if(!headerIsAdded){ mLvPart2.addHeaderView(view); headerIsAdded = true; } mLvPart2.setAdapter(mAdapter); } public void removeSearchRecommendHeader(View view ) { mLvPart2.removeHeaderView(view); headerIsAdded = false; } }
UTF-8
Java
6,067
java
SearchResultView.java
Java
[]
null
[]
package com.polar.business.search.view; import android.annotation.SuppressLint; import android.content.Context; import android.text.TextUtils; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.AbsListView; import android.widget.ListView; import android.widget.RelativeLayout; import com.polar.browser.R; import com.polar.browser.history.IHistoryItemClick; import com.polar.browser.history.ISearchResultNotifyHindeIM; import com.polar.browser.i.IHideIMListener; import com.polar.browser.manager.ThreadManager; import com.polar.browser.utils.SimpleLog; import com.polar.business.search.ISuggestCallBack; import com.polar.business.search.ISuggestUrl; import com.polar.business.search.SuggestTask2; import com.polar.business.search.adapter.RecommendAdapter; import com.polar.business.search.dao.RecommendInfo; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class SearchResultView extends RelativeLayout { private static final String TAG = "SearchResultView"; /** * 下半部分搜索结果,ListView --》 推荐网址 **/ private ListView mLvPart2; private LayoutInflater mInflater; private RecommendAdapter mAdapter; private IHistoryItemClick mClickDelegate; private ISuggestUrl mSuggestUrlDelegate; private ISearchResultNotifyHindeIM mSearchResultNotifyHindeIM; /** * 输入框输入要查询的关键字 **/ private String mKey; /** * 2、搜索推荐网址列表(C++) **/ private Runnable mSuggestTask2; /** * 推荐网址列表结果回调 **/ private ISuggestCallBack callBack2 = new ISuggestCallBack() { @Override public void callBack(final String result) { ThreadManager.getUIHandler().post(new Runnable() { @Override public void run() { if (!TextUtils.isEmpty(result) && !TextUtils.isEmpty(mKey)) { handleSuggestResult2(result); } else { SearchResultView.this.initDataPart2(null); } } }); } }; private boolean headerIsAdded; public SearchResultView(Context context) { this(context, null); } public SearchResultView(Context context, AttributeSet attrs) { super(context, attrs); mInflater = LayoutInflater.from(context); initView(); initData(); } @SuppressLint("InflateParams") private void initView() { mInflater.inflate(R.layout.view_search_result, this); mLvPart2 = (ListView) findViewById(R.id.lv_result_part2); mLvPart2.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { mSearchResultNotifyHindeIM.onNotifyHindeIM(); } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { } }); } private void initData() { mAdapter = new RecommendAdapter(getContext()); } /** * 注册下半部分数据中条目点的击事件处理 * * @param delegate */ public void registerDelegate(IHistoryItemClick delegate, ISuggestUrl urlDelegate, ISearchResultNotifyHindeIM searchResultNotifyHindeIM) { mClickDelegate = delegate; mSuggestUrlDelegate = urlDelegate; this.mSearchResultNotifyHindeIM = searchResultNotifyHindeIM; mAdapter.registerDelegate(mClickDelegate, mSuggestUrlDelegate); } /** * 设置点击键盘消失的监听 * * @param hideIMListener */ public void setHideImListener(IHideIMListener hideIMListener) { // if (mLvPart2 instanceof HideIMListView) { // ((HideIMListView) mLvPart2).setHideImListener(hideIMListener); // } } /** * 初始化下半部分数据 网址。。 */ private void initDataPart2(List<RecommendInfo> datasPart2) { if (datasPart2 == null) { datasPart2 = new ArrayList<RecommendInfo>(); // mLvPart2.setVisibility(View.GONE); } mAdapter.setKey(mKey); mAdapter.updateData(datasPart2); } public void clearResults() { mKey = null; if (mSuggestTask2 != null) { ThreadManager.getLogicHandler().removeCallbacks(mSuggestTask2); } this.initDataPart2(null); } /** * 输入框文字更改时, * 1、请求搜索推荐词 * 2、访问C++ 推荐列表 * * @param key */ public void handleTextChange(String key, boolean isUrl) { mKey = key; if (TextUtils.isEmpty(mKey)) { return; } if (mKey.length() > 2048) { mKey = mKey.substring(0, 50); } // 第二部分数据 if (mSuggestTask2 != null) { ThreadManager.getLogicHandler().removeCallbacks(mSuggestTask2); } mSuggestTask2 = new SuggestTask2(mKey, callBack2); ThreadManager.getLogicHandler().postDelayed(mSuggestTask2, 200); } /** * data part 2 * * @param result */ private void handleSuggestResult2(String result) { // 推荐列表2 //[{"title":"tieba.baidu.com","url":"http%3A%2F%2Ftieba.baidu.com%2F"}, //{"title":"爱奇艺-爱奇艺视频,高清影视剧,网络视频在线观看","url":"http://m.iqiyi.com/"}, //{"title":"手机环球网","url":"http://wap.huanqiu.com/"}, //{"title":"手机网易网","url":"http://3g.163.com/touch/"}] SimpleLog.d(TAG, "Result2 = " + result); JSONArray jsonArray; List<RecommendInfo> infos = new ArrayList<RecommendInfo>(); try { jsonArray = new JSONArray(result); for (int i = 0; i < jsonArray.length(); i++) { JSONObject item = jsonArray.getJSONObject(i); String title = item.getString("title"); String url = item.getString("url"); RecommendInfo info = new RecommendInfo(); info.title = title; info.url = url; infos.add(info); } } catch (JSONException e) { SimpleLog.e(e); } this.initDataPart2(infos); this.setVisibility(View.VISIBLE); } /** * 把搜索建议 添加到历史记录 listView header */ public void addSearchRecommendHeader(View view ) { if(!headerIsAdded){ mLvPart2.addHeaderView(view); headerIsAdded = true; } mLvPart2.setAdapter(mAdapter); } public void removeSearchRecommendHeader(View view ) { mLvPart2.removeHeaderView(view); headerIsAdded = false; } }
6,067
0.723297
0.713539
228
24.171053
23.025379
138
false
false
0
0
0
0
0
0
1.907895
false
false
14
329ff0f62a8a88b0ea60d7795b6f3e9f2dbe48bd
274,877,940,740
4c5315e79e9087adf6bc26196ce1187d9e9791e7
/gwt4ext/src/com/ait/ext4j/client/resizer/Resizer.java
b571d8d2b9369e0421136179e62ece54fe6cc773
[]
no_license
thiagoteixeira/ext4j
https://github.com/thiagoteixeira/ext4j
3082fc31ee00a7158c430cd1a616ef228b997cdd
ee8b691191454875f9457d376c72fd39a335145a
refs/heads/master
2021-01-18T11:09:22.759000
2014-02-22T21:34:21
2014-02-22T21:34:21
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Ext4j UI Library Copyright 2014, Alain Ekambi, and individual contributors as * indicated by the @authors tag. See the copyright.txt in the distribution for * a full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.ait.ext4j.client.resizer; import com.ait.ext4j.client.core.Component; import com.ait.ext4j.client.core.ExtElement; import com.ait.ext4j.client.core.ObservableJso; import com.ait.ext4j.client.events.resizer.BeforeResizeHandler; import com.ait.ext4j.client.events.resizer.ResizeHandler; import com.google.gwt.core.client.JavaScriptObject; public class Resizer extends ObservableJso { private Resizer(ResizerConfig config) { jsObj = createNativePeer(config.getJsObj()); } public static Resizer create(ResizerConfig config) { return new Resizer(config); } protected Resizer(JavaScriptObject obj) { jsObj = obj; } /** * Returns the element that was configured with the el or target config * property. If a component was configured with the target property then * this will return the element of this component. * <p> * Textarea and img elements will be wrapped with an additional div because * these elements do not support child nodes. The original element can be * accessed through the originalTarget property. */ public native ExtElement getEl()/*-{ var obj = this.@com.ait.ext4j.client.core.JsObject::getJsObj()(); var peer = obj.getEl(); return @com.ait.ext4j.client.core.ExtElement::new(Lcom/google/gwt/core/client/JavaScriptObject;)(peer); }-*/; /** * Returns the element or component that was configured with the target * config property. * <p> * Textarea and img elements will be wrapped with an additional div because * these elements do not support child nodes. The original element can be * accessed through the originalTarget property. */ public native ExtElement getTargetElement()/*-{ var obj = this.@com.ait.ext4j.client.core.JsObject::getJsObj()(); var peer = obj.getTarget(); return @com.ait.ext4j.client.core.ExtElement::new(Lcom/google/gwt/core/client/JavaScriptObject;)(peer); }-*/; /** * Returns the element or component that was configured with the target * config property. * <p> * Textarea and img elements will be wrapped with an additional div because * these elements do not support child nodes. The original element can be * accessed through the originalTarget property. */ public native Component getTarget()/*-{ var obj = this.@com.ait.ext4j.client.core.JsObject::getJsObj()(); var peer = obj.getTarget(); return @com.ait.ext4j.client.core.Component::createComponent(Lcom/google/gwt/core/client/JavaScriptObject;)(peer); }-*/; /** * Perform a manual resize and fires the 'resize' event. */ public native void resizeTo(double width, double height)/*-{ var obj = this.@com.ait.ext4j.client.core.JsObject::getJsObj()(); obj.resizeTo(width, height); }-*/; /** * Use this handler to listen to the resize and resize drag event */ public native void addHandler(String event, ResizeHandler handler)/*-{ var obj = this.@com.ait.ext4j.client.core.JsObject::getJsObj()(); obj .addListener( event, $entry(function(r, w, h, e) { var resizer = @com.ait.ext4j.client.resizer.Resizer::new(Lcom/google/gwt/core/client/JavaScriptObject;)(r); var event = @com.ait.ext4j.client.core.EventObject::new(Lcom/google/gwt/core/client/JavaScriptObject;)(e); handler.@com.ait.ext4j.client.events.resizer.ResizeHandler::onEvent(Lcom/ait/ext4j/client/resizer/Resizer;DDLcom/ait/ext4j/client/core/EventObject;)(resizer,w,h,event); })); }-*/; /** * Fired before resize is allowed. Return false to cancel resize. */ public native void addBeforeResizeHandler(BeforeResizeHandler handler)/*-{ var obj = this.@com.ait.ext4j.client.core.JsObject::getJsObj()(); obj .addListener( @com.ait.ext4j.client.events.Event::BEFORE_RESIZE, $entry(function(r, w, h, e) { var resizer = @com.ait.ext4j.client.resizer.Resizer::new(Lcom/google/gwt/core/client/JavaScriptObject;)(r); var event = @com.ait.ext4j.client.core.EventObject::new(Lcom/google/gwt/core/client/JavaScriptObject;)(e); return handler.@com.ait.ext4j.client.events.resizer.BeforeResizeHandler::onEvent(Lcom/ait/ext4j/client/resizer/Resizer;DDLcom/ait/ext4j/client/core/EventObject;)(resizer,w,h,event); })); }-*/; private static native JavaScriptObject createNativePeer(JavaScriptObject config)/*-{ return new $wnd.Ext.resizer.Resizer(config); }-*/; }
UTF-8
Java
5,278
java
Resizer.java
Java
[ { "context": "/**\n * Ext4j UI Library Copyright 2014, Alain Ekambi, and individual contributors as\n * indicated by t", "end": 52, "score": 0.9998710751533508, "start": 40, "tag": "NAME", "value": "Alain Ekambi" }, { "context": "ore/client/JavaScriptObject;)(e);\n\t\t\t\t\t\t\thandler.@com.ait.ext4j.client.events.resizer.ResizeHandler::onEvent(Lcom/ait/ext", "end": 4177, "score": 0.8451871871948242, "start": 4157, "tag": "EMAIL", "value": "com.ait.ext4j.client" }, { "context": "reResizeHandler handler)/*-{\n\t\tvar obj = this.@com.ait.ext4j.client.core.JsObject::getJsObj()();\n\t\tobj\n\t", "end": 4529, "score": 0.6032170057296753, "start": 4526, "tag": "EMAIL", "value": "ait" }, { "context": "ent/JavaScriptObject;)(e);\n\t\t\t\t\t\t\treturn handler.@com.ait.ext4j.client.events.resizer.BeforeResizeHandler::onEvent(Lcom/a", "end": 4961, "score": 0.7757259607315063, "start": 4941, "tag": "EMAIL", "value": "com.ait.ext4j.client" }, { "context": "\t\t\t\t\t\t\treturn handler.@com.ait.ext4j.client.events.resizer.BeforeResizeHandler::onEvent(Lcom/ait/ext4", "end": 4968, "score": 0.515112578868866, "start": 4968, "tag": "EMAIL", "value": "" } ]
null
[]
/** * Ext4j UI Library Copyright 2014, <NAME>, and individual contributors as * indicated by the @authors tag. See the copyright.txt in the distribution for * a full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.ait.ext4j.client.resizer; import com.ait.ext4j.client.core.Component; import com.ait.ext4j.client.core.ExtElement; import com.ait.ext4j.client.core.ObservableJso; import com.ait.ext4j.client.events.resizer.BeforeResizeHandler; import com.ait.ext4j.client.events.resizer.ResizeHandler; import com.google.gwt.core.client.JavaScriptObject; public class Resizer extends ObservableJso { private Resizer(ResizerConfig config) { jsObj = createNativePeer(config.getJsObj()); } public static Resizer create(ResizerConfig config) { return new Resizer(config); } protected Resizer(JavaScriptObject obj) { jsObj = obj; } /** * Returns the element that was configured with the el or target config * property. If a component was configured with the target property then * this will return the element of this component. * <p> * Textarea and img elements will be wrapped with an additional div because * these elements do not support child nodes. The original element can be * accessed through the originalTarget property. */ public native ExtElement getEl()/*-{ var obj = this.@com.ait.ext4j.client.core.JsObject::getJsObj()(); var peer = obj.getEl(); return @com.ait.ext4j.client.core.ExtElement::new(Lcom/google/gwt/core/client/JavaScriptObject;)(peer); }-*/; /** * Returns the element or component that was configured with the target * config property. * <p> * Textarea and img elements will be wrapped with an additional div because * these elements do not support child nodes. The original element can be * accessed through the originalTarget property. */ public native ExtElement getTargetElement()/*-{ var obj = this.@com.ait.ext4j.client.core.JsObject::getJsObj()(); var peer = obj.getTarget(); return @com.ait.ext4j.client.core.ExtElement::new(Lcom/google/gwt/core/client/JavaScriptObject;)(peer); }-*/; /** * Returns the element or component that was configured with the target * config property. * <p> * Textarea and img elements will be wrapped with an additional div because * these elements do not support child nodes. The original element can be * accessed through the originalTarget property. */ public native Component getTarget()/*-{ var obj = this.@com.ait.ext4j.client.core.JsObject::getJsObj()(); var peer = obj.getTarget(); return @com.ait.ext4j.client.core.Component::createComponent(Lcom/google/gwt/core/client/JavaScriptObject;)(peer); }-*/; /** * Perform a manual resize and fires the 'resize' event. */ public native void resizeTo(double width, double height)/*-{ var obj = this.@com.ait.ext4j.client.core.JsObject::getJsObj()(); obj.resizeTo(width, height); }-*/; /** * Use this handler to listen to the resize and resize drag event */ public native void addHandler(String event, ResizeHandler handler)/*-{ var obj = this.@com.ait.ext4j.client.core.JsObject::getJsObj()(); obj .addListener( event, $entry(function(r, w, h, e) { var resizer = @com.ait.ext4j.client.resizer.Resizer::new(Lcom/google/gwt/core/client/JavaScriptObject;)(r); var event = @com.ait.ext4j.client.core.EventObject::new(Lcom/google/gwt/core/client/JavaScriptObject;)(e); handler.@<EMAIL>.events.resizer.ResizeHandler::onEvent(Lcom/ait/ext4j/client/resizer/Resizer;DDLcom/ait/ext4j/client/core/EventObject;)(resizer,w,h,event); })); }-*/; /** * Fired before resize is allowed. Return false to cancel resize. */ public native void addBeforeResizeHandler(BeforeResizeHandler handler)/*-{ var obj = this.@com.ait.ext4j.client.core.JsObject::getJsObj()(); obj .addListener( @com.ait.ext4j.client.events.Event::BEFORE_RESIZE, $entry(function(r, w, h, e) { var resizer = @com.ait.ext4j.client.resizer.Resizer::new(Lcom/google/gwt/core/client/JavaScriptObject;)(r); var event = @com.ait.ext4j.client.core.EventObject::new(Lcom/google/gwt/core/client/JavaScriptObject;)(e); return handler.@<EMAIL>.events.resizer.BeforeResizeHandler::onEvent(Lcom/ait/ext4j/client/resizer/Resizer;DDLcom/ait/ext4j/client/core/EventObject;)(resizer,w,h,event); })); }-*/; private static native JavaScriptObject createNativePeer(JavaScriptObject config)/*-{ return new $wnd.Ext.resizer.Resizer(config); }-*/; }
5,246
0.70576
0.699128
126
40.888889
37.733658
188
false
false
0
0
0
0
0
0
1.52381
false
false
14
0d6c477dd49d67164a76cc216f963f914859460f
10,179,072,515,136
5cbad1a9741e70db54a94c1a0a1ef0952a26d75e
/src/main/java/parkinglot2/Floor.java
f4e0310b2ad2dfe27bc5344fed1ebb3dfdfd0533
[]
no_license
shubham-v/object-oriented-design
https://github.com/shubham-v/object-oriented-design
9943339c7386f4b2f997636cacd72127c8e076d0
9d25ec2e94538f15123102b7667f451990ecb716
refs/heads/main
2023-06-21T01:15:16.037000
2023-01-07T12:48:38
2023-01-07T12:48:38
298,317,966
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package parkinglot2; import java.util.Set; public class Floor { int floorNumber; boolean isFull; Set<Space> spaces; DisplayBoard displayboard; Lot lot; public void addSpace(Space space) {} }
UTF-8
Java
221
java
Floor.java
Java
[]
null
[]
package parkinglot2; import java.util.Set; public class Floor { int floorNumber; boolean isFull; Set<Space> spaces; DisplayBoard displayboard; Lot lot; public void addSpace(Space space) {} }
221
0.678733
0.674208
16
12.8125
12.511088
40
false
false
0
0
0
0
0
0
0.4375
false
false
14
47783c4a4358e8897b0982ff3768c389fd664060
6,227,702,609,072
4b44fa9ee29456e868b3ea62a4e0737d0334465d
/src/dao/StudentDAO.java
d70e664f566abad72d7dc9d71436088a67e426d0
[]
no_license
annalla/hibernate
https://github.com/annalla/hibernate
d2f519a412636251abd5c26e410baf5fa0e4226b
9406c1a76888d774222be1c7b2796d22b6a67c9c
refs/heads/master
2023-05-25T21:33:46.486000
2021-06-09T16:22:23
2021-06-09T16:22:23
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dao; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.query.Query; import pojo.MinitryEntity; import pojo.StudentEntity; import util.HibernateUtil; import java.util.List; public class StudentDAO { public static List<StudentEntity> getStudentList() { List<StudentEntity> ds = null; Session session = HibernateUtil.getSessionFactory().openSession(); try { String hql = "select m from StudentEntity m"; Query query = session.createQuery(hql); ds = query.list(); } catch (HibernateException ex) { //Log the exception System.err.println(ex); } finally { session.close(); } return ds; } public static StudentEntity getStudentbyId(int student) { StudentEntity sach = null; Session session = HibernateUtil.getSessionFactory() .openSession(); try { //int studentId=Integer.parseInt(student); sach = (StudentEntity) session.get(StudentEntity.class, student); } catch (HibernateException ex) { //Log the exception System.err.println(ex); } finally { session.close(); } return sach; } public static StudentEntity getStudentbyUsername(String username) { StudentEntity st = null; Session session = HibernateUtil.getSessionFactory() .openSession(); try { String hql = "select m from StudentEntity m where m.username =:username"; Query query = session.createQuery(hql); query.setString("username", username); st = (StudentEntity) query.uniqueResult(); } catch (HibernateException ex) { //Log the exception System.err.println(ex); } finally { session.close(); } return st; } public static boolean updateStudent(StudentEntity sv) { Session session = HibernateUtil.getSessionFactory().openSession(); if (StudentDAO.getStudentbyId(sv.getStudentId()) == null) { return false; } Transaction transaction = null; try { transaction = session.beginTransaction(); session.update(sv); transaction.commit(); } catch (HibernateException ex) { //Log the exception transaction.rollback(); System.err.println(ex); } finally { session.close(); } return true; } public static boolean deleteStudent(StudentEntity sv) { Session session = HibernateUtil.getSessionFactory().openSession(); if (StudentDAO.getStudentbyId(sv.getStudentId()) == null) { return false; } Transaction transaction = null; try { transaction = session.beginTransaction(); session.delete(sv); transaction.commit(); } catch (HibernateException ex) { //Log the exception transaction.rollback(); System.err.println(ex); } finally { session.close(); } return true; } public static boolean addStudent(StudentEntity sv) { Session session = HibernateUtil.getSessionFactory().openSession(); if (StudentDAO.getStudentbyUsername(sv.getUsername()) != null) { return false; } Transaction transaction = null; try { transaction = session.beginTransaction(); session.save(sv); transaction.commit(); } catch (HibernateException ex) { //Log the exception transaction.rollback(); System.err.println(ex); } finally { session.close(); } return true; } }
UTF-8
Java
3,857
java
StudentDAO.java
Java
[]
null
[]
package dao; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.query.Query; import pojo.MinitryEntity; import pojo.StudentEntity; import util.HibernateUtil; import java.util.List; public class StudentDAO { public static List<StudentEntity> getStudentList() { List<StudentEntity> ds = null; Session session = HibernateUtil.getSessionFactory().openSession(); try { String hql = "select m from StudentEntity m"; Query query = session.createQuery(hql); ds = query.list(); } catch (HibernateException ex) { //Log the exception System.err.println(ex); } finally { session.close(); } return ds; } public static StudentEntity getStudentbyId(int student) { StudentEntity sach = null; Session session = HibernateUtil.getSessionFactory() .openSession(); try { //int studentId=Integer.parseInt(student); sach = (StudentEntity) session.get(StudentEntity.class, student); } catch (HibernateException ex) { //Log the exception System.err.println(ex); } finally { session.close(); } return sach; } public static StudentEntity getStudentbyUsername(String username) { StudentEntity st = null; Session session = HibernateUtil.getSessionFactory() .openSession(); try { String hql = "select m from StudentEntity m where m.username =:username"; Query query = session.createQuery(hql); query.setString("username", username); st = (StudentEntity) query.uniqueResult(); } catch (HibernateException ex) { //Log the exception System.err.println(ex); } finally { session.close(); } return st; } public static boolean updateStudent(StudentEntity sv) { Session session = HibernateUtil.getSessionFactory().openSession(); if (StudentDAO.getStudentbyId(sv.getStudentId()) == null) { return false; } Transaction transaction = null; try { transaction = session.beginTransaction(); session.update(sv); transaction.commit(); } catch (HibernateException ex) { //Log the exception transaction.rollback(); System.err.println(ex); } finally { session.close(); } return true; } public static boolean deleteStudent(StudentEntity sv) { Session session = HibernateUtil.getSessionFactory().openSession(); if (StudentDAO.getStudentbyId(sv.getStudentId()) == null) { return false; } Transaction transaction = null; try { transaction = session.beginTransaction(); session.delete(sv); transaction.commit(); } catch (HibernateException ex) { //Log the exception transaction.rollback(); System.err.println(ex); } finally { session.close(); } return true; } public static boolean addStudent(StudentEntity sv) { Session session = HibernateUtil.getSessionFactory().openSession(); if (StudentDAO.getStudentbyUsername(sv.getUsername()) != null) { return false; } Transaction transaction = null; try { transaction = session.beginTransaction(); session.save(sv); transaction.commit(); } catch (HibernateException ex) { //Log the exception transaction.rollback(); System.err.println(ex); } finally { session.close(); } return true; } }
3,857
0.587503
0.587503
124
30.104839
20.499731
85
false
false
0
0
0
0
0
0
0.524194
false
false
14
f6e96a8db1c3dd0b66abffda3e0512ea80402894
27,281,632,306,663
a9c1dc925542d4c553ef7460e3ba45eb863ac14f
/Loans/src/main/java/com/nwmogk/bukkit/loans/api/Terms.java
c7d9853cb8f01787b5a87dd67b0ffc68c8cc4b1f
[ "Apache-2.0" ]
permissive
nmogk/SerenityLoans
https://github.com/nmogk/SerenityLoans
9c964ba7d7197962c500dff5ef04d1c333499ebe
ea03b12f089f7814e882536accc392d782a800f0
refs/heads/master
2021-01-23T05:45:55.519000
2014-07-14T04:17:04
2014-07-14T04:17:04
21,581,324
1
0
null
false
2014-07-14T04:17:07
2014-07-07T18:11:39
2014-07-07T21:48:02
2014-07-14T04:17:04
0
0
0
0
Java
null
null
/** * ======================================================================== * DESCRIPTION * ======================================================================== * * File: Terms.java * Contributing Authors: Nathan W Mogk * * This enum provides identification for every field that describes the * terms of a loan. There is a 1:1 match with the terms in the mySQL * database and the fields in this enum. * * * ======================================================================== * LICENSE INFORMATION * ======================================================================== * * Copyright 2014 Nathan W Mogk * * 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. * * * ======================================================================== * CHANGE LOG * ======================================================================== * Date Name Description Defect # * ---------- -------------- ---------------------------------- -------- * 2014-02-11 nmogk Initial release for v0.1 * * */ package com.nwmogk.bukkit.loans.api; public enum Terms { LENDER, BORROWER, VALUE, INTERESTRATE, LATEFEE, MINPAYMENT, SERVICEFEE, TERM, COMPOUNDINGPERIOD, GRACEPERIOD, PAYMENTTIME, PAYMENTFREQUENCY, SERVICEFEEFREQUENCY, LOANTYPE; }
UTF-8
Java
1,974
java
Terms.java
Java
[ { "context": " * \r\n * File: Terms.java\r\n * Contributing Authors: Nathan W Mogk\r\n * \r\n * This enum provides identification for ev", "end": 269, "score": 0.9998800754547119, "start": 256, "tag": "NAME", "value": "Nathan W Mogk" }, { "context": "==========================\r\n * \r\n * Copyright 2014 Nathan W Mogk\r\n * \r\n * Licensed under the Apache License, Versi", "end": 714, "score": 0.9998793601989746, "start": 701, "tag": "NAME", "value": "Nathan W Mogk" } ]
null
[]
/** * ======================================================================== * DESCRIPTION * ======================================================================== * * File: Terms.java * Contributing Authors: <NAME> * * This enum provides identification for every field that describes the * terms of a loan. There is a 1:1 match with the terms in the mySQL * database and the fields in this enum. * * * ======================================================================== * LICENSE INFORMATION * ======================================================================== * * Copyright 2014 <NAME> * * 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. * * * ======================================================================== * CHANGE LOG * ======================================================================== * Date Name Description Defect # * ---------- -------------- ---------------------------------- -------- * 2014-02-11 nmogk Initial release for v0.1 * * */ package com.nwmogk.bukkit.loans.api; public enum Terms { LENDER, BORROWER, VALUE, INTERESTRATE, LATEFEE, MINPAYMENT, SERVICEFEE, TERM, COMPOUNDINGPERIOD, GRACEPERIOD, PAYMENTTIME, PAYMENTFREQUENCY, SERVICEFEEFREQUENCY, LOANTYPE; }
1,960
0.458967
0.448835
51
36.705883
30.005421
75
false
false
0
0
0
0
72
0.218845
0.45098
false
false
14
0342d18e8ab777a8c4bd67726f4580c75eee09c0
3,590,592,659,528
6f672fb72caedccb841ee23f53e32aceeaf1895e
/Photography/picarts_studio_source/src/com/picsart/effects/colorsplash/ColorSplashActivity$18.java
df53dd1b43721744cf6bc397b5e05eee8f057804
[]
no_license
cha63506/CompSecurity
https://github.com/cha63506/CompSecurity
5c69743f660b9899146ed3cf21eceabe3d5f4280
eee7e74f4088b9c02dd711c061fc04fb1e4e2654
refs/heads/master
2018-03-23T04:15:18.480000
2015-12-19T01:29:58
2015-12-19T01:29:58
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.picsart.effects.colorsplash; import android.view.View; import android.widget.CompoundButton; // Referenced classes of package com.picsart.effects.colorsplash: // ColorSplashActivity, ColorSplashForegroundView final class a implements android.view.rSplashActivity._cls18 { private ColorSplashActivity a; public final void onClick(View view) { if (ColorSplashActivity.d(a)) { return; } ColorSplashForegroundView colorsplashforegroundview = (ColorSplashForegroundView)a.findViewById(0x7f1002bc); if (view.getId() == 0x7f10018e) { ((CompoundButton)a.findViewById(0x7f10018d)).setChecked(false); ((CompoundButton)a.findViewById(0x7f10018e)).setChecked(true); colorsplashforegroundview.setDrawMode(true); return; } else { ((CompoundButton)a.findViewById(0x7f10018d)).setChecked(true); ((CompoundButton)a.findViewById(0x7f10018e)).setChecked(false); colorsplashforegroundview.setDrawMode(false); return; } } ew(ColorSplashActivity colorsplashactivity) { a = colorsplashactivity; super(); } }
UTF-8
Java
1,417
java
ColorSplashActivity$18.java
Java
[ { "context": "// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.\n// Jad home page: http://www.geocities.com/kpdus", "end": 61, "score": 0.9996766448020935, "start": 45, "tag": "NAME", "value": "Pavel Kouznetsov" } ]
null
[]
// Decompiled by Jad v1.5.8e. Copyright 2001 <NAME>. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.picsart.effects.colorsplash; import android.view.View; import android.widget.CompoundButton; // Referenced classes of package com.picsart.effects.colorsplash: // ColorSplashActivity, ColorSplashForegroundView final class a implements android.view.rSplashActivity._cls18 { private ColorSplashActivity a; public final void onClick(View view) { if (ColorSplashActivity.d(a)) { return; } ColorSplashForegroundView colorsplashforegroundview = (ColorSplashForegroundView)a.findViewById(0x7f1002bc); if (view.getId() == 0x7f10018e) { ((CompoundButton)a.findViewById(0x7f10018d)).setChecked(false); ((CompoundButton)a.findViewById(0x7f10018e)).setChecked(true); colorsplashforegroundview.setDrawMode(true); return; } else { ((CompoundButton)a.findViewById(0x7f10018d)).setChecked(true); ((CompoundButton)a.findViewById(0x7f10018e)).setChecked(false); colorsplashforegroundview.setDrawMode(false); return; } } ew(ColorSplashActivity colorsplashactivity) { a = colorsplashactivity; super(); } }
1,407
0.666196
0.63091
46
29.804348
27.970186
116
false
false
0
0
0
0
0
0
0.369565
false
false
14
1bb846dab11c483cb95ae7afd485e311e71a6a91
28,278,064,710,540
e977063b4cef9a4e402699ad8697e1bba059e511
/src/main/java/com/manage/biz/dao/JoinMemberDao.java
1adc080d320638a15d8d2efb5d669396cf855501
[]
no_license
leedonghyeon/SNS_Pro3
https://github.com/leedonghyeon/SNS_Pro3
82b2166e19a9d94f6771a2b744b1314a7fda7700
da5e497af3cabb213e784149a7a6f9085d10220d
refs/heads/master
2021-04-30T07:07:17.991000
2017-01-25T02:20:57
2017-01-25T02:20:57
79,975,710
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.manage.biz.dao; import com.manage.biz.vo.JoinMember; public interface JoinMemberDao { int insertJoinMember(JoinMember insert_member) throws Exception; JoinMember selectJoinMember(String member_id) throws Exception; public JoinMember findByUserIdAndPassword(String userId, String password) throws Exception; int findPassword(JoinMember joinmember) throws Exception; public void updatePassword(JoinMember joinmember) throws Exception; int CheckID(JoinMember joinmember) throws Exception; }
UTF-8
Java
536
java
JoinMemberDao.java
Java
[]
null
[]
package com.manage.biz.dao; import com.manage.biz.vo.JoinMember; public interface JoinMemberDao { int insertJoinMember(JoinMember insert_member) throws Exception; JoinMember selectJoinMember(String member_id) throws Exception; public JoinMember findByUserIdAndPassword(String userId, String password) throws Exception; int findPassword(JoinMember joinmember) throws Exception; public void updatePassword(JoinMember joinmember) throws Exception; int CheckID(JoinMember joinmember) throws Exception; }
536
0.79291
0.79291
14
36.285713
31.465239
95
false
false
0
0
0
0
0
0
0.785714
false
false
14
9abef8aca0c20fe3f29cf8e2255299d49bc11400
14,620,068,716,289
7d8463292abff3427a502ade6d7d69d307d2aeef
/src/main/java/com/xiaoyuan/common/dao/CommentMapper.java
94a3ec5d0fdecf71047cdb8faa879cf236a63b76
[]
no_license
ForMM/java_web
https://github.com/ForMM/java_web
0491231c253c88263efbd6048591dfd4ff94076a
a5ecba7be97c51077bf45eb40e48418c0afd2ce5
refs/heads/master
2022-12-22T04:55:34.374000
2020-02-28T03:29:27
2020-02-28T03:29:27
232,834,808
0
0
null
false
2022-12-16T05:01:48
2020-01-09T15:02:50
2020-02-28T03:29:47
2022-12-16T05:01:45
18,926
0
0
14
Java
false
false
package com.xiaoyuan.common.dao; import java.util.List; import java.util.Map; import com.xiaoyuan.common.entity.Comment; public interface CommentMapper { int deleteByPrimaryKey(Long nCommentId); int insert(Comment record); int insertSelective(Comment record); Comment selectByPrimaryKey(Long nCommentId); int updateByPrimaryKeySelective(Comment record); int updateByPrimaryKey(Comment record); List<Comment> findByParam(Map<String, Object> param); int countByParam(Map<String, Object> param); List<Comment> myComments(Map<String, Object> param); int myCommentsCount(Map<String, Object> param); }
UTF-8
Java
634
java
CommentMapper.java
Java
[]
null
[]
package com.xiaoyuan.common.dao; import java.util.List; import java.util.Map; import com.xiaoyuan.common.entity.Comment; public interface CommentMapper { int deleteByPrimaryKey(Long nCommentId); int insert(Comment record); int insertSelective(Comment record); Comment selectByPrimaryKey(Long nCommentId); int updateByPrimaryKeySelective(Comment record); int updateByPrimaryKey(Comment record); List<Comment> findByParam(Map<String, Object> param); int countByParam(Map<String, Object> param); List<Comment> myComments(Map<String, Object> param); int myCommentsCount(Map<String, Object> param); }
634
0.766562
0.766562
26
23.423077
21.377871
54
false
false
0
0
0
0
0
0
0.884615
false
false
14
27b0d7fbe14d097aace625ef9ec971da584fa2b8
30,296,699,335,267
5ade2cc67f4b194262c6d22ace2a45f5058b124f
/src/main/java/edu/py/octodb/batch/models/Database.java
0fc5c972fd0a759901e6a844e59f659773769815
[]
no_license
locoabuelito/nosql
https://github.com/locoabuelito/nosql
2a3eb269d81c0df82fc71b5852309f0a41d8553c
b70d20eb9d3236b1dc3d3a482c67c3af55136b63
refs/heads/master
2023-05-01T02:42:03.445000
2020-05-21T04:17:51
2020-05-21T04:17:51
265,101,064
0
0
null
false
2021-04-26T20:18:10
2020-05-19T00:46:19
2020-05-21T04:18:20
2021-04-26T20:18:09
951
0
0
1
Java
false
false
package edu.py.octodb.batch.models; import java.util.Date; import java.util.List; // Gestion de las bases de datos // Lista de documentos y colecciones public class Database { private String name; private String descripcion; private Date date; private List<Document> users; private List<Collection> collections; private static String path; public static String getPath() { return path; } public static void setPath(String path) { Database.path = path; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public List<Document> getUsers() { return users; } public void setUsers(List<Document> users) { this.users = users; } public List<Collection> getCollections() { return collections; } public void setCollections(List<Collection> collections) { this.collections = collections; } }
UTF-8
Java
1,128
java
Database.java
Java
[]
null
[]
package edu.py.octodb.batch.models; import java.util.Date; import java.util.List; // Gestion de las bases de datos // Lista de documentos y colecciones public class Database { private String name; private String descripcion; private Date date; private List<Document> users; private List<Collection> collections; private static String path; public static String getPath() { return path; } public static void setPath(String path) { Database.path = path; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public List<Document> getUsers() { return users; } public void setUsers(List<Document> users) { this.users = users; } public List<Collection> getCollections() { return collections; } public void setCollections(List<Collection> collections) { this.collections = collections; } }
1,128
0.718085
0.718085
65
16.353846
15.920408
59
false
false
0
0
0
0
0
0
1.153846
false
false
14
2f0ac4dc18d1a7a704e5f909b84b22f5a456a772
29,515,015,296,651
969dcd0b6cf2c24cca4324f20f40ba50e54acd69
/MinXing-android/src/cn/minxing/activity/SZ_SheZhiActivity.java
356d2004e789a9b66fed183a63d46c275f324f56
[]
no_license
zhumingmin/android_project
https://github.com/zhumingmin/android_project
29a63bce57e37fc720d0adf13e31d490530accad
a4036d6d130352d13054eed7a4a87cde786e72cf
refs/heads/master
2021-01-20T20:03:34.787000
2017-03-19T10:31:36
2017-03-19T10:31:36
62,620,131
5
4
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.minxing.activity; import com.zhumingmin.vmsofminxing.R; import cn.minxing.PushMessage.ExitApplication; import cn.minxing.PushMessage.XiaoMiTuiSong; import cn.minxing.restwebservice.LoginService; import cn.minxing.restwebservice.YiBaoService; import cn.minxing.util.JianChaGengXin; import android.app.Activity; import android.content.Intent; import android.content.res.AssetManager; import android.graphics.Typeface; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.LinearLayout; import android.widget.Toast; public class SZ_SheZhiActivity extends Activity { private Button zhanghaoanquan, bangzhu, guanyu, shezhi_zhanghaoanquan, shezhi_gengxin, zhuxiaodenglu; String data1, data2, data3; private LinearLayout ly_fanhui; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(com.zhumingmin.vmsofminxing.R.layout.activity_shezhi_shezhi); ExitApplication.getInstance().addActivity(this); zhanghaoanquan = (Button) findViewById(com.zhumingmin.vmsofminxing.R.id.shezhi_zhanghaoanquan); shezhi_gengxin = (Button) findViewById(com.zhumingmin.vmsofminxing.R.id.shezhi_gengxin); bangzhu = (Button) findViewById(com.zhumingmin.vmsofminxing.R.id.shezhi_bangzhu); guanyu = (Button) findViewById(com.zhumingmin.vmsofminxing.R.id.shezhi_guanyu); zhuxiaodenglu = (Button) findViewById(com.zhumingmin.vmsofminxing.R.id.zhuxiaodenglu); shezhi_zhanghaoanquan = (Button) findViewById(com.zhumingmin.vmsofminxing.R.id.shezhi_zhanghaoanquan); ly_fanhui = (LinearLayout) findViewById(R.id.ly_fanhui_shezhi); ly_fanhui.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub finish(); } }); Intent intent = getIntent(); data1 = intent.getStringExtra("data1"); data2 = intent.getStringExtra("data2"); data3 = intent.getStringExtra("data3"); zhuxiaodenglu.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub // Intent logoutIntent = new Intent(SZ_SheZhi.this, // DengLuJieMian.class); // logoutIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK // | Intent.FLAG_ACTIVITY_NEW_TASK); // startActivity(logoutIntent); Intent intent = new Intent(SZ_SheZhiActivity.this, LoginService.class); intent.putExtra("from", 1); startActivity(intent); ExitApplication.getInstance().exit(); finish(); } }); shezhi_gengxin.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub DisplayToast("将使用第三方工具实现,如小米提供的检查更新的功能!"); Intent intent = new Intent(SZ_SheZhiActivity.this, JianChaGengXin.class); startActivity(intent); } }); zhanghaoanquan.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(); intent = new Intent(SZ_SheZhiActivity.this, ZhangHaoAnQuanActivity.class); intent.putExtra("data1", data1); intent.putExtra("data2", data2); intent.putExtra("data3", data3); startActivity(intent); } }); bangzhu.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(); intent.setClass(SZ_SheZhiActivity.this, HelpActivity.class); startActivity(intent); } }); guanyu.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(); intent.setClass(SZ_SheZhiActivity.this, GuanYuMinXingZhiJiaActivity.class); startActivity(intent); } }); } private void DisplayToast(String string) { // TODO Auto-generated method stub Toast.makeText(this, string, Toast.LENGTH_SHORT).show(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK) && (event.getRepeatCount() == 0)) { // Intent intent = new Intent(); // intent.setClass(SZ_SheZhi.this, SheZhi.class); // startActivity(intent); SZ_SheZhiActivity.this.finish(); } return super.onKeyDown(keyCode, event); } }
UTF-8
Java
4,611
java
SZ_SheZhiActivity.java
Java
[]
null
[]
package cn.minxing.activity; import com.zhumingmin.vmsofminxing.R; import cn.minxing.PushMessage.ExitApplication; import cn.minxing.PushMessage.XiaoMiTuiSong; import cn.minxing.restwebservice.LoginService; import cn.minxing.restwebservice.YiBaoService; import cn.minxing.util.JianChaGengXin; import android.app.Activity; import android.content.Intent; import android.content.res.AssetManager; import android.graphics.Typeface; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.LinearLayout; import android.widget.Toast; public class SZ_SheZhiActivity extends Activity { private Button zhanghaoanquan, bangzhu, guanyu, shezhi_zhanghaoanquan, shezhi_gengxin, zhuxiaodenglu; String data1, data2, data3; private LinearLayout ly_fanhui; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(com.zhumingmin.vmsofminxing.R.layout.activity_shezhi_shezhi); ExitApplication.getInstance().addActivity(this); zhanghaoanquan = (Button) findViewById(com.zhumingmin.vmsofminxing.R.id.shezhi_zhanghaoanquan); shezhi_gengxin = (Button) findViewById(com.zhumingmin.vmsofminxing.R.id.shezhi_gengxin); bangzhu = (Button) findViewById(com.zhumingmin.vmsofminxing.R.id.shezhi_bangzhu); guanyu = (Button) findViewById(com.zhumingmin.vmsofminxing.R.id.shezhi_guanyu); zhuxiaodenglu = (Button) findViewById(com.zhumingmin.vmsofminxing.R.id.zhuxiaodenglu); shezhi_zhanghaoanquan = (Button) findViewById(com.zhumingmin.vmsofminxing.R.id.shezhi_zhanghaoanquan); ly_fanhui = (LinearLayout) findViewById(R.id.ly_fanhui_shezhi); ly_fanhui.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub finish(); } }); Intent intent = getIntent(); data1 = intent.getStringExtra("data1"); data2 = intent.getStringExtra("data2"); data3 = intent.getStringExtra("data3"); zhuxiaodenglu.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub // Intent logoutIntent = new Intent(SZ_SheZhi.this, // DengLuJieMian.class); // logoutIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK // | Intent.FLAG_ACTIVITY_NEW_TASK); // startActivity(logoutIntent); Intent intent = new Intent(SZ_SheZhiActivity.this, LoginService.class); intent.putExtra("from", 1); startActivity(intent); ExitApplication.getInstance().exit(); finish(); } }); shezhi_gengxin.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub DisplayToast("将使用第三方工具实现,如小米提供的检查更新的功能!"); Intent intent = new Intent(SZ_SheZhiActivity.this, JianChaGengXin.class); startActivity(intent); } }); zhanghaoanquan.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(); intent = new Intent(SZ_SheZhiActivity.this, ZhangHaoAnQuanActivity.class); intent.putExtra("data1", data1); intent.putExtra("data2", data2); intent.putExtra("data3", data3); startActivity(intent); } }); bangzhu.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(); intent.setClass(SZ_SheZhiActivity.this, HelpActivity.class); startActivity(intent); } }); guanyu.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(); intent.setClass(SZ_SheZhiActivity.this, GuanYuMinXingZhiJiaActivity.class); startActivity(intent); } }); } private void DisplayToast(String string) { // TODO Auto-generated method stub Toast.makeText(this, string, Toast.LENGTH_SHORT).show(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK) && (event.getRepeatCount() == 0)) { // Intent intent = new Intent(); // intent.setClass(SZ_SheZhi.this, SheZhi.class); // startActivity(intent); SZ_SheZhiActivity.this.finish(); } return super.onKeyDown(keyCode, event); } }
4,611
0.737777
0.73405
147
30.02721
23.808174
104
false
false
0
0
0
0
0
0
2.666667
false
false
14
2bffd05f174ec1864517e1b55c92805b66f227aa
29,515,015,296,597
7ccd837c94e59aea198812227a9d9fe2ef6b6d57
/MyProxyB/Client.java
96fd934353197e306d61bba1c01ef98f04789318
[]
no_license
RaisaSilva/Ejercicio-Proxy
https://github.com/RaisaSilva/Ejercicio-Proxy
e05d988eab80a07a3f931dc42bfae6b32ac2113e
9c099bc0d4598a19ab0a7e68085beb1f0af155e0
refs/heads/master
2022-11-04T09:23:06.959000
2020-06-23T13:34:07
2020-06-23T13:34:07
274,414,026
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package proxy.MyProxyB; public class Client { public static void main (String []args){ Proxy proxy = new Proxy(); proxy.setFile(new File("Musica", ".zzip")); proxy.request(); } }
UTF-8
Java
212
java
Client.java
Java
[]
null
[]
package proxy.MyProxyB; public class Client { public static void main (String []args){ Proxy proxy = new Proxy(); proxy.setFile(new File("Musica", ".zzip")); proxy.request(); } }
212
0.59434
0.59434
12
16.666666
17.598927
50
false
false
0
0
0
0
0
0
0.416667
false
false
14
04602eb5fcab712d79d462a1432555e007d22ee5
26,233,660,291,208
24da0765d172d4f8cfbf46d61f7ce95a21463a73
/src/printReadme/PrintReadme.java
b6aa60a3bba7cc714db7c601e9b77c330086a8ac
[]
no_license
alex-novosiber/MultiParser
https://github.com/alex-novosiber/MultiParser
c2f4d0181ce817f99fd73bbbd8d3b4d8da0cbd71
c9c384adba752c0ab2643647b6b867ed7f932025
refs/heads/master
2023-07-14T23:44:43.900000
2021-08-31T14:26:58
2021-08-31T14:26:58
381,346,358
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package printReadme; public class PrintReadme { public static void print() { System.out.println(""); System.out.println("*****************************************************************"); System.out.println(" Парсер обьявлений о продаже недвижимости по Новосибирску.\n" + "Программа способна сохранить до 1.350 обьявлений. \n" + "Задержки в работе созданы специально - чтобы не перегружать сервер запросами.\n" + "\n" + " 1. Запуск парсера через батничек \"startParser.bat\"\n" + "\n" + " 2. Дождись завершения работы программы. \n" + " ( По завершению работы она выдаст звуковой сигнал).\n" + " Теперь окно программы можно закрыть.\n" + " 3.Используй сортировку и фильтр для сортировки.\n" + " 4. Если загрузились не все обьявления - проверь интернет-соединение,\n" + " возможны пропуски при загруженности вызываемого сервера.\n" + "\n" + " Автор - Олег Гюнтер, 04,2020 , Новосибирск."); System.out.println("*****************************************************************"); } }
UTF-8
Java
1,740
java
PrintReadme.java
Java
[ { "context": " \"\\n\" +\n \" Автор - Олег Гюнтер, 04,2020 , Новосибирск.\");\n ", "end": 1139, "score": 0.9536855816841125, "start": 1134, "tag": "NAME", "value": "Автор" }, { "context": " \"\\n\" +\n \" Автор - Олег Гюнтер, 04,2020 , Новосибирск.\");\n System.out.pri", "end": 1153, "score": 0.9998777508735657, "start": 1142, "tag": "NAME", "value": "Олег Гюнтер" } ]
null
[]
package printReadme; public class PrintReadme { public static void print() { System.out.println(""); System.out.println("*****************************************************************"); System.out.println(" Парсер обьявлений о продаже недвижимости по Новосибирску.\n" + "Программа способна сохранить до 1.350 обьявлений. \n" + "Задержки в работе созданы специально - чтобы не перегружать сервер запросами.\n" + "\n" + " 1. Запуск парсера через батничек \"startParser.bat\"\n" + "\n" + " 2. Дождись завершения работы программы. \n" + " ( По завершению работы она выдаст звуковой сигнал).\n" + " Теперь окно программы можно закрыть.\n" + " 3.Используй сортировку и фильтр для сортировки.\n" + " 4. Если загрузились не все обьявления - проверь интернет-соединение,\n" + " возможны пропуски при загруженности вызываемого сервера.\n" + "\n" + " Автор - <NAME>, 04,2020 , Новосибирск."); System.out.println("*****************************************************************"); } }
1,725
0.480963
0.470085
28
44.964287
37.317635
99
false
false
0
0
0
0
0
0
0.321429
false
false
14
a29bbcd5c605753ab4eb21b57a9a75702d30f552
18,932,215,886,063
f36c1715273809f63748a742add10d327b808575
/onstreet/src/main/java/org/kosta/onstreet/model/service/AdminServiceImpl.java
eea987b4f82257322eaf92006127b5844f075cd1
[]
no_license
JinYongHyeon/ONStreet
https://github.com/JinYongHyeon/ONStreet
4ef3aa0507af8813f4629777f6eef1ff3d5bda52
b5c01604a88cbf107e051122e25d4e5cbad95c1b
refs/heads/main
2023-02-18T06:19:13.425000
2021-01-21T07:24:51
2021-01-21T07:24:51
315,853,821
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.kosta.onstreet.model.service; import javax.annotation.Resource; import org.kosta.onstreet.model.PagingBean; import org.kosta.onstreet.model.mapper.AdminMapper; import org.kosta.onstreet.model.mapper.BoardMapper; import org.kosta.onstreet.model.mapper.MemberMapper; import org.kosta.onstreet.model.vo.ArtistListVO; import org.kosta.onstreet.model.vo.ArtistVO; import org.kosta.onstreet.model.vo.EventListVO; import org.kosta.onstreet.model.vo.MemberListVO; import org.kosta.onstreet.model.vo.MemberVO; import org.kosta.onstreet.model.vo.ShowListVO; import org.kosta.onstreet.model.vo.ShowVO; import org.springframework.stereotype.Service; @Service public class AdminServiceImpl implements AdminService { @Resource private MemberMapper memberMapper; @Resource private AdminMapper adminMapper; @Resource private BoardMapper boardMapper; /** * 정지윤 * 회원관리 - 삭제 */ @Override public void manageMember(String[] checkMember) { ArtistVO avo = new ArtistVO(); MemberVO memberVO = new MemberVO(); for(String id:checkMember) { memberVO.setId(id); avo.setMemberVO(memberVO); memberMapper.removeMember(avo); } } /** * 정지윤 * 회원(ROLE_MEMBER) 리스트 불러오기 */ @Override public MemberListVO getMemberList(String pageNo) { int memberTotalCount = adminMapper.getTotalMemberCount(); PagingBean pagingBean = null; if(pageNo==null) pagingBean = new PagingBean(memberTotalCount); else pagingBean = new PagingBean(memberTotalCount,Integer.parseInt(pageNo)); MemberListVO memberListVO = new MemberListVO(adminMapper.getManageMemberList("ROLE_MEMBER",pagingBean),pagingBean); return memberListVO; } /** * 정지윤 * 회원(ROLE_ARTIST) 리스트 불러오기 */ @Override public MemberListVO getMemberArtistList(String pageNo) { int memberTotalCount = adminMapper.getTotalMemberArtistCount(); PagingBean pagingBean = null; if(pageNo==null) pagingBean = new PagingBean(memberTotalCount); else pagingBean = new PagingBean(memberTotalCount,Integer.parseInt(pageNo)); MemberListVO memberListVO = new MemberListVO(adminMapper.getManageMemberArtistList("ROLE_ARTIST", pagingBean),pagingBean); return memberListVO; } /** * 정지윤 * 탈퇴 회원 리스트 불러오기 */ @Override public MemberListVO getRemoveMemberList(String pageNo) { int removeMemberTotal = adminMapper.getTotalRemoveMemberCount(); PagingBean pagingBean = null; if(pageNo==null) pagingBean = new PagingBean(removeMemberTotal); else pagingBean = new PagingBean(removeMemberTotal,Integer.parseInt(pageNo)); MemberListVO memberListVO = new MemberListVO(adminMapper.getRemoveMemberList("ROLE_MEMBER", pagingBean),pagingBean); return memberListVO; } /** * 정지윤 * 회원 검색 카운트 */ @Override public int manageSearchMemberTotalCount(String nickName) { return adminMapper.manageSearchMemberTotalCount(nickName); } /** * 정지윤 * 회원 검색 */ @Override public MemberListVO manageSearchMember(String pageNo, String nickName) { int totalCount = adminMapper.manageSearchMemberTotalCount(nickName); PagingBean pagingBean = null; if(pageNo != null) pagingBean = new PagingBean(totalCount, Integer.parseInt(pageNo)); else pagingBean = new PagingBean(totalCount); MemberListVO memberListVO = new MemberListVO(adminMapper.manageSearchMember(nickName, pagingBean),pagingBean); return memberListVO; } /** * 정지윤 * 탈퇴 회원 검색 카운트 */ @Override public int manageSearchRemoveMemberTotalCount(String nickName) { return adminMapper.manageSearchRemoveMemberTotalCount(nickName); } /** * 정지윤 * 탈퇴 회원 검색 */ @Override public MemberListVO manageSearchRemoveMember(String pageNo, String nickName) { int totalCount = adminMapper.manageSearchRemoveMemberTotalCount(nickName); PagingBean pagingBean = null; if(pageNo != null) pagingBean = new PagingBean(totalCount, Integer.parseInt(pageNo)); else pagingBean = new PagingBean(totalCount); MemberListVO memberListVO = new MemberListVO(adminMapper.manageSearchRemoveMember(nickName, pagingBean),pagingBean); return memberListVO; } /** * 정지윤 * 게시물 삭제 */ @Override public void manageShow(String[] checkShow) { ShowVO showVO = new ShowVO(); for(String showNo:checkShow) { showVO.setShowNo(showNo); boardMapper.deleteShow(showNo); } } /** * 정지윤 * 공연 검색 카운트 */ @Override public int manageSearchShowTotalCount(String showTitle) { return boardMapper.getSearchShowTotalCount(showTitle); } /** * 정지윤 * 공연 검색 */ @Override public ShowListVO manageSearchShow(String pageNo, String showTitle) { int totalCount = boardMapper.getSearchShowTotalCount(showTitle); PagingBean pagingBean = null; if(pageNo != null) pagingBean = new PagingBean(totalCount, Integer.parseInt(pageNo)); else pagingBean = new PagingBean(totalCount); ShowListVO showListVO = new ShowListVO(boardMapper.getSearchShow(showTitle, pagingBean),pagingBean); return showListVO; } /** * 정지윤 * 미승인 아티스트 리스트 불러오기 */ @Override public ArtistListVO getCheckArtistList(String pageNo) { int checkArtistTotalCount = adminMapper.getTotalCheckArtist(); PagingBean pagingBean = null; if(pageNo==null) pagingBean = new PagingBean(checkArtistTotalCount); else pagingBean = new PagingBean(checkArtistTotalCount,Integer.parseInt(pageNo)); ArtistListVO artistListVO = new ArtistListVO(adminMapper.getCheckArtistList(pagingBean),pagingBean); return artistListVO; } /** * 정지윤 * 아티스트 승인 */ @Override public void checkArtist(String[] checkArtist) { for(String id:checkArtist) { adminMapper.checkArtist(id); } } /** * 정지윤 * 아티스트 반려 */ @Override public void uncheckArtist(String[] uncheckArtist) { for(String id:uncheckArtist) adminMapper.uncheckArtist(id); } /** * 정지윤 * 미승인 이벤트 리스트 불러오기 */ @Override public EventListVO getCheckEventList(String pageNo) { int checkEventTotalCount = adminMapper.getTotalCheckEvent(); PagingBean pagingBean = null; if(pageNo==null) pagingBean = new PagingBean(checkEventTotalCount); else pagingBean = new PagingBean(checkEventTotalCount,Integer.parseInt(pageNo)); EventListVO eventListVO = new EventListVO(adminMapper.getCheckEventList(pagingBean),pagingBean); return eventListVO; } /** * 정지윤 * 이벤트 승인 */ @Override public void checkEvent(String[] checkEvent) { for(String eventNo:checkEvent) { adminMapper.checkEvent(eventNo); } } /** * 정지윤 * 이벤트 반려 */ @Override public void uncheckEvent(String[] uncheckEvent) { for(String eventNo:uncheckEvent) { adminMapper.uncheckEvent(eventNo); } } /** * 정지윤 * 게시된 이벤트 리스트 불러오기 */ @Override public EventListVO manageEventList(String pageNo) { int manageEventCount = adminMapper.manageEventListCount(); PagingBean pagingBean = null; if(pageNo==null) pagingBean = new PagingBean(manageEventCount); else pagingBean = new PagingBean(manageEventCount,Integer.parseInt(pageNo)); EventListVO eventListVO = new EventListVO(adminMapper.manageEventList(pagingBean),pagingBean); return eventListVO; } /** * 정지윤 * 이벤트 삭제 */ public void deleteEvent(String[] deleteEvent) { for(String eventNo:deleteEvent) { adminMapper.deleteEvent(eventNo); } } }
UTF-8
Java
7,592
java
AdminServiceImpl.java
Java
[]
null
[]
package org.kosta.onstreet.model.service; import javax.annotation.Resource; import org.kosta.onstreet.model.PagingBean; import org.kosta.onstreet.model.mapper.AdminMapper; import org.kosta.onstreet.model.mapper.BoardMapper; import org.kosta.onstreet.model.mapper.MemberMapper; import org.kosta.onstreet.model.vo.ArtistListVO; import org.kosta.onstreet.model.vo.ArtistVO; import org.kosta.onstreet.model.vo.EventListVO; import org.kosta.onstreet.model.vo.MemberListVO; import org.kosta.onstreet.model.vo.MemberVO; import org.kosta.onstreet.model.vo.ShowListVO; import org.kosta.onstreet.model.vo.ShowVO; import org.springframework.stereotype.Service; @Service public class AdminServiceImpl implements AdminService { @Resource private MemberMapper memberMapper; @Resource private AdminMapper adminMapper; @Resource private BoardMapper boardMapper; /** * 정지윤 * 회원관리 - 삭제 */ @Override public void manageMember(String[] checkMember) { ArtistVO avo = new ArtistVO(); MemberVO memberVO = new MemberVO(); for(String id:checkMember) { memberVO.setId(id); avo.setMemberVO(memberVO); memberMapper.removeMember(avo); } } /** * 정지윤 * 회원(ROLE_MEMBER) 리스트 불러오기 */ @Override public MemberListVO getMemberList(String pageNo) { int memberTotalCount = adminMapper.getTotalMemberCount(); PagingBean pagingBean = null; if(pageNo==null) pagingBean = new PagingBean(memberTotalCount); else pagingBean = new PagingBean(memberTotalCount,Integer.parseInt(pageNo)); MemberListVO memberListVO = new MemberListVO(adminMapper.getManageMemberList("ROLE_MEMBER",pagingBean),pagingBean); return memberListVO; } /** * 정지윤 * 회원(ROLE_ARTIST) 리스트 불러오기 */ @Override public MemberListVO getMemberArtistList(String pageNo) { int memberTotalCount = adminMapper.getTotalMemberArtistCount(); PagingBean pagingBean = null; if(pageNo==null) pagingBean = new PagingBean(memberTotalCount); else pagingBean = new PagingBean(memberTotalCount,Integer.parseInt(pageNo)); MemberListVO memberListVO = new MemberListVO(adminMapper.getManageMemberArtistList("ROLE_ARTIST", pagingBean),pagingBean); return memberListVO; } /** * 정지윤 * 탈퇴 회원 리스트 불러오기 */ @Override public MemberListVO getRemoveMemberList(String pageNo) { int removeMemberTotal = adminMapper.getTotalRemoveMemberCount(); PagingBean pagingBean = null; if(pageNo==null) pagingBean = new PagingBean(removeMemberTotal); else pagingBean = new PagingBean(removeMemberTotal,Integer.parseInt(pageNo)); MemberListVO memberListVO = new MemberListVO(adminMapper.getRemoveMemberList("ROLE_MEMBER", pagingBean),pagingBean); return memberListVO; } /** * 정지윤 * 회원 검색 카운트 */ @Override public int manageSearchMemberTotalCount(String nickName) { return adminMapper.manageSearchMemberTotalCount(nickName); } /** * 정지윤 * 회원 검색 */ @Override public MemberListVO manageSearchMember(String pageNo, String nickName) { int totalCount = adminMapper.manageSearchMemberTotalCount(nickName); PagingBean pagingBean = null; if(pageNo != null) pagingBean = new PagingBean(totalCount, Integer.parseInt(pageNo)); else pagingBean = new PagingBean(totalCount); MemberListVO memberListVO = new MemberListVO(adminMapper.manageSearchMember(nickName, pagingBean),pagingBean); return memberListVO; } /** * 정지윤 * 탈퇴 회원 검색 카운트 */ @Override public int manageSearchRemoveMemberTotalCount(String nickName) { return adminMapper.manageSearchRemoveMemberTotalCount(nickName); } /** * 정지윤 * 탈퇴 회원 검색 */ @Override public MemberListVO manageSearchRemoveMember(String pageNo, String nickName) { int totalCount = adminMapper.manageSearchRemoveMemberTotalCount(nickName); PagingBean pagingBean = null; if(pageNo != null) pagingBean = new PagingBean(totalCount, Integer.parseInt(pageNo)); else pagingBean = new PagingBean(totalCount); MemberListVO memberListVO = new MemberListVO(adminMapper.manageSearchRemoveMember(nickName, pagingBean),pagingBean); return memberListVO; } /** * 정지윤 * 게시물 삭제 */ @Override public void manageShow(String[] checkShow) { ShowVO showVO = new ShowVO(); for(String showNo:checkShow) { showVO.setShowNo(showNo); boardMapper.deleteShow(showNo); } } /** * 정지윤 * 공연 검색 카운트 */ @Override public int manageSearchShowTotalCount(String showTitle) { return boardMapper.getSearchShowTotalCount(showTitle); } /** * 정지윤 * 공연 검색 */ @Override public ShowListVO manageSearchShow(String pageNo, String showTitle) { int totalCount = boardMapper.getSearchShowTotalCount(showTitle); PagingBean pagingBean = null; if(pageNo != null) pagingBean = new PagingBean(totalCount, Integer.parseInt(pageNo)); else pagingBean = new PagingBean(totalCount); ShowListVO showListVO = new ShowListVO(boardMapper.getSearchShow(showTitle, pagingBean),pagingBean); return showListVO; } /** * 정지윤 * 미승인 아티스트 리스트 불러오기 */ @Override public ArtistListVO getCheckArtistList(String pageNo) { int checkArtistTotalCount = adminMapper.getTotalCheckArtist(); PagingBean pagingBean = null; if(pageNo==null) pagingBean = new PagingBean(checkArtistTotalCount); else pagingBean = new PagingBean(checkArtistTotalCount,Integer.parseInt(pageNo)); ArtistListVO artistListVO = new ArtistListVO(adminMapper.getCheckArtistList(pagingBean),pagingBean); return artistListVO; } /** * 정지윤 * 아티스트 승인 */ @Override public void checkArtist(String[] checkArtist) { for(String id:checkArtist) { adminMapper.checkArtist(id); } } /** * 정지윤 * 아티스트 반려 */ @Override public void uncheckArtist(String[] uncheckArtist) { for(String id:uncheckArtist) adminMapper.uncheckArtist(id); } /** * 정지윤 * 미승인 이벤트 리스트 불러오기 */ @Override public EventListVO getCheckEventList(String pageNo) { int checkEventTotalCount = adminMapper.getTotalCheckEvent(); PagingBean pagingBean = null; if(pageNo==null) pagingBean = new PagingBean(checkEventTotalCount); else pagingBean = new PagingBean(checkEventTotalCount,Integer.parseInt(pageNo)); EventListVO eventListVO = new EventListVO(adminMapper.getCheckEventList(pagingBean),pagingBean); return eventListVO; } /** * 정지윤 * 이벤트 승인 */ @Override public void checkEvent(String[] checkEvent) { for(String eventNo:checkEvent) { adminMapper.checkEvent(eventNo); } } /** * 정지윤 * 이벤트 반려 */ @Override public void uncheckEvent(String[] uncheckEvent) { for(String eventNo:uncheckEvent) { adminMapper.uncheckEvent(eventNo); } } /** * 정지윤 * 게시된 이벤트 리스트 불러오기 */ @Override public EventListVO manageEventList(String pageNo) { int manageEventCount = adminMapper.manageEventListCount(); PagingBean pagingBean = null; if(pageNo==null) pagingBean = new PagingBean(manageEventCount); else pagingBean = new PagingBean(manageEventCount,Integer.parseInt(pageNo)); EventListVO eventListVO = new EventListVO(adminMapper.manageEventList(pagingBean),pagingBean); return eventListVO; } /** * 정지윤 * 이벤트 삭제 */ public void deleteEvent(String[] deleteEvent) { for(String eventNo:deleteEvent) { adminMapper.deleteEvent(eventNo); } } }
7,592
0.745202
0.745202
279
24.770609
26.8305
124
false
false
0
0
0
0
0
0
1.781362
false
false
14
eab552a9040f8bda0fc5378e9e56b20df2fdd8ff
6,468,220,808,946
af16bdeebb2e09810a12000265b883e2fc6e58db
/lab1from2012/lab1/Citat.java
805175ffc821d56eeb3ba8b8a6125f74e31c4116
[]
no_license
jherrlin/1DV006
https://github.com/jherrlin/1DV006
ccd44cf5f66ac8872a38a1f2df4153e961152a4a
bafc3371ed948fca6383022b3e69512d2d74cceb
refs/heads/master
2020-02-22T04:45:25.052000
2014-11-09T22:44:17
2014-11-09T22:44:17
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package lab1; // Import scanner import java.util.Scanner; /* Useful escape sequences \t is for inserting tabs into the literal \b inserts a backspace \n inserts a newline \r inserts a carriage return \' inserts a single quotation mark \" inserts a double quotation mark \\ inserts a backslash */ public class Citat { public static void main(String[] args) { // Scanner Scanner sc = new Scanner(System.in); // System.out.print("Skriv in en rad text: "); // Input String input1 = sc.nextLine(); System.out.println("Citat: " + "\"" + input1 + "\""); } }
UTF-8
Java
589
java
Citat.java
Java
[]
null
[]
package lab1; // Import scanner import java.util.Scanner; /* Useful escape sequences \t is for inserting tabs into the literal \b inserts a backspace \n inserts a newline \r inserts a carriage return \' inserts a single quotation mark \" inserts a double quotation mark \\ inserts a backslash */ public class Citat { public static void main(String[] args) { // Scanner Scanner sc = new Scanner(System.in); // System.out.print("Skriv in en rad text: "); // Input String input1 = sc.nextLine(); System.out.println("Citat: " + "\"" + input1 + "\""); } }
589
0.663837
0.658744
32
17.40625
15.978226
55
false
false
0
0
0
0
0
0
1
false
false
14
e35a1ad29c0db1b4bfaaa4ebbce94cd1d9cb3070
7,627,861,959,243
4da340a6db0eb1d845fec6aaf6b75a6871987eea
/org.adichatz.generator/src/generator/org/adichatz/generator/xjc/QueryTree.java
e62d23540d25426f5a2735694f7dd89bb766d1e3
[]
no_license
YvesDrumbonnet/Adichatz-RCP-Eclipse
https://github.com/YvesDrumbonnet/Adichatz-RCP-Eclipse
107bbf784407a6167729e9ed82c5546f3f8e3b5d
359c430f6daec55cab93a63d08c669fcd05dea84
refs/heads/master
2023-08-26T02:06:25.194000
2020-04-28T15:49:51
2020-04-28T15:49:51
256,515,394
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// // Ce fichier a été généré par l'implémentation de référence JavaTM Architecture for XML Binding (JAXB), v2.2.8-b130911.1802 // Voir <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Toute modification apportée à ce fichier sera perdue lors de la recompilation du schéma source. // Généré le : 2020.01.22 à 11:02:17 AM CET // package org.adichatz.generator.xjc; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Classe Java pour anonymous complex type. * * <p>Le fragment de schéma suivant indique le contenu attendu figurant dans cette classe. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;extension base="{}queryPartType"> * &lt;choice> * &lt;element name="jointure" type="{}jointureType" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="whereClause" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="sqlClause" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="jointureAliases" type="{}jointureAliasesType"/> * &lt;element name="queryPreference" type="{}queryPreferenceType"/> * &lt;element name="customizedPreferences" type="{}customizedPreferenceType"/> * &lt;element name="queryBuilder" type="{}queryBuilderType"/> * &lt;/choice> * &lt;attribute name="parentQueryManagerURI" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="lazyFetches" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="queryType" type="{}queryTypeEnum" /> * &lt;attribute name="valid" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(factoryClass=WrapperFactory.class, factoryMethod="getQueryTree", name = "", propOrder = { "jointure", "whereClause", "sqlClause", "jointureAliases", "queryPreference", "customizedPreferences", "queryBuilder" }) @XmlRootElement(name = "queryTree") public class QueryTree extends QueryPartType implements Serializable { private final static long serialVersionUID = 1L; protected List<JointureType> jointure; protected String whereClause; protected String sqlClause; protected JointureAliasesType jointureAliases; protected QueryPreferenceType queryPreference; protected CustomizedPreferenceType customizedPreferences; protected QueryBuilderType queryBuilder; @XmlAttribute(name = "parentQueryManagerURI") protected String parentQueryManagerURI; @XmlAttribute(name = "lazyFetches") protected String lazyFetches; @XmlAttribute(name = "queryType") protected QueryTypeEnum queryType; @XmlAttribute(name = "valid") protected String valid; /** * Gets the value of the jointure property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the jointure property. * * <p> * For example, to add a new item, do as follows: * <pre> * getJointure().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link JointureType } * * */ public List<JointureType> getJointure() { if (jointure == null) { jointure = new ArrayList<JointureType>(); } return this.jointure; } /** * Obtient la valeur de la propriété whereClause. * * @return * possible object is * {@link String } * */ public String getWhereClause() { return whereClause; } /** * Définit la valeur de la propriété whereClause. * * @param value * allowed object is * {@link String } * */ public void setWhereClause(String value) { this.whereClause = value; } /** * Obtient la valeur de la propriété sqlClause. * * @return * possible object is * {@link String } * */ public String getSqlClause() { return sqlClause; } /** * Définit la valeur de la propriété sqlClause. * * @param value * allowed object is * {@link String } * */ public void setSqlClause(String value) { this.sqlClause = value; } /** * Obtient la valeur de la propriété jointureAliases. * * @return * possible object is * {@link JointureAliasesType } * */ public JointureAliasesType getJointureAliases() { return jointureAliases; } /** * Définit la valeur de la propriété jointureAliases. * * @param value * allowed object is * {@link JointureAliasesType } * */ public void setJointureAliases(JointureAliasesType value) { this.jointureAliases = value; } /** * Obtient la valeur de la propriété queryPreference. * * @return * possible object is * {@link QueryPreferenceType } * */ public QueryPreferenceType getQueryPreference() { return queryPreference; } /** * Définit la valeur de la propriété queryPreference. * * @param value * allowed object is * {@link QueryPreferenceType } * */ public void setQueryPreference(QueryPreferenceType value) { this.queryPreference = value; } /** * Obtient la valeur de la propriété customizedPreferences. * * @return * possible object is * {@link CustomizedPreferenceType } * */ public CustomizedPreferenceType getCustomizedPreferences() { return customizedPreferences; } /** * Définit la valeur de la propriété customizedPreferences. * * @param value * allowed object is * {@link CustomizedPreferenceType } * */ public void setCustomizedPreferences(CustomizedPreferenceType value) { this.customizedPreferences = value; } /** * Obtient la valeur de la propriété queryBuilder. * * @return * possible object is * {@link QueryBuilderType } * */ public QueryBuilderType getQueryBuilder() { return queryBuilder; } /** * Définit la valeur de la propriété queryBuilder. * * @param value * allowed object is * {@link QueryBuilderType } * */ public void setQueryBuilder(QueryBuilderType value) { this.queryBuilder = value; } /** * Obtient la valeur de la propriété parentQueryManagerURI. * * @return * possible object is * {@link String } * */ public String getParentQueryManagerURI() { return parentQueryManagerURI; } /** * Définit la valeur de la propriété parentQueryManagerURI. * * @param value * allowed object is * {@link String } * */ public void setParentQueryManagerURI(String value) { this.parentQueryManagerURI = value; } /** * Obtient la valeur de la propriété lazyFetches. * * @return * possible object is * {@link String } * */ public String getLazyFetches() { return lazyFetches; } /** * Définit la valeur de la propriété lazyFetches. * * @param value * allowed object is * {@link String } * */ public void setLazyFetches(String value) { this.lazyFetches = value; } /** * Obtient la valeur de la propriété queryType. * * @return * possible object is * {@link QueryTypeEnum } * */ public QueryTypeEnum getQueryType() { return queryType; } /** * Définit la valeur de la propriété queryType. * * @param value * allowed object is * {@link QueryTypeEnum } * */ public void setQueryType(QueryTypeEnum value) { this.queryType = value; } /** * Obtient la valeur de la propriété valid. * * @return * possible object is * {@link String } * */ public String getValid() { return valid; } /** * Définit la valeur de la propriété valid. * * @param value * allowed object is * {@link String } * */ public void setValid(String value) { this.valid = value; } }
ISO-8859-1
Java
9,595
java
QueryTree.java
Java
[]
null
[]
// // Ce fichier a été généré par l'implémentation de référence JavaTM Architecture for XML Binding (JAXB), v2.2.8-b130911.1802 // Voir <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Toute modification apportée à ce fichier sera perdue lors de la recompilation du schéma source. // Généré le : 2020.01.22 à 11:02:17 AM CET // package org.adichatz.generator.xjc; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Classe Java pour anonymous complex type. * * <p>Le fragment de schéma suivant indique le contenu attendu figurant dans cette classe. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;extension base="{}queryPartType"> * &lt;choice> * &lt;element name="jointure" type="{}jointureType" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="whereClause" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="sqlClause" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="jointureAliases" type="{}jointureAliasesType"/> * &lt;element name="queryPreference" type="{}queryPreferenceType"/> * &lt;element name="customizedPreferences" type="{}customizedPreferenceType"/> * &lt;element name="queryBuilder" type="{}queryBuilderType"/> * &lt;/choice> * &lt;attribute name="parentQueryManagerURI" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="lazyFetches" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="queryType" type="{}queryTypeEnum" /> * &lt;attribute name="valid" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(factoryClass=WrapperFactory.class, factoryMethod="getQueryTree", name = "", propOrder = { "jointure", "whereClause", "sqlClause", "jointureAliases", "queryPreference", "customizedPreferences", "queryBuilder" }) @XmlRootElement(name = "queryTree") public class QueryTree extends QueryPartType implements Serializable { private final static long serialVersionUID = 1L; protected List<JointureType> jointure; protected String whereClause; protected String sqlClause; protected JointureAliasesType jointureAliases; protected QueryPreferenceType queryPreference; protected CustomizedPreferenceType customizedPreferences; protected QueryBuilderType queryBuilder; @XmlAttribute(name = "parentQueryManagerURI") protected String parentQueryManagerURI; @XmlAttribute(name = "lazyFetches") protected String lazyFetches; @XmlAttribute(name = "queryType") protected QueryTypeEnum queryType; @XmlAttribute(name = "valid") protected String valid; /** * Gets the value of the jointure property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the jointure property. * * <p> * For example, to add a new item, do as follows: * <pre> * getJointure().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link JointureType } * * */ public List<JointureType> getJointure() { if (jointure == null) { jointure = new ArrayList<JointureType>(); } return this.jointure; } /** * Obtient la valeur de la propriété whereClause. * * @return * possible object is * {@link String } * */ public String getWhereClause() { return whereClause; } /** * Définit la valeur de la propriété whereClause. * * @param value * allowed object is * {@link String } * */ public void setWhereClause(String value) { this.whereClause = value; } /** * Obtient la valeur de la propriété sqlClause. * * @return * possible object is * {@link String } * */ public String getSqlClause() { return sqlClause; } /** * Définit la valeur de la propriété sqlClause. * * @param value * allowed object is * {@link String } * */ public void setSqlClause(String value) { this.sqlClause = value; } /** * Obtient la valeur de la propriété jointureAliases. * * @return * possible object is * {@link JointureAliasesType } * */ public JointureAliasesType getJointureAliases() { return jointureAliases; } /** * Définit la valeur de la propriété jointureAliases. * * @param value * allowed object is * {@link JointureAliasesType } * */ public void setJointureAliases(JointureAliasesType value) { this.jointureAliases = value; } /** * Obtient la valeur de la propriété queryPreference. * * @return * possible object is * {@link QueryPreferenceType } * */ public QueryPreferenceType getQueryPreference() { return queryPreference; } /** * Définit la valeur de la propriété queryPreference. * * @param value * allowed object is * {@link QueryPreferenceType } * */ public void setQueryPreference(QueryPreferenceType value) { this.queryPreference = value; } /** * Obtient la valeur de la propriété customizedPreferences. * * @return * possible object is * {@link CustomizedPreferenceType } * */ public CustomizedPreferenceType getCustomizedPreferences() { return customizedPreferences; } /** * Définit la valeur de la propriété customizedPreferences. * * @param value * allowed object is * {@link CustomizedPreferenceType } * */ public void setCustomizedPreferences(CustomizedPreferenceType value) { this.customizedPreferences = value; } /** * Obtient la valeur de la propriété queryBuilder. * * @return * possible object is * {@link QueryBuilderType } * */ public QueryBuilderType getQueryBuilder() { return queryBuilder; } /** * Définit la valeur de la propriété queryBuilder. * * @param value * allowed object is * {@link QueryBuilderType } * */ public void setQueryBuilder(QueryBuilderType value) { this.queryBuilder = value; } /** * Obtient la valeur de la propriété parentQueryManagerURI. * * @return * possible object is * {@link String } * */ public String getParentQueryManagerURI() { return parentQueryManagerURI; } /** * Définit la valeur de la propriété parentQueryManagerURI. * * @param value * allowed object is * {@link String } * */ public void setParentQueryManagerURI(String value) { this.parentQueryManagerURI = value; } /** * Obtient la valeur de la propriété lazyFetches. * * @return * possible object is * {@link String } * */ public String getLazyFetches() { return lazyFetches; } /** * Définit la valeur de la propriété lazyFetches. * * @param value * allowed object is * {@link String } * */ public void setLazyFetches(String value) { this.lazyFetches = value; } /** * Obtient la valeur de la propriété queryType. * * @return * possible object is * {@link QueryTypeEnum } * */ public QueryTypeEnum getQueryType() { return queryType; } /** * Définit la valeur de la propriété queryType. * * @param value * allowed object is * {@link QueryTypeEnum } * */ public void setQueryType(QueryTypeEnum value) { this.queryType = value; } /** * Obtient la valeur de la propriété valid. * * @return * possible object is * {@link String } * */ public String getValid() { return valid; } /** * Définit la valeur de la propriété valid. * * @param value * allowed object is * {@link String } * */ public void setValid(String value) { this.valid = value; } }
9,595
0.572148
0.566481
352
25.071022
23.077515
125
false
false
0
0
0
0
0
0
0.215909
false
false
14
bda1b4b700483e3f1e67bb08f78a9d747e6b7474
20,804,821,632,680
068532b8088823bbbd34ebc987cd3cd6e229467b
/Song.java
6168945b52d32b0696ac405cfa3e596fe418700c
[]
no_license
shuiqingliu/Java
https://github.com/shuiqingliu/Java
6226ed102840ee3b61ed4e379352f2c5bcbcc3b6
0420dfa79c4a2b7e9bafe9eb4497a8b24ceaa504
refs/heads/master
2021-01-13T02:09:05.519000
2014-05-03T13:51:12
2014-05-03T13:51:12
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Song{ String title; String artist; public void setTitle(String title){ this.title = title; } public void setArtist(String artist){ this.artist = artist; } public void play(){ System.out.println(artist + " is play " + title); } public static void main(String[] args){ Song mysong = new Song(); mysong.setTitle("yesterday once more"); mysong.setArtist("qingliu"); mysong.play(); } }
UTF-8
Java
425
java
Song.java
Java
[]
null
[]
public class Song{ String title; String artist; public void setTitle(String title){ this.title = title; } public void setArtist(String artist){ this.artist = artist; } public void play(){ System.out.println(artist + " is play " + title); } public static void main(String[] args){ Song mysong = new Song(); mysong.setTitle("yesterday once more"); mysong.setArtist("qingliu"); mysong.play(); } }
425
0.670588
0.670588
26
15.384615
15.845593
51
false
false
0
0
0
0
0
0
1.307692
false
false
14
793f72e52cb63e87dcb694ddaed0c9d4e80cf444
4,148,938,457,336
93079b507815ccb6b7987e1427c9d9c548f5f4bc
/cdap-app-fabric/src/main/java/co/cask/cdap/route/store/ZKRouteStore.java
a60d1e7e657a2fc0b3d7aac3c62b35ca2dea79e0
[]
no_license
pergrand/cdap
https://github.com/pergrand/cdap
1ca2cc775880db0bb8f6e0560737709dd4caeb69
b0f9efd05494ddcdc7587f474236ae43cc04eeb4
refs/heads/master
2020-03-05T16:52:08.823000
2017-06-06T11:03:06
2017-06-06T11:03:06
93,508,449
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright © 2016 Cask Data, Inc. * * 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 co.cask.cdap.route.store; import co.cask.cdap.api.common.Bytes; import co.cask.cdap.common.NotFoundException; import co.cask.cdap.common.io.Codec; import co.cask.cdap.common.service.ServiceDiscoverable; import co.cask.cdap.common.zookeeper.ZKExtOperations; import co.cask.cdap.proto.id.ProgramId; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.common.base.Throwables; import com.google.common.collect.Maps; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.SettableFuture; import com.google.gson.Gson; import com.google.inject.Inject; import org.apache.twill.zookeeper.NodeData; import org.apache.twill.zookeeper.OperationFuture; import org.apache.twill.zookeeper.ZKClient; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.data.Stat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Collections; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import javax.annotation.Nullable; /** * RouteStore where the routes are stored in a ZK persistent node. This is intended for use in distributed mode. */ public class ZKRouteStore implements RouteStore { private static final Logger LOG = LoggerFactory.getLogger(ZKRouteStore.class); private static final Gson GSON = new Gson(); private static final int ZK_TIMEOUT_SECS = 5; private static final Codec<RouteConfig> ROUTE_CONFIG_CODEC = new Codec<RouteConfig>() { @Override public byte[] encode(RouteConfig object) throws IOException { return Bytes.toBytes(GSON.toJson(object)); } @Override public RouteConfig decode(byte[] data) throws IOException { return GSON.fromJson(Bytes.toString(data), RouteConfig.class); } }; private final ZKClient zkClient; private final ConcurrentMap<ProgramId, SettableFuture<RouteConfig>> routeConfigMap; @Inject public ZKRouteStore(ZKClient zkClient) { this.zkClient = zkClient; this.routeConfigMap = Maps.newConcurrentMap(); } @Override public void store(final ProgramId serviceId, final RouteConfig routeConfig) { Supplier<RouteConfig> supplier = Suppliers.ofInstance(routeConfig); SettableFuture<RouteConfig> oldConfigFuture = routeConfigMap.get(serviceId); Future<RouteConfig> future = ZKExtOperations.createOrSet(zkClient, getZKPath(serviceId), supplier, ROUTE_CONFIG_CODEC, 10); try { future.get(ZK_TIMEOUT_SECS, TimeUnit.SECONDS); SettableFuture<RouteConfig> newFuture = SettableFuture.create(); newFuture.set(routeConfig); if (oldConfigFuture != null) { routeConfigMap.replace(serviceId, oldConfigFuture, newFuture); } else { routeConfigMap.putIfAbsent(serviceId, newFuture); } } catch (ExecutionException | InterruptedException | TimeoutException ex) { throw Throwables.propagate(ex); } } @Override public void delete(final ProgramId serviceId) throws NotFoundException { OperationFuture<String> future = zkClient.delete(getZKPath(serviceId)); SettableFuture<RouteConfig> oldConfigFuture = routeConfigMap.get(serviceId); try { future.get(ZK_TIMEOUT_SECS, TimeUnit.SECONDS); routeConfigMap.remove(serviceId, oldConfigFuture); } catch (ExecutionException | InterruptedException | TimeoutException ex) { if (ex.getCause() instanceof KeeperException.NoNodeException) { throw new NotFoundException(String.format("Route Config for Service %s was not found.", serviceId)); } throw Throwables.propagate(ex); } } @Override public RouteConfig fetch(final ProgramId serviceId) { Future<RouteConfig> future = routeConfigMap.get(serviceId); if (future == null) { SettableFuture<RouteConfig> settableFuture = SettableFuture.create(); future = routeConfigMap.putIfAbsent(serviceId, settableFuture); if (future == null) { future = getAndWatchData(serviceId, settableFuture, settableFuture, new ZKRouteWatcher(serviceId)); } } return getConfig(serviceId, future); } private RouteConfig getConfig(ProgramId serviceId, Future<RouteConfig> future) { try { return future.get(ZK_TIMEOUT_SECS, TimeUnit.SECONDS); } catch (Exception e) { LOG.debug("Getting configuration for service {} from ZK failed.", serviceId, e); return new RouteConfig(Collections.<String, Integer>emptyMap()); } } private static String getZKPath(ProgramId serviceId) { return String.format("/routestore/%s", ServiceDiscoverable.getName(serviceId)); } private Future<RouteConfig> getAndWatchData(final ProgramId serviceId, final SettableFuture<RouteConfig> settableFuture, final SettableFuture<RouteConfig> oldSettableFuture, final Watcher watcher) { OperationFuture<NodeData> future = zkClient.getData(getZKPath(serviceId), watcher); Futures.addCallback(future, new FutureCallback<NodeData>() { @Override public void onSuccess(NodeData result) { try { RouteConfig route = ROUTE_CONFIG_CODEC.decode(result.getData()); settableFuture.set(route); // Replace the future in the routeConfigMap in order to reflect the route config changes routeConfigMap.replace(serviceId, oldSettableFuture, settableFuture); } catch (Exception ex) { LOG.debug("Unable to deserialize the config for service {}. Got data {}", serviceId, result.getData()); // Need to remove the future from the map since later calls will continue to use this future and will think // that there is an exception routeConfigMap.remove(serviceId, settableFuture); settableFuture.setException(ex); } } @Override public void onFailure(Throwable t) { // If no node is present, then set an empty RouteConfig (instead of setting exception since generating // stack trace, when future.get is called, is expensive). Also place a watch on the node to monitor further // data updates. If its an exception other than NoNodeException, then remove the future, so that // zkClient#getData will be retried during the next fetch config request if (t instanceof KeeperException.NoNodeException) { settableFuture.set(new RouteConfig(Collections.<String, Integer>emptyMap())); existsAndWatch(serviceId, settableFuture); } else { settableFuture.setException(t); routeConfigMap.remove(serviceId, settableFuture); } } }); return settableFuture; } private void existsAndWatch(final ProgramId serviceId, final SettableFuture<RouteConfig> oldSettableFuture) { Futures.addCallback(zkClient.exists(getZKPath(serviceId), new Watcher() { @Override public void process(WatchedEvent event) { // If service name doesn't exist in the map, then don't rewatch it. if (!routeConfigMap.containsKey(serviceId)) { return; } if (event.getType() == Event.EventType.NodeCreated) { getAndWatchData(serviceId, SettableFuture.<RouteConfig>create(), oldSettableFuture, new ZKRouteWatcher(serviceId)); } } }), new FutureCallback<Stat>() { @Override public void onSuccess(@Nullable Stat result) { if (result != null) { getAndWatchData(serviceId, SettableFuture.<RouteConfig>create(), oldSettableFuture, new ZKRouteWatcher(serviceId)); } } @Override public void onFailure(Throwable t) { routeConfigMap.remove(serviceId); LOG.debug("Failed to check exists for property data for {}", serviceId, t); } }); } @Override public void close() throws Exception { // Clear the map, so that any active watches will expire. routeConfigMap.clear(); } private class ZKRouteWatcher implements Watcher { private final ProgramId serviceId; ZKRouteWatcher(ProgramId serviceId) { this.serviceId = serviceId; } @Override public void process(WatchedEvent event) { // If service name doesn't exist in the map, then don't re-watch it. SettableFuture<RouteConfig> oldSettableFuture = routeConfigMap.get(serviceId); if (oldSettableFuture == null) { return; } if (event.getType() == Event.EventType.NodeDeleted) { // Remove the mapping from cache routeConfigMap.remove(serviceId, oldSettableFuture); return; } // Create a new settable future, since we don't want to set the existing future again getAndWatchData(serviceId, SettableFuture.<RouteConfig>create(), oldSettableFuture, this); } } }
UTF-8
Java
9,840
java
ZKRouteStore.java
Java
[ { "context": "/*\n * Copyright © 2016 Cask Data, Inc.\n *\n * Licensed under the Apache License, Ve", "end": 32, "score": 0.9339993596076965, "start": 23, "tag": "NAME", "value": "Cask Data" } ]
null
[]
/* * Copyright © 2016 <NAME>, Inc. * * 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 co.cask.cdap.route.store; import co.cask.cdap.api.common.Bytes; import co.cask.cdap.common.NotFoundException; import co.cask.cdap.common.io.Codec; import co.cask.cdap.common.service.ServiceDiscoverable; import co.cask.cdap.common.zookeeper.ZKExtOperations; import co.cask.cdap.proto.id.ProgramId; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.common.base.Throwables; import com.google.common.collect.Maps; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.SettableFuture; import com.google.gson.Gson; import com.google.inject.Inject; import org.apache.twill.zookeeper.NodeData; import org.apache.twill.zookeeper.OperationFuture; import org.apache.twill.zookeeper.ZKClient; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.data.Stat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Collections; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import javax.annotation.Nullable; /** * RouteStore where the routes are stored in a ZK persistent node. This is intended for use in distributed mode. */ public class ZKRouteStore implements RouteStore { private static final Logger LOG = LoggerFactory.getLogger(ZKRouteStore.class); private static final Gson GSON = new Gson(); private static final int ZK_TIMEOUT_SECS = 5; private static final Codec<RouteConfig> ROUTE_CONFIG_CODEC = new Codec<RouteConfig>() { @Override public byte[] encode(RouteConfig object) throws IOException { return Bytes.toBytes(GSON.toJson(object)); } @Override public RouteConfig decode(byte[] data) throws IOException { return GSON.fromJson(Bytes.toString(data), RouteConfig.class); } }; private final ZKClient zkClient; private final ConcurrentMap<ProgramId, SettableFuture<RouteConfig>> routeConfigMap; @Inject public ZKRouteStore(ZKClient zkClient) { this.zkClient = zkClient; this.routeConfigMap = Maps.newConcurrentMap(); } @Override public void store(final ProgramId serviceId, final RouteConfig routeConfig) { Supplier<RouteConfig> supplier = Suppliers.ofInstance(routeConfig); SettableFuture<RouteConfig> oldConfigFuture = routeConfigMap.get(serviceId); Future<RouteConfig> future = ZKExtOperations.createOrSet(zkClient, getZKPath(serviceId), supplier, ROUTE_CONFIG_CODEC, 10); try { future.get(ZK_TIMEOUT_SECS, TimeUnit.SECONDS); SettableFuture<RouteConfig> newFuture = SettableFuture.create(); newFuture.set(routeConfig); if (oldConfigFuture != null) { routeConfigMap.replace(serviceId, oldConfigFuture, newFuture); } else { routeConfigMap.putIfAbsent(serviceId, newFuture); } } catch (ExecutionException | InterruptedException | TimeoutException ex) { throw Throwables.propagate(ex); } } @Override public void delete(final ProgramId serviceId) throws NotFoundException { OperationFuture<String> future = zkClient.delete(getZKPath(serviceId)); SettableFuture<RouteConfig> oldConfigFuture = routeConfigMap.get(serviceId); try { future.get(ZK_TIMEOUT_SECS, TimeUnit.SECONDS); routeConfigMap.remove(serviceId, oldConfigFuture); } catch (ExecutionException | InterruptedException | TimeoutException ex) { if (ex.getCause() instanceof KeeperException.NoNodeException) { throw new NotFoundException(String.format("Route Config for Service %s was not found.", serviceId)); } throw Throwables.propagate(ex); } } @Override public RouteConfig fetch(final ProgramId serviceId) { Future<RouteConfig> future = routeConfigMap.get(serviceId); if (future == null) { SettableFuture<RouteConfig> settableFuture = SettableFuture.create(); future = routeConfigMap.putIfAbsent(serviceId, settableFuture); if (future == null) { future = getAndWatchData(serviceId, settableFuture, settableFuture, new ZKRouteWatcher(serviceId)); } } return getConfig(serviceId, future); } private RouteConfig getConfig(ProgramId serviceId, Future<RouteConfig> future) { try { return future.get(ZK_TIMEOUT_SECS, TimeUnit.SECONDS); } catch (Exception e) { LOG.debug("Getting configuration for service {} from ZK failed.", serviceId, e); return new RouteConfig(Collections.<String, Integer>emptyMap()); } } private static String getZKPath(ProgramId serviceId) { return String.format("/routestore/%s", ServiceDiscoverable.getName(serviceId)); } private Future<RouteConfig> getAndWatchData(final ProgramId serviceId, final SettableFuture<RouteConfig> settableFuture, final SettableFuture<RouteConfig> oldSettableFuture, final Watcher watcher) { OperationFuture<NodeData> future = zkClient.getData(getZKPath(serviceId), watcher); Futures.addCallback(future, new FutureCallback<NodeData>() { @Override public void onSuccess(NodeData result) { try { RouteConfig route = ROUTE_CONFIG_CODEC.decode(result.getData()); settableFuture.set(route); // Replace the future in the routeConfigMap in order to reflect the route config changes routeConfigMap.replace(serviceId, oldSettableFuture, settableFuture); } catch (Exception ex) { LOG.debug("Unable to deserialize the config for service {}. Got data {}", serviceId, result.getData()); // Need to remove the future from the map since later calls will continue to use this future and will think // that there is an exception routeConfigMap.remove(serviceId, settableFuture); settableFuture.setException(ex); } } @Override public void onFailure(Throwable t) { // If no node is present, then set an empty RouteConfig (instead of setting exception since generating // stack trace, when future.get is called, is expensive). Also place a watch on the node to monitor further // data updates. If its an exception other than NoNodeException, then remove the future, so that // zkClient#getData will be retried during the next fetch config request if (t instanceof KeeperException.NoNodeException) { settableFuture.set(new RouteConfig(Collections.<String, Integer>emptyMap())); existsAndWatch(serviceId, settableFuture); } else { settableFuture.setException(t); routeConfigMap.remove(serviceId, settableFuture); } } }); return settableFuture; } private void existsAndWatch(final ProgramId serviceId, final SettableFuture<RouteConfig> oldSettableFuture) { Futures.addCallback(zkClient.exists(getZKPath(serviceId), new Watcher() { @Override public void process(WatchedEvent event) { // If service name doesn't exist in the map, then don't rewatch it. if (!routeConfigMap.containsKey(serviceId)) { return; } if (event.getType() == Event.EventType.NodeCreated) { getAndWatchData(serviceId, SettableFuture.<RouteConfig>create(), oldSettableFuture, new ZKRouteWatcher(serviceId)); } } }), new FutureCallback<Stat>() { @Override public void onSuccess(@Nullable Stat result) { if (result != null) { getAndWatchData(serviceId, SettableFuture.<RouteConfig>create(), oldSettableFuture, new ZKRouteWatcher(serviceId)); } } @Override public void onFailure(Throwable t) { routeConfigMap.remove(serviceId); LOG.debug("Failed to check exists for property data for {}", serviceId, t); } }); } @Override public void close() throws Exception { // Clear the map, so that any active watches will expire. routeConfigMap.clear(); } private class ZKRouteWatcher implements Watcher { private final ProgramId serviceId; ZKRouteWatcher(ProgramId serviceId) { this.serviceId = serviceId; } @Override public void process(WatchedEvent event) { // If service name doesn't exist in the map, then don't re-watch it. SettableFuture<RouteConfig> oldSettableFuture = routeConfigMap.get(serviceId); if (oldSettableFuture == null) { return; } if (event.getType() == Event.EventType.NodeDeleted) { // Remove the mapping from cache routeConfigMap.remove(serviceId, oldSettableFuture); return; } // Create a new settable future, since we don't want to set the existing future again getAndWatchData(serviceId, SettableFuture.<RouteConfig>create(), oldSettableFuture, this); } } }
9,837
0.702307
0.700986
248
38.673386
31.917519
117
false
false
0
0
0
0
0
0
0.669355
false
false
14
bd6a77de063330734d266e15a6d2b488e2ef55aa
16,621,523,491,162
292bd357f3a14a81d7fd743453fbd52e2c3090e8
/src/leetcode/problems/dp/LC_Triangle.java
743c7d3de98a7be7a449b09eed57d82c96014bb6
[]
no_license
BangKiHyun/Algorithm
https://github.com/BangKiHyun/Algorithm
90ea1e07924d06ab7c16a9aa6e5578c33953c705
065953a728227c796294ef993815a1fa50d9be31
refs/heads/master
2023-04-13T11:14:35.325000
2023-04-02T08:50:43
2023-04-02T08:50:43
190,966,256
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package leetcode.problems.dp; import java.util.Arrays; import java.util.List; public class LC_Triangle { private int maxSize; public static void main(String[] args) { final LC_Triangle task = new LC_Triangle(); List<List<Integer>> triangle = Arrays.asList(Arrays.asList(2), Arrays.asList(3, 4), Arrays.asList(6, 5, 7), Arrays.asList(4, 1, 8, 3)); System.out.println(task.minimumTotal(triangle)); } public int minimumTotal(List<List<Integer>> triangle) { maxSize = triangle.size(); int[][] cache = new int[maxSize][maxSize]; return findMinimumTotal(triangle, cache, 0, 0); } private int findMinimumTotal(List<List<Integer>> triangle, int[][] cache, int raw, int col) { if (raw == maxSize) { return 0; } if (cache[raw][col] != 0) { return cache[raw][col]; } return cache[raw][col] = triangle.get(raw).get(col) + Math.min(findMinimumTotal(triangle, cache, raw + 1, col), findMinimumTotal(triangle, cache, raw + 1, col + 1)); } }
UTF-8
Java
1,160
java
LC_Triangle.java
Java
[]
null
[]
package leetcode.problems.dp; import java.util.Arrays; import java.util.List; public class LC_Triangle { private int maxSize; public static void main(String[] args) { final LC_Triangle task = new LC_Triangle(); List<List<Integer>> triangle = Arrays.asList(Arrays.asList(2), Arrays.asList(3, 4), Arrays.asList(6, 5, 7), Arrays.asList(4, 1, 8, 3)); System.out.println(task.minimumTotal(triangle)); } public int minimumTotal(List<List<Integer>> triangle) { maxSize = triangle.size(); int[][] cache = new int[maxSize][maxSize]; return findMinimumTotal(triangle, cache, 0, 0); } private int findMinimumTotal(List<List<Integer>> triangle, int[][] cache, int raw, int col) { if (raw == maxSize) { return 0; } if (cache[raw][col] != 0) { return cache[raw][col]; } return cache[raw][col] = triangle.get(raw).get(col) + Math.min(findMinimumTotal(triangle, cache, raw + 1, col), findMinimumTotal(triangle, cache, raw + 1, col + 1)); } }
1,160
0.568965
0.55431
36
31.222221
25.721922
97
false
false
0
0
0
0
0
0
0.972222
false
false
14
17db1752a3eeee3b9100a987bd8ee65efdc9cbe2
32,633,161,581,191
c11a11419232edac993d327a881f5888a8158569
/src/Etoile.java
4178fc6b73b12335ad2bf786d34ea767b1bffc98
[]
no_license
Lordimado/Etoile
https://github.com/Lordimado/Etoile
7c4c12ec2e9207093014489e86611b82c2fe0c8c
86c0e10598a4e32f2ed5fa192e4d9a486710d3f6
refs/heads/master
2021-01-10T22:42:08.420000
2016-10-15T21:08:17
2016-10-15T21:08:17
70,365,370
0
5
null
false
2016-10-22T18:33:15
2016-10-09T00:38:55
2016-10-09T00:39:39
2016-10-15T21:08:17
8
0
4
1
Java
null
null
import java.util.*; public class Etoile { public static void triangle(int n,int espace){ String etoile = " "; for(int i=0;i<n;i++){ espace =n-i; for(int j=0;j<espace;j++){ System.out.print(" "); } etoile =etoile+"* "; System.out.println(etoile); } } public static void main(String [] args){ Scanner sc = new Scanner(System.in); int n=sc.nextInt(); int espace = 0; triangle(n,espace); } } //
UTF-8
Java
426
java
Etoile.java
Java
[]
null
[]
import java.util.*; public class Etoile { public static void triangle(int n,int espace){ String etoile = " "; for(int i=0;i<n;i++){ espace =n-i; for(int j=0;j<espace;j++){ System.out.print(" "); } etoile =etoile+"* "; System.out.println(etoile); } } public static void main(String [] args){ Scanner sc = new Scanner(System.in); int n=sc.nextInt(); int espace = 0; triangle(n,espace); } } //
426
0.605634
0.598592
25
16.040001
13.799942
47
false
false
0
0
0
0
0
0
1.88
false
false
14
180c004944addada444da5e47274f8108c42e35c
31,207,232,410,931
07203ed1daa77c037eeb903c2f2c7e74c7814566
/src/Index.java
324ee552faef926c43de494aa7336d69672e6003
[]
no_license
lamlamngo/index-generator
https://github.com/lamlamngo/index-generator
b8a2e20eb82b4c14b635f4282bce9be4c17afd36
9619978225126ff806077e1b3fb2951696763e7e
refs/heads/master
2021-08-22T07:11:04.609000
2017-11-29T15:24:19
2017-11-29T15:24:19
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Create an index that tells on what pages you can find certain keywords for any given text files. * * @author Lam Ngo * @version 06/02/2016 * * I have read the syllabus and understand what outside sources I am allowed to consult for this *class and how I am allowed to discuss the class projects with other people. I confirm that I have *done all my work on this project according to the guidelines in the syllabus. * Signature: Lam Ngo */ public class Index { /** * A string containing all punctuations */ private static final String PUNCTUATION = "!\"”“‘’….',;:.-_?)(/[]{}<>*#\n\t\r$%^&"; /** * a FileReader object to read text files */ private FileReader myReader; /** * A binary Search Tree that will holds the words that appears more than 4 times */ private BinarySearchTree<String> myDictionary; /** * A binary search tree that will holds keywords and they pages it appears on */ private BinarySearchTree<IndexNode> myIndex; /** * an int keeping track of the page the program is currently on */ private int pageNumber; /** * A default constructor that creates an empty Index */ public Index(){ myDictionary = new BinarySearchTree<String>(); myIndex = new BinarySearchTree<IndexNode>(); pageNumber = 1; } /** * Fills the index using the words in the given document file * @param filename * the given text file */ public void createIndexFromFile(String filename){ IndexNode indexNode; myReader = new FileReader(filename); String token = myReader.nextToken(); // while there are still words to process while (token != null){ // if the token is #, increment page number if (token.equals("#")){ pageNumber ++; }else{ token = cleanToken(token,PUNCTUATION); token = token.toLowerCase(); indexNode = new IndexNode(token); // if token is 3 chars or longer and token is not in the dictionary if (token.length() >= 3 && myDictionary.find(token) == null){ // if token is already in the index if (myIndex.find(indexNode) != null){ // if word's page list doesnt yet have this page number if (!myIndex.find(indexNode).ifAlreadyin(pageNumber)){ // if word's page list isnt full if (!myIndex.find(indexNode).ifFull()){ myIndex.find(indexNode).insert(pageNumber); }else{ myIndex.remove(indexNode); myDictionary.add(token); } } }else{ indexNode.insert(pageNumber); myIndex.add(indexNode); } } } // get a new token token = myReader.nextToken(); } } /** * strip a string off any leading or trailing punctuation * @param source * the string to be stripped * @param trimChars * all punctuation to be removed * @return */ private String cleanToken(String source, String trimChars) { char[] chars = source.toCharArray(); int length = chars.length; int start = 0; while (start < length && trimChars.indexOf(chars[start]) > -1) { start++; } while (start < length && trimChars.indexOf(chars[length - 1]) > -1) { length--; } if (start > 0 || length < chars.length) { return source.substring(start, length); } else { return source; } } /** * Prints out the constructed index */ public void printIndex(){ String result = "INDEX:\n"; result += "======\n"; result += myIndex.toString(); System.out.println(result); } /** * Prints out the words that were not included in the index. */ public void printExcludedWords(){ String result = "DICTIONARY of excluded words:\n"; result += "=============================\n"; result += myDictionary.toString(); System.out.println(result); } }
UTF-8
Java
3,774
java
Index.java
Java
[ { "context": " keywords for any given text files.\n * \n * @author Lam Ngo\n * @version 06/02/2016\n * \n * I have read the sy", "end": 127, "score": 0.9998530149459839, "start": 120, "tag": "NAME", "value": "Lam Ngo" } ]
null
[]
/** * Create an index that tells on what pages you can find certain keywords for any given text files. * * @author <NAME> * @version 06/02/2016 * * I have read the syllabus and understand what outside sources I am allowed to consult for this *class and how I am allowed to discuss the class projects with other people. I confirm that I have *done all my work on this project according to the guidelines in the syllabus. * Signature: Lam Ngo */ public class Index { /** * A string containing all punctuations */ private static final String PUNCTUATION = "!\"”“‘’….',;:.-_?)(/[]{}<>*#\n\t\r$%^&"; /** * a FileReader object to read text files */ private FileReader myReader; /** * A binary Search Tree that will holds the words that appears more than 4 times */ private BinarySearchTree<String> myDictionary; /** * A binary search tree that will holds keywords and they pages it appears on */ private BinarySearchTree<IndexNode> myIndex; /** * an int keeping track of the page the program is currently on */ private int pageNumber; /** * A default constructor that creates an empty Index */ public Index(){ myDictionary = new BinarySearchTree<String>(); myIndex = new BinarySearchTree<IndexNode>(); pageNumber = 1; } /** * Fills the index using the words in the given document file * @param filename * the given text file */ public void createIndexFromFile(String filename){ IndexNode indexNode; myReader = new FileReader(filename); String token = myReader.nextToken(); // while there are still words to process while (token != null){ // if the token is #, increment page number if (token.equals("#")){ pageNumber ++; }else{ token = cleanToken(token,PUNCTUATION); token = token.toLowerCase(); indexNode = new IndexNode(token); // if token is 3 chars or longer and token is not in the dictionary if (token.length() >= 3 && myDictionary.find(token) == null){ // if token is already in the index if (myIndex.find(indexNode) != null){ // if word's page list doesnt yet have this page number if (!myIndex.find(indexNode).ifAlreadyin(pageNumber)){ // if word's page list isnt full if (!myIndex.find(indexNode).ifFull()){ myIndex.find(indexNode).insert(pageNumber); }else{ myIndex.remove(indexNode); myDictionary.add(token); } } }else{ indexNode.insert(pageNumber); myIndex.add(indexNode); } } } // get a new token token = myReader.nextToken(); } } /** * strip a string off any leading or trailing punctuation * @param source * the string to be stripped * @param trimChars * all punctuation to be removed * @return */ private String cleanToken(String source, String trimChars) { char[] chars = source.toCharArray(); int length = chars.length; int start = 0; while (start < length && trimChars.indexOf(chars[start]) > -1) { start++; } while (start < length && trimChars.indexOf(chars[length - 1]) > -1) { length--; } if (start > 0 || length < chars.length) { return source.substring(start, length); } else { return source; } } /** * Prints out the constructed index */ public void printIndex(){ String result = "INDEX:\n"; result += "======\n"; result += myIndex.toString(); System.out.println(result); } /** * Prints out the words that were not included in the index. */ public void printExcludedWords(){ String result = "DICTIONARY of excluded words:\n"; result += "=============================\n"; result += myDictionary.toString(); System.out.println(result); } }
3,773
0.635494
0.630978
141
25.687943
24.224756
99
false
false
0
0
0
0
0
0
2.212766
false
false
14
22bfe05b2a40136119a4d2695b97c95c32a69bea
11,081,015,680,756
2d6d240d0dd256b2d28d93af6640ec0058200ab9
/DSLs/kafka/model/src/main/java-gen/com/fkorotkov/kubernetes/kafka/Schema.java
e8e132184fb71b206ecfb972d8ea8bb50c4a1c36
[ "MIT" ]
permissive
woxiehaode/k8s-kotlin-dsl
https://github.com/woxiehaode/k8s-kotlin-dsl
5b591e318ad388159452655e1ed356ec772f5f47
5caafecc9948817feadb977069091e111012b45a
refs/heads/master
2022-06-23T04:35:19.151000
2020-05-13T18:21:29
2020-05-13T18:21:29
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.fkorotkov.kubernetes.kafka; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyDescription; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import io.fabric8.kubernetes.api.model.Doneable; import io.fabric8.kubernetes.api.model.ObjectMeta; import io.sundr.builder.annotations.Buildable; import io.sundr.builder.annotations.BuildableReference; import io.sundr.builder.annotations.Inline; import lombok.EqualsAndHashCode; import lombok.ToString; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "annotations", "authentication", "brokerEndpoints", "configOverrides", "envVar", "initContainer", "jvmConfig", "kafkaCluster", "kafkaClusterList", "limits", "metricReporter", "network", "nodeAffinity", "options", "placement", "podSecurityContext", "rack", "requests", "resources", "seLinuxOptions", "spec", "status", "storage", "sysctl", "tls", "zookeeper" }) @JsonDeserialize(using = com.fasterxml.jackson.databind.JsonDeserializer.None.class) @ToString @EqualsAndHashCode @Buildable(editableEnabled = false, validationEnabled = false, generateBuilderPackage = false, builderPackage = "io.fabric8.kubernetes.api.builder", inline = { @Inline(type = Doneable.class, prefix = "Doneable", value = "done") }, refs = { @BuildableReference(ObjectMeta.class) }) public class Schema { /** * */ @JsonProperty("annotations") @JsonPropertyDescription("") private Annotations annotations; /** * */ @JsonProperty("authentication") @JsonPropertyDescription("") private Authentication authentication; /** * */ @JsonProperty("brokerEndpoints") @JsonPropertyDescription("") private BrokerEndpoints brokerEndpoints; /** * */ @JsonProperty("configOverrides") @JsonPropertyDescription("") private ConfigOverrides configOverrides; /** * */ @JsonProperty("envVar") @JsonPropertyDescription("") private EnvVar envVar; /** * */ @JsonProperty("initContainer") @JsonPropertyDescription("") private InitContainer initContainer; /** * */ @JsonProperty("jvmConfig") @JsonPropertyDescription("") private JvmConfig jvmConfig; /** * */ @JsonProperty("kafkaCluster") @JsonPropertyDescription("") private KafkaCluster kafkaCluster; /** * */ @JsonProperty("kafkaClusterList") @JsonPropertyDescription("") private KafkaClusterList kafkaClusterList; /** * */ @JsonProperty("limits") @JsonPropertyDescription("") private Limits limits; /** * */ @JsonProperty("metricReporter") @JsonPropertyDescription("") private MetricReporter metricReporter; /** * */ @JsonProperty("network") @JsonPropertyDescription("") private Network network; /** * */ @JsonProperty("nodeAffinity") @JsonPropertyDescription("") private NodeAffinity nodeAffinity; /** * */ @JsonProperty("options") @JsonPropertyDescription("") private Options options; /** * */ @JsonProperty("placement") @JsonPropertyDescription("") private Placement placement; /** * */ @JsonProperty("podSecurityContext") @JsonPropertyDescription("") private PodSecurityContext podSecurityContext; /** * */ @JsonProperty("rack") @JsonPropertyDescription("") private Rack rack; /** * */ @JsonProperty("requests") @JsonPropertyDescription("") private Requests requests; /** * */ @JsonProperty("resources") @JsonPropertyDescription("") private Resources resources; /** * */ @JsonProperty("seLinuxOptions") @JsonPropertyDescription("") private SeLinuxOptions seLinuxOptions; /** * */ @JsonProperty("spec") @JsonPropertyDescription("") private Spec spec; /** * */ @JsonProperty("status") @JsonPropertyDescription("") private Status status; /** * */ @JsonProperty("storage") @JsonPropertyDescription("") private Storage storage; /** * */ @JsonProperty("sysctl") @JsonPropertyDescription("") private Sysctl sysctl; /** * */ @JsonProperty("tls") @JsonPropertyDescription("") private Tls tls; /** * */ @JsonProperty("zookeeper") @JsonPropertyDescription("") private Zookeeper zookeeper; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); /** * No args constructor for use in serialization * */ public Schema() { } /** * * @param metricReporter * @param seLinuxOptions * @param podSecurityContext * @param annotations * @param initContainer * @param requests * @param storage * @param spec * @param jvmConfig * @param network * @param options * @param kafkaClusterList * @param limits * @param authentication * @param rack * @param envVar * @param zookeeper * @param resources * @param nodeAffinity * @param sysctl * @param configOverrides * @param brokerEndpoints * @param tls * @param placement * @param kafkaCluster * @param status */ public Schema(Annotations annotations, Authentication authentication, BrokerEndpoints brokerEndpoints, ConfigOverrides configOverrides, EnvVar envVar, InitContainer initContainer, JvmConfig jvmConfig, KafkaCluster kafkaCluster, KafkaClusterList kafkaClusterList, Limits limits, MetricReporter metricReporter, Network network, NodeAffinity nodeAffinity, Options options, Placement placement, PodSecurityContext podSecurityContext, Rack rack, Requests requests, Resources resources, SeLinuxOptions seLinuxOptions, Spec spec, Status status, Storage storage, Sysctl sysctl, Tls tls, Zookeeper zookeeper) { super(); this.annotations = annotations; this.authentication = authentication; this.brokerEndpoints = brokerEndpoints; this.configOverrides = configOverrides; this.envVar = envVar; this.initContainer = initContainer; this.jvmConfig = jvmConfig; this.kafkaCluster = kafkaCluster; this.kafkaClusterList = kafkaClusterList; this.limits = limits; this.metricReporter = metricReporter; this.network = network; this.nodeAffinity = nodeAffinity; this.options = options; this.placement = placement; this.podSecurityContext = podSecurityContext; this.rack = rack; this.requests = requests; this.resources = resources; this.seLinuxOptions = seLinuxOptions; this.spec = spec; this.status = status; this.storage = storage; this.sysctl = sysctl; this.tls = tls; this.zookeeper = zookeeper; } /** * */ @JsonProperty("annotations") public Annotations getAnnotations() { return annotations; } /** * */ @JsonProperty("annotations") public void setAnnotations(Annotations annotations) { this.annotations = annotations; } /** * */ @JsonProperty("authentication") public Authentication getAuthentication() { return authentication; } /** * */ @JsonProperty("authentication") public void setAuthentication(Authentication authentication) { this.authentication = authentication; } /** * */ @JsonProperty("brokerEndpoints") public BrokerEndpoints getBrokerEndpoints() { return brokerEndpoints; } /** * */ @JsonProperty("brokerEndpoints") public void setBrokerEndpoints(BrokerEndpoints brokerEndpoints) { this.brokerEndpoints = brokerEndpoints; } /** * */ @JsonProperty("configOverrides") public ConfigOverrides getConfigOverrides() { return configOverrides; } /** * */ @JsonProperty("configOverrides") public void setConfigOverrides(ConfigOverrides configOverrides) { this.configOverrides = configOverrides; } /** * */ @JsonProperty("envVar") public EnvVar getEnvVar() { return envVar; } /** * */ @JsonProperty("envVar") public void setEnvVar(EnvVar envVar) { this.envVar = envVar; } /** * */ @JsonProperty("initContainer") public InitContainer getInitContainer() { return initContainer; } /** * */ @JsonProperty("initContainer") public void setInitContainer(InitContainer initContainer) { this.initContainer = initContainer; } /** * */ @JsonProperty("jvmConfig") public JvmConfig getJvmConfig() { return jvmConfig; } /** * */ @JsonProperty("jvmConfig") public void setJvmConfig(JvmConfig jvmConfig) { this.jvmConfig = jvmConfig; } /** * */ @JsonProperty("kafkaCluster") public KafkaCluster getKafkaCluster() { return kafkaCluster; } /** * */ @JsonProperty("kafkaCluster") public void setKafkaCluster(KafkaCluster kafkaCluster) { this.kafkaCluster = kafkaCluster; } /** * */ @JsonProperty("kafkaClusterList") public KafkaClusterList getKafkaClusterList() { return kafkaClusterList; } /** * */ @JsonProperty("kafkaClusterList") public void setKafkaClusterList(KafkaClusterList kafkaClusterList) { this.kafkaClusterList = kafkaClusterList; } /** * */ @JsonProperty("limits") public Limits getLimits() { return limits; } /** * */ @JsonProperty("limits") public void setLimits(Limits limits) { this.limits = limits; } /** * */ @JsonProperty("metricReporter") public MetricReporter getMetricReporter() { return metricReporter; } /** * */ @JsonProperty("metricReporter") public void setMetricReporter(MetricReporter metricReporter) { this.metricReporter = metricReporter; } /** * */ @JsonProperty("network") public Network getNetwork() { return network; } /** * */ @JsonProperty("network") public void setNetwork(Network network) { this.network = network; } /** * */ @JsonProperty("nodeAffinity") public NodeAffinity getNodeAffinity() { return nodeAffinity; } /** * */ @JsonProperty("nodeAffinity") public void setNodeAffinity(NodeAffinity nodeAffinity) { this.nodeAffinity = nodeAffinity; } /** * */ @JsonProperty("options") public Options getOptions() { return options; } /** * */ @JsonProperty("options") public void setOptions(Options options) { this.options = options; } /** * */ @JsonProperty("placement") public Placement getPlacement() { return placement; } /** * */ @JsonProperty("placement") public void setPlacement(Placement placement) { this.placement = placement; } /** * */ @JsonProperty("podSecurityContext") public PodSecurityContext getPodSecurityContext() { return podSecurityContext; } /** * */ @JsonProperty("podSecurityContext") public void setPodSecurityContext(PodSecurityContext podSecurityContext) { this.podSecurityContext = podSecurityContext; } /** * */ @JsonProperty("rack") public Rack getRack() { return rack; } /** * */ @JsonProperty("rack") public void setRack(Rack rack) { this.rack = rack; } /** * */ @JsonProperty("requests") public Requests getRequests() { return requests; } /** * */ @JsonProperty("requests") public void setRequests(Requests requests) { this.requests = requests; } /** * */ @JsonProperty("resources") public Resources getResources() { return resources; } /** * */ @JsonProperty("resources") public void setResources(Resources resources) { this.resources = resources; } /** * */ @JsonProperty("seLinuxOptions") public SeLinuxOptions getSeLinuxOptions() { return seLinuxOptions; } /** * */ @JsonProperty("seLinuxOptions") public void setSeLinuxOptions(SeLinuxOptions seLinuxOptions) { this.seLinuxOptions = seLinuxOptions; } /** * */ @JsonProperty("spec") public Spec getSpec() { return spec; } /** * */ @JsonProperty("spec") public void setSpec(Spec spec) { this.spec = spec; } /** * */ @JsonProperty("status") public Status getStatus() { return status; } /** * */ @JsonProperty("status") public void setStatus(Status status) { this.status = status; } /** * */ @JsonProperty("storage") public Storage getStorage() { return storage; } /** * */ @JsonProperty("storage") public void setStorage(Storage storage) { this.storage = storage; } /** * */ @JsonProperty("sysctl") public Sysctl getSysctl() { return sysctl; } /** * */ @JsonProperty("sysctl") public void setSysctl(Sysctl sysctl) { this.sysctl = sysctl; } /** * */ @JsonProperty("tls") public Tls getTls() { return tls; } /** * */ @JsonProperty("tls") public void setTls(Tls tls) { this.tls = tls; } /** * */ @JsonProperty("zookeeper") public Zookeeper getZookeeper() { return zookeeper; } /** * */ @JsonProperty("zookeeper") public void setZookeeper(Zookeeper zookeeper) { this.zookeeper = zookeeper; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } }
UTF-8
Java
15,146
java
Schema.java
Java
[ { "context": "\npackage com.fkorotkov.kubernetes.kafka;\n\nimport java.util.HashMa", "end": 15, "score": 0.6139136552810669, "start": 13, "tag": "USERNAME", "value": "fk" } ]
null
[]
package com.fkorotkov.kubernetes.kafka; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyDescription; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import io.fabric8.kubernetes.api.model.Doneable; import io.fabric8.kubernetes.api.model.ObjectMeta; import io.sundr.builder.annotations.Buildable; import io.sundr.builder.annotations.BuildableReference; import io.sundr.builder.annotations.Inline; import lombok.EqualsAndHashCode; import lombok.ToString; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "annotations", "authentication", "brokerEndpoints", "configOverrides", "envVar", "initContainer", "jvmConfig", "kafkaCluster", "kafkaClusterList", "limits", "metricReporter", "network", "nodeAffinity", "options", "placement", "podSecurityContext", "rack", "requests", "resources", "seLinuxOptions", "spec", "status", "storage", "sysctl", "tls", "zookeeper" }) @JsonDeserialize(using = com.fasterxml.jackson.databind.JsonDeserializer.None.class) @ToString @EqualsAndHashCode @Buildable(editableEnabled = false, validationEnabled = false, generateBuilderPackage = false, builderPackage = "io.fabric8.kubernetes.api.builder", inline = { @Inline(type = Doneable.class, prefix = "Doneable", value = "done") }, refs = { @BuildableReference(ObjectMeta.class) }) public class Schema { /** * */ @JsonProperty("annotations") @JsonPropertyDescription("") private Annotations annotations; /** * */ @JsonProperty("authentication") @JsonPropertyDescription("") private Authentication authentication; /** * */ @JsonProperty("brokerEndpoints") @JsonPropertyDescription("") private BrokerEndpoints brokerEndpoints; /** * */ @JsonProperty("configOverrides") @JsonPropertyDescription("") private ConfigOverrides configOverrides; /** * */ @JsonProperty("envVar") @JsonPropertyDescription("") private EnvVar envVar; /** * */ @JsonProperty("initContainer") @JsonPropertyDescription("") private InitContainer initContainer; /** * */ @JsonProperty("jvmConfig") @JsonPropertyDescription("") private JvmConfig jvmConfig; /** * */ @JsonProperty("kafkaCluster") @JsonPropertyDescription("") private KafkaCluster kafkaCluster; /** * */ @JsonProperty("kafkaClusterList") @JsonPropertyDescription("") private KafkaClusterList kafkaClusterList; /** * */ @JsonProperty("limits") @JsonPropertyDescription("") private Limits limits; /** * */ @JsonProperty("metricReporter") @JsonPropertyDescription("") private MetricReporter metricReporter; /** * */ @JsonProperty("network") @JsonPropertyDescription("") private Network network; /** * */ @JsonProperty("nodeAffinity") @JsonPropertyDescription("") private NodeAffinity nodeAffinity; /** * */ @JsonProperty("options") @JsonPropertyDescription("") private Options options; /** * */ @JsonProperty("placement") @JsonPropertyDescription("") private Placement placement; /** * */ @JsonProperty("podSecurityContext") @JsonPropertyDescription("") private PodSecurityContext podSecurityContext; /** * */ @JsonProperty("rack") @JsonPropertyDescription("") private Rack rack; /** * */ @JsonProperty("requests") @JsonPropertyDescription("") private Requests requests; /** * */ @JsonProperty("resources") @JsonPropertyDescription("") private Resources resources; /** * */ @JsonProperty("seLinuxOptions") @JsonPropertyDescription("") private SeLinuxOptions seLinuxOptions; /** * */ @JsonProperty("spec") @JsonPropertyDescription("") private Spec spec; /** * */ @JsonProperty("status") @JsonPropertyDescription("") private Status status; /** * */ @JsonProperty("storage") @JsonPropertyDescription("") private Storage storage; /** * */ @JsonProperty("sysctl") @JsonPropertyDescription("") private Sysctl sysctl; /** * */ @JsonProperty("tls") @JsonPropertyDescription("") private Tls tls; /** * */ @JsonProperty("zookeeper") @JsonPropertyDescription("") private Zookeeper zookeeper; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); /** * No args constructor for use in serialization * */ public Schema() { } /** * * @param metricReporter * @param seLinuxOptions * @param podSecurityContext * @param annotations * @param initContainer * @param requests * @param storage * @param spec * @param jvmConfig * @param network * @param options * @param kafkaClusterList * @param limits * @param authentication * @param rack * @param envVar * @param zookeeper * @param resources * @param nodeAffinity * @param sysctl * @param configOverrides * @param brokerEndpoints * @param tls * @param placement * @param kafkaCluster * @param status */ public Schema(Annotations annotations, Authentication authentication, BrokerEndpoints brokerEndpoints, ConfigOverrides configOverrides, EnvVar envVar, InitContainer initContainer, JvmConfig jvmConfig, KafkaCluster kafkaCluster, KafkaClusterList kafkaClusterList, Limits limits, MetricReporter metricReporter, Network network, NodeAffinity nodeAffinity, Options options, Placement placement, PodSecurityContext podSecurityContext, Rack rack, Requests requests, Resources resources, SeLinuxOptions seLinuxOptions, Spec spec, Status status, Storage storage, Sysctl sysctl, Tls tls, Zookeeper zookeeper) { super(); this.annotations = annotations; this.authentication = authentication; this.brokerEndpoints = brokerEndpoints; this.configOverrides = configOverrides; this.envVar = envVar; this.initContainer = initContainer; this.jvmConfig = jvmConfig; this.kafkaCluster = kafkaCluster; this.kafkaClusterList = kafkaClusterList; this.limits = limits; this.metricReporter = metricReporter; this.network = network; this.nodeAffinity = nodeAffinity; this.options = options; this.placement = placement; this.podSecurityContext = podSecurityContext; this.rack = rack; this.requests = requests; this.resources = resources; this.seLinuxOptions = seLinuxOptions; this.spec = spec; this.status = status; this.storage = storage; this.sysctl = sysctl; this.tls = tls; this.zookeeper = zookeeper; } /** * */ @JsonProperty("annotations") public Annotations getAnnotations() { return annotations; } /** * */ @JsonProperty("annotations") public void setAnnotations(Annotations annotations) { this.annotations = annotations; } /** * */ @JsonProperty("authentication") public Authentication getAuthentication() { return authentication; } /** * */ @JsonProperty("authentication") public void setAuthentication(Authentication authentication) { this.authentication = authentication; } /** * */ @JsonProperty("brokerEndpoints") public BrokerEndpoints getBrokerEndpoints() { return brokerEndpoints; } /** * */ @JsonProperty("brokerEndpoints") public void setBrokerEndpoints(BrokerEndpoints brokerEndpoints) { this.brokerEndpoints = brokerEndpoints; } /** * */ @JsonProperty("configOverrides") public ConfigOverrides getConfigOverrides() { return configOverrides; } /** * */ @JsonProperty("configOverrides") public void setConfigOverrides(ConfigOverrides configOverrides) { this.configOverrides = configOverrides; } /** * */ @JsonProperty("envVar") public EnvVar getEnvVar() { return envVar; } /** * */ @JsonProperty("envVar") public void setEnvVar(EnvVar envVar) { this.envVar = envVar; } /** * */ @JsonProperty("initContainer") public InitContainer getInitContainer() { return initContainer; } /** * */ @JsonProperty("initContainer") public void setInitContainer(InitContainer initContainer) { this.initContainer = initContainer; } /** * */ @JsonProperty("jvmConfig") public JvmConfig getJvmConfig() { return jvmConfig; } /** * */ @JsonProperty("jvmConfig") public void setJvmConfig(JvmConfig jvmConfig) { this.jvmConfig = jvmConfig; } /** * */ @JsonProperty("kafkaCluster") public KafkaCluster getKafkaCluster() { return kafkaCluster; } /** * */ @JsonProperty("kafkaCluster") public void setKafkaCluster(KafkaCluster kafkaCluster) { this.kafkaCluster = kafkaCluster; } /** * */ @JsonProperty("kafkaClusterList") public KafkaClusterList getKafkaClusterList() { return kafkaClusterList; } /** * */ @JsonProperty("kafkaClusterList") public void setKafkaClusterList(KafkaClusterList kafkaClusterList) { this.kafkaClusterList = kafkaClusterList; } /** * */ @JsonProperty("limits") public Limits getLimits() { return limits; } /** * */ @JsonProperty("limits") public void setLimits(Limits limits) { this.limits = limits; } /** * */ @JsonProperty("metricReporter") public MetricReporter getMetricReporter() { return metricReporter; } /** * */ @JsonProperty("metricReporter") public void setMetricReporter(MetricReporter metricReporter) { this.metricReporter = metricReporter; } /** * */ @JsonProperty("network") public Network getNetwork() { return network; } /** * */ @JsonProperty("network") public void setNetwork(Network network) { this.network = network; } /** * */ @JsonProperty("nodeAffinity") public NodeAffinity getNodeAffinity() { return nodeAffinity; } /** * */ @JsonProperty("nodeAffinity") public void setNodeAffinity(NodeAffinity nodeAffinity) { this.nodeAffinity = nodeAffinity; } /** * */ @JsonProperty("options") public Options getOptions() { return options; } /** * */ @JsonProperty("options") public void setOptions(Options options) { this.options = options; } /** * */ @JsonProperty("placement") public Placement getPlacement() { return placement; } /** * */ @JsonProperty("placement") public void setPlacement(Placement placement) { this.placement = placement; } /** * */ @JsonProperty("podSecurityContext") public PodSecurityContext getPodSecurityContext() { return podSecurityContext; } /** * */ @JsonProperty("podSecurityContext") public void setPodSecurityContext(PodSecurityContext podSecurityContext) { this.podSecurityContext = podSecurityContext; } /** * */ @JsonProperty("rack") public Rack getRack() { return rack; } /** * */ @JsonProperty("rack") public void setRack(Rack rack) { this.rack = rack; } /** * */ @JsonProperty("requests") public Requests getRequests() { return requests; } /** * */ @JsonProperty("requests") public void setRequests(Requests requests) { this.requests = requests; } /** * */ @JsonProperty("resources") public Resources getResources() { return resources; } /** * */ @JsonProperty("resources") public void setResources(Resources resources) { this.resources = resources; } /** * */ @JsonProperty("seLinuxOptions") public SeLinuxOptions getSeLinuxOptions() { return seLinuxOptions; } /** * */ @JsonProperty("seLinuxOptions") public void setSeLinuxOptions(SeLinuxOptions seLinuxOptions) { this.seLinuxOptions = seLinuxOptions; } /** * */ @JsonProperty("spec") public Spec getSpec() { return spec; } /** * */ @JsonProperty("spec") public void setSpec(Spec spec) { this.spec = spec; } /** * */ @JsonProperty("status") public Status getStatus() { return status; } /** * */ @JsonProperty("status") public void setStatus(Status status) { this.status = status; } /** * */ @JsonProperty("storage") public Storage getStorage() { return storage; } /** * */ @JsonProperty("storage") public void setStorage(Storage storage) { this.storage = storage; } /** * */ @JsonProperty("sysctl") public Sysctl getSysctl() { return sysctl; } /** * */ @JsonProperty("sysctl") public void setSysctl(Sysctl sysctl) { this.sysctl = sysctl; } /** * */ @JsonProperty("tls") public Tls getTls() { return tls; } /** * */ @JsonProperty("tls") public void setTls(Tls tls) { this.tls = tls; } /** * */ @JsonProperty("zookeeper") public Zookeeper getZookeeper() { return zookeeper; } /** * */ @JsonProperty("zookeeper") public void setZookeeper(Zookeeper zookeeper) { this.zookeeper = zookeeper; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } }
15,146
0.597319
0.597121
711
20.300985
28.006168
605
false
false
0
0
0
0
0
0
0.264416
false
false
14
a42890f09e29cffcfc8b94d31155bf292af2122d
28,346,784,217,964
5c2d47a1a641af5a3c4bfbb771b0c957ca21bfa7
/app/src/main/java/com/suki/bnk48profile/MainActivity.java
cad618669e90d785854838e9000568c45c131092
[]
no_license
khichi0104/bnk48profile
https://github.com/khichi0104/bnk48profile
d3d2bf1677cba3eac5715953c253eab7e649e727
3023f2f41f5c8b9a1e9341050a862f9dd112ed5c
refs/heads/master
2021-01-19T23:21:32.403000
2017-04-21T09:58:32
2017-04-21T09:58:32
88,969,385
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.suki.bnk48profile; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity { TextView txvLogo; Button btnLogo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); txvLogo = (TextView)findViewById(R.id.txvLogo); btnLogo = (Button)findViewById(R.id.btnLogo); final Context context = this; btnLogo.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { txvLogo.setTextColor(Color.BLACK); Intent intent = new Intent(context,Main2Activity.class); startActivity(intent); } }); } }
UTF-8
Java
1,027
java
MainActivity.java
Java
[]
null
[]
package com.suki.bnk48profile; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity { TextView txvLogo; Button btnLogo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); txvLogo = (TextView)findViewById(R.id.txvLogo); btnLogo = (Button)findViewById(R.id.btnLogo); final Context context = this; btnLogo.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { txvLogo.setTextColor(Color.BLACK); Intent intent = new Intent(context,Main2Activity.class); startActivity(intent); } }); } }
1,027
0.680623
0.676728
37
26.756756
20.869486
72
false
false
0
0
0
0
0
0
0.567568
false
false
14
270b73d33da71d1f0be46c1e8c2fba02bff61997
5,394,478,971,871
83b99dd19c2b82a203f4d8956c5c91a8749cc62e
/src/top/codingma/leetcode/leet559/Solution.java
8bae913a8399c2c1a9c379d83ed0139a7b5bd3cd
[]
no_license
codingbyma/leet
https://github.com/codingbyma/leet
fe1e54a9cb907c3b0f2c23240b83dd6c6b279023
d0e1865b01551db6637b86fab341a3b5403671f2
refs/heads/master
2020-05-31T21:00:37.726000
2019-06-24T07:18:56
2019-06-24T07:18:56
190,488,353
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package top.codingma.leetcode.leet559; import java.util.List; class Node { public int val; public List<Node> children; public Node() {} public Node(int _val, List<Node> _children) { val = _val; children = _children; } } class Solution { int maxH=0; public int maxDepth(Node root) { if (root==null){ return 0; } dfs(root,1); return maxH; } void dfs(Node root,int curDepth){ maxH=Math.max(maxH,curDepth); if (root==null||root.children==null||root.children.size()==0){ return; } for (Node node:root.children){ dfs(node,curDepth+1); } } }
UTF-8
Java
706
java
Solution.java
Java
[]
null
[]
package top.codingma.leetcode.leet559; import java.util.List; class Node { public int val; public List<Node> children; public Node() {} public Node(int _val, List<Node> _children) { val = _val; children = _children; } } class Solution { int maxH=0; public int maxDepth(Node root) { if (root==null){ return 0; } dfs(root,1); return maxH; } void dfs(Node root,int curDepth){ maxH=Math.max(maxH,curDepth); if (root==null||root.children==null||root.children.size()==0){ return; } for (Node node:root.children){ dfs(node,curDepth+1); } } }
706
0.532578
0.521246
38
17.605263
16.274843
70
false
false
0
0
0
0
0
0
0.578947
false
false
14
cb1d204f0170ff188277a042140b8b7a6169aba5
7,318,624,342,170
95a026a7fa118f0ea421358554494ba1bf086ecf
/web/src/main/java/com/vlogs/web/Controller/UserController.java
83159da46c74a2f1bd8e15d9d6e28b7b095ae2c6
[]
no_license
kolanan/wefun
https://github.com/kolanan/wefun
7c69289937509d28579731e9ce4911ae0d10d5ce
74f39a2ccfd5fb87ee91ffabaedf12cdaee2ca12
refs/heads/master
2021-04-15T14:48:52.581000
2018-03-21T14:21:00
2018-03-21T14:21:00
126,188,819
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.vlogs.web.Controller; import com.vlogs.web.Service.UserService; import com.vlogs.web.domain.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * Created by nan on 2018/3/21 21:22 */ @RestController public class UserController { @Autowired UserService userService; @RequestMapping("/user/{id}") public User getUser(@PathVariable Integer id){ return userService.findUserById(id); } }
UTF-8
Java
647
java
UserController.java
Java
[ { "context": "bind.annotation.RestController;\n\n/**\n * Created by nan on 2018/3/21 21:22\n */\n@RestController\npublic cla", "end": 383, "score": 0.9463778734207153, "start": 380, "tag": "USERNAME", "value": "nan" } ]
null
[]
package com.vlogs.web.Controller; import com.vlogs.web.Service.UserService; import com.vlogs.web.domain.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * Created by nan on 2018/3/21 21:22 */ @RestController public class UserController { @Autowired UserService userService; @RequestMapping("/user/{id}") public User getUser(@PathVariable Integer id){ return userService.findUserById(id); } }
647
0.760433
0.743431
25
24.879999
22.987509
62
false
false
0
0
0
0
0
0
0.36
false
false
14
f996b2b70ce1560d9065c320ce0093a12b870c19
28,845,000,421,070
308d4cb3d43231cba48900b2a3ddca510c9f1d82
/src/main/java/com/appcrews/javaee/maicai/dal/ShopImpl.java
f20791c967410d9d070a2e3dc9588f77c848713a
[]
no_license
wlancer1/Manage
https://github.com/wlancer1/Manage
94674c77c490687a15f6dafebd26682641a51ecf
2b79e897a13388927bbc1f1c963ff1de1c7a892e
refs/heads/myweb
2023-06-21T18:33:52.241000
2022-07-21T07:38:17
2022-07-21T07:38:17
56,694,120
0
0
null
false
2023-04-15T14:04:51
2016-04-20T14:31:00
2022-07-21T07:38:21
2023-04-15T14:04:50
38,613
0
0
93
Java
false
false
package com.appcrews.javaee.maicai.dal; import com.appcrews.javaee.maicai.model.base.ShopInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import java.util.List; /** * Created by micheal on 2017/8/23. */ @Repository public class ShopImpl implements Shop { @Autowired BaseDaoI baseDaoI; @Override public List<ShopInfo> query(int uid) { String hql="from ShopInfo where uid ="+uid; return baseDaoI.find(hql); } @Override public List<ShopInfo> getListShop() { String hql="from ShopInfo"; return baseDaoI.find(hql); } @Override public int getLength() { String hql="SELECT COUNT(*) FROM ShopInfo"; return baseDaoI.count(hql); } }
UTF-8
Java
794
java
ShopImpl.java
Java
[ { "context": "sitory;\n\nimport java.util.List;\n\n/**\n * Created by micheal on 2017/8/23.\n */\n@Repository\npublic class ShopIm", "end": 259, "score": 0.9996429085731506, "start": 252, "tag": "USERNAME", "value": "micheal" } ]
null
[]
package com.appcrews.javaee.maicai.dal; import com.appcrews.javaee.maicai.model.base.ShopInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import java.util.List; /** * Created by micheal on 2017/8/23. */ @Repository public class ShopImpl implements Shop { @Autowired BaseDaoI baseDaoI; @Override public List<ShopInfo> query(int uid) { String hql="from ShopInfo where uid ="+uid; return baseDaoI.find(hql); } @Override public List<ShopInfo> getListShop() { String hql="from ShopInfo"; return baseDaoI.find(hql); } @Override public int getLength() { String hql="SELECT COUNT(*) FROM ShopInfo"; return baseDaoI.count(hql); } }
794
0.677582
0.668766
34
22.352942
19.253544
62
false
false
0
0
0
0
0
0
0.352941
false
false
14