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 list | 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 list | 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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
566307177e5b099ecd69b1536f28faae41786654 | 30,562,987,317,925 | ef02ceb89976eed1de90d4b11dff99dd2b4c628a | /IndigoDB/src/main/java/com/fire/core/dbcs/executor/BatchBean.java | 54bf1652515c4144610aad60d29f0dccf6aee719 | [] | no_license | x163maiaytang/Indigo | https://github.com/x163maiaytang/Indigo | ac37a3b583e081f8629ec571ce8727cfa3cc6786 | 5a2bdcc84b2a9925ab3e5936d6b116818100fae2 | refs/heads/master | 2020-03-29T08:20:05.217000 | 2018-12-06T06:23:08 | 2018-12-06T06:23:08 | 149,705,226 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.fire.core.dbcs.executor;
public class BatchBean {
private Object[] args;
private StatementProxy proxy;
public BatchBean(StatementProxy proxy, Object[] args) {
this.proxy = proxy;
this.args = args;
}
public Object[] getArgs() {
return args;
}
public StatementProxy getProxy() {
return proxy;
}
}
| UTF-8 | Java | 329 | java | BatchBean.java | Java | [] | null | [] | package com.fire.core.dbcs.executor;
public class BatchBean {
private Object[] args;
private StatementProxy proxy;
public BatchBean(StatementProxy proxy, Object[] args) {
this.proxy = proxy;
this.args = args;
}
public Object[] getArgs() {
return args;
}
public StatementProxy getProxy() {
return proxy;
}
}
| 329 | 0.702128 | 0.702128 | 21 | 14.666667 | 15.682363 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.142857 | false | false | 3 |
bcb9d2a2661d31c9bd1ffcddbae4513063a8426a | 13,151,189,881,265 | b54af8261c831803af813bf90e37d58f6bc6afeb | /src/main/java/com/dahantc/erp/vo/rolerelation/entity/RoleRelation.java | 63898d306154ca8088a99b7d5b4720aab3d1b77d | [] | no_license | jesonxu/ctc-erp | https://github.com/jesonxu/ctc-erp | c34165f83e297327551949816042a51e34a95093 | b83c85b1f6f51895051a2fbb5888598ee03dd815 | refs/heads/master | 2023-01-14T06:21:05.249000 | 2020-11-13T02:23:51 | 2020-11-13T02:23:51 | 312,448,611 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.dahantc.erp.vo.rolerelation.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name = "erp_role_relation")
@DynamicUpdate(true)
public class RoleRelation implements Serializable {
private static final long serialVersionUID = -4383842163439043317L;
@Id
@Column(name = "rolerelationid", length = 32)
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid")
private String roleRelationId;
/** 参数说明 **/
@Column(name = "roleid", length = 32)
private String roleId;
@Column(name = "ossuserid", length = 32)
private String ossUserId;
public String getOssUserId() {
return ossUserId;
}
public void setOssUserId(String ossUserId) {
this.ossUserId = ossUserId;
}
public String getRoleId() {
return roleId;
}
public void setRoleId(String roleId) {
this.roleId = roleId;
}
public String getRoleRelationId() {
return roleRelationId;
}
public void setRoleRelationId(String roleRelationId) {
this.roleRelationId = roleRelationId;
}
}
| UTF-8 | Java | 1,300 | java | RoleRelation.java | Java | [] | null | [] | package com.dahantc.erp.vo.rolerelation.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name = "erp_role_relation")
@DynamicUpdate(true)
public class RoleRelation implements Serializable {
private static final long serialVersionUID = -4383842163439043317L;
@Id
@Column(name = "rolerelationid", length = 32)
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid")
private String roleRelationId;
/** 参数说明 **/
@Column(name = "roleid", length = 32)
private String roleId;
@Column(name = "ossuserid", length = 32)
private String ossUserId;
public String getOssUserId() {
return ossUserId;
}
public void setOssUserId(String ossUserId) {
this.ossUserId = ossUserId;
}
public String getRoleId() {
return roleId;
}
public void setRoleId(String roleId) {
this.roleId = roleId;
}
public String getRoleRelationId() {
return roleRelationId;
}
public void setRoleRelationId(String roleRelationId) {
this.roleRelationId = roleRelationId;
}
}
| 1,300 | 0.760062 | 0.740712 | 56 | 22.071428 | 19.497122 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.035714 | false | false | 3 |
658405be89b030a7c90bb2dafcbfb00dca30d654 | 13,151,189,879,706 | 0c44da76a30138ebaee6700e2e33df5204ef21fc | /PODM/SW/resource-manager/runner/src/main/java/com/intel/rsd/resourcemanager/runner/requiredlayer/RequiredLayer.java | af73b5623c19dd0623241bfb75eebafdc4f64dff | [] | no_license | rwleea/intelRSD | https://github.com/rwleea/intelRSD | 263e4c86801792be88e528d30d5a1d3c85af3a62 | 8e404abc211211a2d49776b8e3bf07d108c4bd4b | refs/heads/master | 2023-02-20T22:26:07.222000 | 2022-08-04T22:08:00 | 2022-08-04T22:08:00 | 64,722,362 | 0 | 0 | null | true | 2016-08-02T03:49:59 | 2016-08-02T03:49:58 | 2016-08-02T03:37:03 | 2016-08-01T06:25:42 | 5,263 | 0 | 0 | 0 | null | null | null | /*
* Copyright (c) 2017-2019 Intel Corporation
*
* 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.intel.rsd.resourcemanager.runner.requiredlayer;
import com.fasterxml.jackson.databind.JsonNode;
import com.intel.rsd.collections.Lists;
import com.intel.rsd.resourcemanager.common.SouthboundConfig;
import com.intel.rsd.resourcemanager.layers.Layer;
import com.intel.rsd.resourcemanager.layers.Response;
import com.intel.rsd.resourcemanager.layers.ServiceId;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import static java.util.stream.Collectors.toMap;
import static org.springframework.http.HttpHeaders.EMPTY;
import static org.springframework.http.HttpStatus.SERVICE_UNAVAILABLE;
@Component
@Slf4j
public class RequiredLayer extends Layer {
private final RestClient restClient;
private final RequiredServiceFinder finder;
private final Collection<String> acceptedHeaders;
private final String basicAuthToken;
@Autowired
RequiredLayer(RestClient restClient, RequiredServiceFinder finder, SouthboundConfig southboundConfig) {
this.restClient = restClient;
this.finder = finder;
this.acceptedHeaders = southboundConfig.getAcceptedHeaders();
this.basicAuthToken = southboundConfig.getBasicAuthToken();
}
@Override
public Set<ServiceId> getServices() {
return finder.getServices();
}
@Override
protected Response invokeImpl(ServiceId serviceId, String path, HttpMethod method, HttpHeaders headers, JsonNode body,
Map<String, String> requestParams) {
val serviceHost = finder.findServiceHost(serviceId);
if (serviceHost == null) {
return serviceNotAvailableResponse();
}
val uri = serviceHost.resolve(path);
addBasicAuthHeaderIfNecessary(headers);
try {
Response response = restClient.call(uri, method, headers, body);
HttpHeaders httpHeaders = response.getHttpHeaders().entrySet().stream()
.filter(entry -> acceptedHeaders.contains(entry.getKey()))
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue, Lists::concat, HttpHeaders::new));
return new Response(response.getBody(), httpHeaders, response.getHttpStatus());
} catch (ServiceAccessException e) {
log.info("Service({}) unavailable: {}", serviceId, e.getMessage());
log.trace("Exception has been thrown during accessing URI({}) on service({})", path, serviceId, e);
return serviceNotAvailableResponse();
}
}
private Response serviceNotAvailableResponse() {
return new Response(null, EMPTY, SERVICE_UNAVAILABLE);
}
private void addBasicAuthHeaderIfNecessary(@NonNull HttpHeaders headers) {
if (basicAuthToken != null && !basicAuthToken.isEmpty()) {
headers.add("Authorization", "Basic " + basicAuthToken);
}
}
}
| UTF-8 | Java | 3,766 | java | RequiredLayer.java | Java | [] | null | [] | /*
* Copyright (c) 2017-2019 Intel Corporation
*
* 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.intel.rsd.resourcemanager.runner.requiredlayer;
import com.fasterxml.jackson.databind.JsonNode;
import com.intel.rsd.collections.Lists;
import com.intel.rsd.resourcemanager.common.SouthboundConfig;
import com.intel.rsd.resourcemanager.layers.Layer;
import com.intel.rsd.resourcemanager.layers.Response;
import com.intel.rsd.resourcemanager.layers.ServiceId;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import static java.util.stream.Collectors.toMap;
import static org.springframework.http.HttpHeaders.EMPTY;
import static org.springframework.http.HttpStatus.SERVICE_UNAVAILABLE;
@Component
@Slf4j
public class RequiredLayer extends Layer {
private final RestClient restClient;
private final RequiredServiceFinder finder;
private final Collection<String> acceptedHeaders;
private final String basicAuthToken;
@Autowired
RequiredLayer(RestClient restClient, RequiredServiceFinder finder, SouthboundConfig southboundConfig) {
this.restClient = restClient;
this.finder = finder;
this.acceptedHeaders = southboundConfig.getAcceptedHeaders();
this.basicAuthToken = southboundConfig.getBasicAuthToken();
}
@Override
public Set<ServiceId> getServices() {
return finder.getServices();
}
@Override
protected Response invokeImpl(ServiceId serviceId, String path, HttpMethod method, HttpHeaders headers, JsonNode body,
Map<String, String> requestParams) {
val serviceHost = finder.findServiceHost(serviceId);
if (serviceHost == null) {
return serviceNotAvailableResponse();
}
val uri = serviceHost.resolve(path);
addBasicAuthHeaderIfNecessary(headers);
try {
Response response = restClient.call(uri, method, headers, body);
HttpHeaders httpHeaders = response.getHttpHeaders().entrySet().stream()
.filter(entry -> acceptedHeaders.contains(entry.getKey()))
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue, Lists::concat, HttpHeaders::new));
return new Response(response.getBody(), httpHeaders, response.getHttpStatus());
} catch (ServiceAccessException e) {
log.info("Service({}) unavailable: {}", serviceId, e.getMessage());
log.trace("Exception has been thrown during accessing URI({}) on service({})", path, serviceId, e);
return serviceNotAvailableResponse();
}
}
private Response serviceNotAvailableResponse() {
return new Response(null, EMPTY, SERVICE_UNAVAILABLE);
}
private void addBasicAuthHeaderIfNecessary(@NonNull HttpHeaders headers) {
if (basicAuthToken != null && !basicAuthToken.isEmpty()) {
headers.add("Authorization", "Basic " + basicAuthToken);
}
}
}
| 3,766 | 0.719065 | 0.715082 | 99 | 37.040405 | 30.733103 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.707071 | false | false | 3 |
0bcd6098ef052bb4d58805cc72b3975da9db9694 | 35,502,199,668,994 | 2c5aca1abd0952a29118c1ca8a98da3d7573b9c4 | /src/main/java/com/zbl/algorithm/practice/_02/Test001.java | e316b7a56ad20c3fb370a9a2b65a68b9b4104d7a | [] | no_license | ZBL0507/mycode | https://github.com/ZBL0507/mycode | bfb8e258b8409660652b8dd7e1a44775a6ffc281 | 3e360cdb47b09506fbea03908ff82306628f8c2a | refs/heads/master | 2022-12-28T11:52:29.832000 | 2022-12-25T04:22:06 | 2022-12-25T04:22:06 | 267,891,277 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zbl.algorithm.practice._02;
import java.util.Scanner;
/**
* @author zbl
* @version 1.0
* @since 2022/2/16 9:26
* <p>
* <p>
* 写出一个程序,接受一个正浮点数值,输出该数值的近似整数值。如果小数点后数值大于等于 0.5 ,向上取整;小于 0.5 ,则向下取整。
* 数据范围:保证输入的数字在 32 位浮点数范围内
* <p>
* 输入描述:
* 输入一个正浮点数值
* <p>
* 输出描述:
* 输出该数值的近似整数值
* <p>
* 示例1
* 输入:
* 5.5
* 输出:
* 6
* 说明:
* 0.5>=0.5,所以5.5需要向上取整为6
* <p>
* 示例2
* 输入:
* 2.499
* 输出:
* 2
* 复制
* 0.499 < 0.5,2.499向下取整为2
*/
public class Test001 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
float aFloat = scanner.nextFloat();
int result = (int) (aFloat + 0.5);
System.out.println(result);
}
}
| UTF-8 | Java | 985 | java | Test001.java | Java | [
{
"context": "ce._02;\n\nimport java.util.Scanner;\n\n/**\n * @author zbl\n * @version 1.0\n * @since 2022/2/16 9:26\n * <p>\n ",
"end": 86,
"score": 0.9995791912078857,
"start": 83,
"tag": "USERNAME",
"value": "zbl"
}
] | null | [] | package com.zbl.algorithm.practice._02;
import java.util.Scanner;
/**
* @author zbl
* @version 1.0
* @since 2022/2/16 9:26
* <p>
* <p>
* 写出一个程序,接受一个正浮点数值,输出该数值的近似整数值。如果小数点后数值大于等于 0.5 ,向上取整;小于 0.5 ,则向下取整。
* 数据范围:保证输入的数字在 32 位浮点数范围内
* <p>
* 输入描述:
* 输入一个正浮点数值
* <p>
* 输出描述:
* 输出该数值的近似整数值
* <p>
* 示例1
* 输入:
* 5.5
* 输出:
* 6
* 说明:
* 0.5>=0.5,所以5.5需要向上取整为6
* <p>
* 示例2
* 输入:
* 2.499
* 输出:
* 2
* 复制
* 0.499 < 0.5,2.499向下取整为2
*/
public class Test001 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
float aFloat = scanner.nextFloat();
int result = (int) (aFloat + 0.5);
System.out.println(result);
}
}
| 985 | 0.57204 | 0.496434 | 43 | 15.302325 | 15.745852 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.162791 | false | false | 3 |
85c2a05cb36b871955cd03022268e788cb8812b4 | 10,651,518,929,100 | ec12e8aee6b44874a9401ded3d4625808abdb391 | /src/main/java/pub/timelyrain/logmining/biz/ExtractService.java | 24c13c44eaf648b14f4591a24beacee767d02ce1 | [] | no_license | timelyrain80/oracle-logmining | https://github.com/timelyrain80/oracle-logmining | e42961866f605eb202c20d98e1e7736850be978e | 4973b5fded27f9f8c821591c12db0af801c48413 | refs/heads/master | 2023-08-27T02:55:00.063000 | 2021-10-15T06:02:27 | 2021-10-15T06:02:27 | 307,120,313 | 0 | 1 | null | false | 2021-06-18T04:28:38 | 2020-10-25T14:44:38 | 2021-06-18T04:28:02 | 2021-06-18T04:28:37 | 212 | 0 | 1 | 0 | Java | false | false | package pub.timelyrain.logmining.biz;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import pub.timelyrain.logmining.config.Env;
import pub.timelyrain.logmining.pojo.MiningState;
import pub.timelyrain.logmining.pojo.RedoLog;
import pub.timelyrain.logmining.utils.TimeUtil;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static pub.timelyrain.logmining.biz.Constants.*;
@Component
@Scope("prototype")
public class ExtractService extends Thread {
private static final Logger log = LogManager.getLogger(ExtractService.class);
private static final Logger trlog = LogManager.getLogger("tracetr");
private final JdbcTemplate jdbcTemplate;
private final CounterService counterService;
private final Env env;
private final RedisTemplate redisTemplate;
@Autowired
public ExtractService(JdbcTemplate jdbcTemplate, CounterService counterService, Env env, RedisTemplate redisTemplate) {
this.jdbcTemplate = jdbcTemplate;
this.counterService = counterService;
this.env = env;
this.redisTemplate = redisTemplate;
getFilePath();
}
private String miningSql;
private MiningState state;
private int currentThread;
private int hashid;
private String filePath;
@Override
public void run() {
log.debug("开始抓取 run ");
// 读取state的seq
state = loadState();
// 判断 seq 小于数据库 archivelog的的最小 seq 提示有数据丢失(抓取程序长时间未启动,而归档日志被清理掉了)
pollingCheck(state);
miningSql = buildMiningSql();
try {
hashid = jdbcTemplate.getDataSource().getConnection().hashCode();
log.info("getConnection hash 值:{}", hashid);
} catch (SQLException e) {
e.printStackTrace();
}
while (!Thread.interrupted()) {
// 判断该seq是否是最末尾,若是代表本次抓取的日志不完整,需要再次抓取该文件。若不是末尾seq ,则一次可以抓取完整的日志。保存一个fulllog 状态.
boolean completedLogFlag = checkCompletedLog(state);
// 从 seq 开始读取 archive log 或 redo log
try {
pollingData(state);
// 正常抓取完毕后,若fulllog=true,则seq+1 重复进行新日志抓取
if (completedLogFlag) {
log.info("日志 {} 读取完毕", state.getLastSequence());
state.nextLog();
}
} catch (Exception e) {
log.error("抓取数据出错》》》》》",e);
TimeUtil.sheep(1);
}
}
}
/**
* 检查当前的seq 是否是最新的日志,如果是最新的日志,表示该日志还可能被追加新的待抓取内容.需要重新读取
*
* @param state
* @return
*/
private boolean checkCompletedLog(MiningState state) {
//检查归档日志的最大seq是否大于当前日志编号
long maxSequence = jdbcTemplate.queryForObject(QUERY_MAX_SEQUENCE_ARCHIVED, Long.class, currentThread);
if (maxSequence > state.getLastSequence())
return true;
//检查online日志的最大seq是否大于当前日志编号
maxSequence = jdbcTemplate.queryForObject(QUERY_MAX_SEQUENCE_ONLINE, Long.class, currentThread);
if (maxSequence > state.getLastSequence())
return true;
return false;
}
/**
* 检查数据库的日志列表是否完整,并警告
*
* @param state
*/
private void pollingCheck(MiningState state) {
long minSequence = jdbcTemplate.queryForObject(QUERY_MIN_SEQUENCE_ARCHIVED, Long.class, currentThread);
if (minSequence > state.getLastSequence()) {
log.warn("\r\n");
log.warn("**********************************");
log.warn("请注意: 最后一次处理的日志编号为 {} , 数据库保存最久的日志编号为 {}, 存在数据丢失的情况", state.getLastSequence(), minSequence);
log.warn("**********************************");
log.warn("\r\n");
}
}
/**
* 读取上次运行时的结束同步信息.用于恢复同步.
*
* @return
*/
private MiningState loadState() {
try {
File stateFile = new File(filePath + currentThread + "_state.saved");
if (!stateFile.exists()) {
//初次启动,读取当前seq.
long seq = jdbcTemplate.queryForObject(QUERY_SEQUENCE, Long.class, currentThread);
log.info("未找到进度状态文件,从最新日志开始抓取,日志编号为 {} hash值:{}", seq, hashid);
return new MiningState(0, 0, seq, null);
}
String stateStr = FileUtils.readFileToString(stateFile, "utf-8");
ObjectMapper om = new ObjectMapper();
MiningState lastState = om.readValue(stateStr, MiningState.class);
log.info("读取状态文件信息为 {}", stateStr);
return lastState;
} catch (IOException e) {
log.error("读取进度状态错误", e);
throw new RuntimeException("读取进度状态错误");
}
}
/**
* 根据sequence 和 commitScn 抓取待同步数据.
*
* @param state
* @return
*/
private void pollingData(MiningState state) {
//获得seq对应的日志文件的位置,先从归档日志里判断
startLogFileMining(state);
//启动日志分析
jdbcTemplate.setFetchSize(500);
try {
//jdbcTemplate.update("create table save_" + state.getLastSequence() + "_" + state.getLastRowNum() + " as " + Constants.QUERY_REDO.replaceAll("\\?", String.valueOf(state.getLastRowNum())));
jdbcTemplate.query(Constants.QUERY_REDO, (rs) -> {
//读取事务id
String xid = rs.getString("XID");
int opCode = rs.getInt("OPERATION_CODE");
int rollback = rs.getInt("ROLLBACK");
if (1 == rollback)
return;
long rn = rs.getLong("RN");
//读取日志位置
long scn = rs.getLong("SCN");
long commitScn = rs.getLong("COMMIT_SCN");
String timestamp = rs.getTimestamp("TIMESTAMP").toString();
try {
//log.debug(scn);
//读取REDO
int csf = rs.getInt("CSF");
String schema = rs.getString("SEG_OWNER");
String rsId = rs.getString("RS_ID");
// trlog.info("{}\t{}\t{}", rn, rsId, state.getLastSequence());
String tableName = rs.getString("TABLE_NAME");
String redo = rs.getString("SQL_REDO");
String rowId = rs.getString("ROW_ID");
if (csf == 1) { //如果REDO被截断
while (rs.next() && !Thread.interrupted()) { //继续查询下一条REDO
redo += rs.getString("SQL_REDO");
if (0 == rs.getInt("CSF")) { //
csf = 0;
break; //退出循环
}
}
}
RedoLog redoLog = new RedoLog(schema, tableName, redo, rowId, scn, commitScn, timestamp, rn, xid, opCode, rsId);
traceChange(redoLog);
} finally {
// log.debug("成功完成读取REDO日志 并保存读取的结果的索引值 ");
saveMiningState(commitScn, rn, state.getLastSequence(), timestamp);
}
}, state.getLastRowNum()); //传入redo value,不重复读取日志。
//关闭日志分析
} catch (Exception e) {
log.error("读取LOG出错", e);
throw e;
} finally {
log.debug("停止分析REDO日志 {} ,hash值:{}", Constants.MINING_END, hashid);
jdbcTemplate.update(Constants.MINING_END);
}
}
private void startLogFileMining(MiningState state) {
loadLogFile(state.getLastSequence());
// for (int i = 1; i < env.getLogFileScaned(); i++) {
// try {
// loadLogFile(state.getLastSequence() - i);
// } catch (Exception e) {
// //为了避免日志切换造成数据丢失,同时加载两个连续的日志文件
// //如果未找到前一个日志,不处理异常
// }
// }
jdbcTemplate.update(Constants.MINING_START);
log.debug("开启日志,hash值:{}", hashid);
}
private void traceChange(RedoLog redoLog) {
//判断是否是提交opCode=6 或回滚opCode=36
if (7 == redoLog.getOpCode()) {
commitRedo(redoLog);
return;
} else if (36 == redoLog.getOpCode()) {
rollbackRedo(redoLog);
return;
} else if (1 == redoLog.getOpCode() || 2 == redoLog.getOpCode() || 3 == redoLog.getOpCode()) {
saveRedo(redoLog);
return;
} else if (5 == redoLog.getOpCode()) {
// todo 更新日志字典
}
}
private void saveRedo(RedoLog redoLog) {
if (!env.getScanTables().contains(redoLog.getSchema() + "." + redoLog.getTableName()))
return;
String txKey = "mining:xid:" + redoLog.getXid();
//新增、修改、删除
redisTemplate.opsForList().rightPush(txKey, redoLog);
log.debug("识别待提交数据,缓存成功 {}", redoLog.toString());
//计数
counterService.addCount();
}
private void commitRedo(RedoLog redoLog) {
String txKey = "mining:xid:" + redoLog.getXid();
long count = redisTemplate.opsForList().size(txKey);
log.info("识别提交标记 事务id为 {} 总数据条数 {}", redoLog.getXid(), count);
redisTemplate.opsForList().rightPush("mining:replicate", redoLog.getXid());
}
private void rollbackRedo(RedoLog redoLog) {
//根据事务id删除redis缓存的redelog
redisTemplate.delete("mining:xid:" + redoLog.getXid());
log.debug("识别回滚标记 事务id为 {}", redoLog.getXid());
}
private void loadLogFile(long sequence) {
String logFile;
boolean onlineLogFlag = false;
List<Map<String, Object>> result = jdbcTemplate.queryForList(QUERY_NAME_SEQUENCE_ARCHIVED, sequence, currentThread);
if (result.isEmpty()) {
result = jdbcTemplate.queryForList(QUERY_NAME_SEQUENCE_ONLINE, sequence, currentThread);
onlineLogFlag = true;
}
Assert.state(!result.isEmpty(), String.format("未找到编号为 %d 的日志文件地址", sequence));
logFile = (String) result.get(0).get("name");
if (StringUtils.isEmpty(logFile)) {
log.error("待挖掘的日志已被删除,请检查 hash值:{}", hashid);
return;
}
jdbcTemplate.update(ADD_LOGFILE, logFile);
log.debug("分析 {} 日志, 日志编号为 {}, 日志文件为 {}", (onlineLogFlag ? "online log" : "archive log"), sequence, logFile);
}
/**
* 保存同步位置.用于下次程序运行时,可以恢复到停止点.
*
* @param commitScn
* @param sequence
* @param timestamp
*/
private void saveMiningState(long commitScn, long redoValue, long sequence, String timestamp) {
state.setLastCommitScn(commitScn);
state.setLastRowNum(redoValue);
state.setLastSequence(sequence);
state.setLastTime(timestamp);
String stateStr = null;
try {
File state = new File("/"+filePath + currentThread + "_state.saved");
state.exists();
stateStr = new ObjectMapper().writeValueAsString(this.state);
FileUtils.writeStringToFile(state, stateStr, "UTF-8", false);
// log.debug("saved state {}", stateStr);
} catch (Exception e) {
log.error("写入传输状态错误,当前传输信息为 " + stateStr, e);
}
}
/**
* 根据系统类型生成文件路径
*/
void getFilePath (){
// 得到当前系统名称
String s = System.getProperties().get("os.name").toString();
// 如果是window 则 用相对路径 如果是liunx 则用 绝对路径
if(s.indexOf("windows")>-1 || s.indexOf("Windows")>-1){
this.filePath= "state/thread_";
}else {
this.filePath= "/state/thread_";
}
}
private String buildMiningSqlWhere() {
HashMap<String, String> tableGroup = new HashMap<>();
//将数据库名.表名的数组,转成 数据库名和表名的集合
for (String tb : env.getScanTables()) {
// if (field.contains("|")) {
// tb = field.substring(0, field.indexOf("|"));
// tb = tb.toUpperCase();
// String condition = field.substring(field.indexOf("|") + 1, field.length());
//
// } else {
// tb = field.toUpperCase();
// }
Assert.isTrue(tb.contains("."), "同步表名格式不符合 数据库名.表名 的格式(" + tb + ")");
Assert.isTrue(!tb.contains("\\*"), "同步表名格式不符合 不可以使用通配 *(" + tb + ")");
String schemaName = tb.split("\\.")[0]; // 数据库名.表名
String tableName = tb.split("\\.")[1]; // 数据库名.表名
String tablesIn = tableGroup.get(schemaName);
tablesIn = (tablesIn == null ? "'" + tableName + "'" : tablesIn + ",'" + tableName + "'");
tableGroup.put(schemaName, tablesIn);
}
StringBuilder sql = new StringBuilder();
for (String schemaName : tableGroup.keySet()) {
if (sql.length() != 0) sql.append(" or ");
String tablesIn = tableGroup.get(schemaName);
if (tablesIn.startsWith("*"))
sql.append(String.format(" SEG_OWNER = '%s' ", schemaName));
else
sql.append(String.format(" SEG_OWNER = '%s' and TABLE_NAME in (%s)", schemaName, tableGroup.get(schemaName)));
}
sql.insert(0, "( ").append(" )");
return sql.toString();
}
private String buildMiningSql() {
// StringBuilder sql = new StringBuilder();
// sql.insert(0, buildMiningSqlWhere());
// sql.insert(0, " AND ");
// sql.insert(0, Constants.QUERY_REDO);
String sql = String.format(Constants.QUERY_REDO2, buildMiningSqlWhere());
log.debug("日志查询的sql是 {}", sql.toString());
return sql.toString();
}
public int getCurrentThread() {
return currentThread;
}
public void setCurrentThread(int currentThread) {
this.currentThread = currentThread;
}
}
| UTF-8 | Java | 15,758 | java | ExtractService.java | Java | [
{
"context": "e()))\n return;\n String txKey = \"mining:xid:\" + redoLog.getXid();\n //新增、修改、删除\n re",
"end": 9151,
"score": 0.9115650057792664,
"start": 9139,
"tag": "KEY",
"value": "mining:xid:\""
},
{
"context": " String txKey = \"mining:xid:\... | null | [] | package pub.timelyrain.logmining.biz;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import pub.timelyrain.logmining.config.Env;
import pub.timelyrain.logmining.pojo.MiningState;
import pub.timelyrain.logmining.pojo.RedoLog;
import pub.timelyrain.logmining.utils.TimeUtil;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static pub.timelyrain.logmining.biz.Constants.*;
@Component
@Scope("prototype")
public class ExtractService extends Thread {
private static final Logger log = LogManager.getLogger(ExtractService.class);
private static final Logger trlog = LogManager.getLogger("tracetr");
private final JdbcTemplate jdbcTemplate;
private final CounterService counterService;
private final Env env;
private final RedisTemplate redisTemplate;
@Autowired
public ExtractService(JdbcTemplate jdbcTemplate, CounterService counterService, Env env, RedisTemplate redisTemplate) {
this.jdbcTemplate = jdbcTemplate;
this.counterService = counterService;
this.env = env;
this.redisTemplate = redisTemplate;
getFilePath();
}
private String miningSql;
private MiningState state;
private int currentThread;
private int hashid;
private String filePath;
@Override
public void run() {
log.debug("开始抓取 run ");
// 读取state的seq
state = loadState();
// 判断 seq 小于数据库 archivelog的的最小 seq 提示有数据丢失(抓取程序长时间未启动,而归档日志被清理掉了)
pollingCheck(state);
miningSql = buildMiningSql();
try {
hashid = jdbcTemplate.getDataSource().getConnection().hashCode();
log.info("getConnection hash 值:{}", hashid);
} catch (SQLException e) {
e.printStackTrace();
}
while (!Thread.interrupted()) {
// 判断该seq是否是最末尾,若是代表本次抓取的日志不完整,需要再次抓取该文件。若不是末尾seq ,则一次可以抓取完整的日志。保存一个fulllog 状态.
boolean completedLogFlag = checkCompletedLog(state);
// 从 seq 开始读取 archive log 或 redo log
try {
pollingData(state);
// 正常抓取完毕后,若fulllog=true,则seq+1 重复进行新日志抓取
if (completedLogFlag) {
log.info("日志 {} 读取完毕", state.getLastSequence());
state.nextLog();
}
} catch (Exception e) {
log.error("抓取数据出错》》》》》",e);
TimeUtil.sheep(1);
}
}
}
/**
* 检查当前的seq 是否是最新的日志,如果是最新的日志,表示该日志还可能被追加新的待抓取内容.需要重新读取
*
* @param state
* @return
*/
private boolean checkCompletedLog(MiningState state) {
//检查归档日志的最大seq是否大于当前日志编号
long maxSequence = jdbcTemplate.queryForObject(QUERY_MAX_SEQUENCE_ARCHIVED, Long.class, currentThread);
if (maxSequence > state.getLastSequence())
return true;
//检查online日志的最大seq是否大于当前日志编号
maxSequence = jdbcTemplate.queryForObject(QUERY_MAX_SEQUENCE_ONLINE, Long.class, currentThread);
if (maxSequence > state.getLastSequence())
return true;
return false;
}
/**
* 检查数据库的日志列表是否完整,并警告
*
* @param state
*/
private void pollingCheck(MiningState state) {
long minSequence = jdbcTemplate.queryForObject(QUERY_MIN_SEQUENCE_ARCHIVED, Long.class, currentThread);
if (minSequence > state.getLastSequence()) {
log.warn("\r\n");
log.warn("**********************************");
log.warn("请注意: 最后一次处理的日志编号为 {} , 数据库保存最久的日志编号为 {}, 存在数据丢失的情况", state.getLastSequence(), minSequence);
log.warn("**********************************");
log.warn("\r\n");
}
}
/**
* 读取上次运行时的结束同步信息.用于恢复同步.
*
* @return
*/
private MiningState loadState() {
try {
File stateFile = new File(filePath + currentThread + "_state.saved");
if (!stateFile.exists()) {
//初次启动,读取当前seq.
long seq = jdbcTemplate.queryForObject(QUERY_SEQUENCE, Long.class, currentThread);
log.info("未找到进度状态文件,从最新日志开始抓取,日志编号为 {} hash值:{}", seq, hashid);
return new MiningState(0, 0, seq, null);
}
String stateStr = FileUtils.readFileToString(stateFile, "utf-8");
ObjectMapper om = new ObjectMapper();
MiningState lastState = om.readValue(stateStr, MiningState.class);
log.info("读取状态文件信息为 {}", stateStr);
return lastState;
} catch (IOException e) {
log.error("读取进度状态错误", e);
throw new RuntimeException("读取进度状态错误");
}
}
/**
* 根据sequence 和 commitScn 抓取待同步数据.
*
* @param state
* @return
*/
private void pollingData(MiningState state) {
//获得seq对应的日志文件的位置,先从归档日志里判断
startLogFileMining(state);
//启动日志分析
jdbcTemplate.setFetchSize(500);
try {
//jdbcTemplate.update("create table save_" + state.getLastSequence() + "_" + state.getLastRowNum() + " as " + Constants.QUERY_REDO.replaceAll("\\?", String.valueOf(state.getLastRowNum())));
jdbcTemplate.query(Constants.QUERY_REDO, (rs) -> {
//读取事务id
String xid = rs.getString("XID");
int opCode = rs.getInt("OPERATION_CODE");
int rollback = rs.getInt("ROLLBACK");
if (1 == rollback)
return;
long rn = rs.getLong("RN");
//读取日志位置
long scn = rs.getLong("SCN");
long commitScn = rs.getLong("COMMIT_SCN");
String timestamp = rs.getTimestamp("TIMESTAMP").toString();
try {
//log.debug(scn);
//读取REDO
int csf = rs.getInt("CSF");
String schema = rs.getString("SEG_OWNER");
String rsId = rs.getString("RS_ID");
// trlog.info("{}\t{}\t{}", rn, rsId, state.getLastSequence());
String tableName = rs.getString("TABLE_NAME");
String redo = rs.getString("SQL_REDO");
String rowId = rs.getString("ROW_ID");
if (csf == 1) { //如果REDO被截断
while (rs.next() && !Thread.interrupted()) { //继续查询下一条REDO
redo += rs.getString("SQL_REDO");
if (0 == rs.getInt("CSF")) { //
csf = 0;
break; //退出循环
}
}
}
RedoLog redoLog = new RedoLog(schema, tableName, redo, rowId, scn, commitScn, timestamp, rn, xid, opCode, rsId);
traceChange(redoLog);
} finally {
// log.debug("成功完成读取REDO日志 并保存读取的结果的索引值 ");
saveMiningState(commitScn, rn, state.getLastSequence(), timestamp);
}
}, state.getLastRowNum()); //传入redo value,不重复读取日志。
//关闭日志分析
} catch (Exception e) {
log.error("读取LOG出错", e);
throw e;
} finally {
log.debug("停止分析REDO日志 {} ,hash值:{}", Constants.MINING_END, hashid);
jdbcTemplate.update(Constants.MINING_END);
}
}
private void startLogFileMining(MiningState state) {
loadLogFile(state.getLastSequence());
// for (int i = 1; i < env.getLogFileScaned(); i++) {
// try {
// loadLogFile(state.getLastSequence() - i);
// } catch (Exception e) {
// //为了避免日志切换造成数据丢失,同时加载两个连续的日志文件
// //如果未找到前一个日志,不处理异常
// }
// }
jdbcTemplate.update(Constants.MINING_START);
log.debug("开启日志,hash值:{}", hashid);
}
private void traceChange(RedoLog redoLog) {
//判断是否是提交opCode=6 或回滚opCode=36
if (7 == redoLog.getOpCode()) {
commitRedo(redoLog);
return;
} else if (36 == redoLog.getOpCode()) {
rollbackRedo(redoLog);
return;
} else if (1 == redoLog.getOpCode() || 2 == redoLog.getOpCode() || 3 == redoLog.getOpCode()) {
saveRedo(redoLog);
return;
} else if (5 == redoLog.getOpCode()) {
// todo 更新日志字典
}
}
private void saveRedo(RedoLog redoLog) {
if (!env.getScanTables().contains(redoLog.getSchema() + "." + redoLog.getTableName()))
return;
String txKey = "mining:xid:" + redoLog.getXid();
//新增、修改、删除
redisTemplate.opsForList().rightPush(txKey, redoLog);
log.debug("识别待提交数据,缓存成功 {}", redoLog.toString());
//计数
counterService.addCount();
}
private void commitRedo(RedoLog redoLog) {
String txKey = "mining:xid:" + redoLog.getXid();
long count = redisTemplate.opsForList().size(txKey);
log.info("识别提交标记 事务id为 {} 总数据条数 {}", redoLog.getXid(), count);
redisTemplate.opsForList().rightPush("mining:replicate", redoLog.getXid());
}
private void rollbackRedo(RedoLog redoLog) {
//根据事务id删除redis缓存的redelog
redisTemplate.delete("mining:xid:" + redoLog.getXid());
log.debug("识别回滚标记 事务id为 {}", redoLog.getXid());
}
private void loadLogFile(long sequence) {
String logFile;
boolean onlineLogFlag = false;
List<Map<String, Object>> result = jdbcTemplate.queryForList(QUERY_NAME_SEQUENCE_ARCHIVED, sequence, currentThread);
if (result.isEmpty()) {
result = jdbcTemplate.queryForList(QUERY_NAME_SEQUENCE_ONLINE, sequence, currentThread);
onlineLogFlag = true;
}
Assert.state(!result.isEmpty(), String.format("未找到编号为 %d 的日志文件地址", sequence));
logFile = (String) result.get(0).get("name");
if (StringUtils.isEmpty(logFile)) {
log.error("待挖掘的日志已被删除,请检查 hash值:{}", hashid);
return;
}
jdbcTemplate.update(ADD_LOGFILE, logFile);
log.debug("分析 {} 日志, 日志编号为 {}, 日志文件为 {}", (onlineLogFlag ? "online log" : "archive log"), sequence, logFile);
}
/**
* 保存同步位置.用于下次程序运行时,可以恢复到停止点.
*
* @param commitScn
* @param sequence
* @param timestamp
*/
private void saveMiningState(long commitScn, long redoValue, long sequence, String timestamp) {
state.setLastCommitScn(commitScn);
state.setLastRowNum(redoValue);
state.setLastSequence(sequence);
state.setLastTime(timestamp);
String stateStr = null;
try {
File state = new File("/"+filePath + currentThread + "_state.saved");
state.exists();
stateStr = new ObjectMapper().writeValueAsString(this.state);
FileUtils.writeStringToFile(state, stateStr, "UTF-8", false);
// log.debug("saved state {}", stateStr);
} catch (Exception e) {
log.error("写入传输状态错误,当前传输信息为 " + stateStr, e);
}
}
/**
* 根据系统类型生成文件路径
*/
void getFilePath (){
// 得到当前系统名称
String s = System.getProperties().get("os.name").toString();
// 如果是window 则 用相对路径 如果是liunx 则用 绝对路径
if(s.indexOf("windows")>-1 || s.indexOf("Windows")>-1){
this.filePath= "state/thread_";
}else {
this.filePath= "/state/thread_";
}
}
private String buildMiningSqlWhere() {
HashMap<String, String> tableGroup = new HashMap<>();
//将数据库名.表名的数组,转成 数据库名和表名的集合
for (String tb : env.getScanTables()) {
// if (field.contains("|")) {
// tb = field.substring(0, field.indexOf("|"));
// tb = tb.toUpperCase();
// String condition = field.substring(field.indexOf("|") + 1, field.length());
//
// } else {
// tb = field.toUpperCase();
// }
Assert.isTrue(tb.contains("."), "同步表名格式不符合 数据库名.表名 的格式(" + tb + ")");
Assert.isTrue(!tb.contains("\\*"), "同步表名格式不符合 不可以使用通配 *(" + tb + ")");
String schemaName = tb.split("\\.")[0]; // 数据库名.表名
String tableName = tb.split("\\.")[1]; // 数据库名.表名
String tablesIn = tableGroup.get(schemaName);
tablesIn = (tablesIn == null ? "'" + tableName + "'" : tablesIn + ",'" + tableName + "'");
tableGroup.put(schemaName, tablesIn);
}
StringBuilder sql = new StringBuilder();
for (String schemaName : tableGroup.keySet()) {
if (sql.length() != 0) sql.append(" or ");
String tablesIn = tableGroup.get(schemaName);
if (tablesIn.startsWith("*"))
sql.append(String.format(" SEG_OWNER = '%s' ", schemaName));
else
sql.append(String.format(" SEG_OWNER = '%s' and TABLE_NAME in (%s)", schemaName, tableGroup.get(schemaName)));
}
sql.insert(0, "( ").append(" )");
return sql.toString();
}
private String buildMiningSql() {
// StringBuilder sql = new StringBuilder();
// sql.insert(0, buildMiningSqlWhere());
// sql.insert(0, " AND ");
// sql.insert(0, Constants.QUERY_REDO);
String sql = String.format(Constants.QUERY_REDO2, buildMiningSqlWhere());
log.debug("日志查询的sql是 {}", sql.toString());
return sql.toString();
}
public int getCurrentThread() {
return currentThread;
}
public void setCurrentThread(int currentThread) {
this.currentThread = currentThread;
}
}
| 15,758 | 0.565825 | 0.563073 | 387 | 35.625324 | 28.6621 | 201 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.767442 | false | false | 3 |
8c7cfe2436aefa02fc2c0c85eb86bf6a82b44119 | 11,072,425,741,579 | 14d6b21fedd15c2560a0ad49b63fc4fd3ce8d6fc | /Android/app/src/main/java/com/vps/smartpantry/HotelRegistration.java | 17f7ddb417ba3f287772903a187933f4bc2c1c61 | [] | no_license | maddy8381/Smart_Pantry | https://github.com/maddy8381/Smart_Pantry | 6c2e73095373b5a2e4cc376062380d95f81aa011 | dabe0b66df432b3a4eb114a2ecd6120488857c83 | refs/heads/master | 2020-03-17T20:26:38.407000 | 2018-10-28T10:57:24 | 2018-10-28T10:57:24 | 133,909,965 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.vps.smartpantry;
import android.Manifest;
import android.app.Activity;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
* Created by Pravin on 4/7/2018.
*/
public class HotelRegistration extends AppCompatActivity implements View.OnClickListener
{
private EditText hotel_name_et,authority_name_et,address_et,mobile_number_et;
private Button register_bt;
private String SMS_SENT = "SMS_SENT";
private static final int PERMISSION_REQUEST_CODE = 1;
private ProgressDialog mDialog;
private String hotel_name,authority_name,address,mobile_number,otp;
private BroadcastReceiver sms_sent_notifier;
private Spinner sellers_locations;
private RequestQueue volleyRequestQueue;
private ArrayList<String> locations;
@Override
public void onCreate(Bundle b)
{
super.onCreate(b);
setContentView(R.layout.hotel_registration);
hotel_name_et=(EditText)findViewById(R.id.hotel_name_hotel_registration_et);
authority_name_et=(EditText)findViewById(R.id.authority_name_hotel_registration_et);
address_et=(EditText)findViewById(R.id.address_hotel_registration_et);
mobile_number_et=(EditText)findViewById(R.id.mobile_number_hotel_registration_et);
register_bt=(Button)findViewById(R.id.register_hotel_registration_bt);
sellers_locations=(Spinner)findViewById(R.id.sellers_locations_spinner);
mDialog = new ProgressDialog(this);
mDialog.setCancelable(false);
volleyRequestQueue = Volley.newRequestQueue(this);
locations=new ArrayList<String>();
resetLocationList();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS}, 123);
register_bt.setEnabled(false);
}
else
{
setToReadSmsStatus();
register_bt.setEnabled(true);
}
register_bt.setOnClickListener(this);
sellers_locations.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, locations));
getSellersLocations();
}
@Override
public void onClick(View v)
{
if(hotel_name_et.getText().toString().trim().isEmpty())
{
Toast.makeText(getApplicationContext(), "Hotel name should not be empty", Toast.LENGTH_SHORT).show();
}
else if(authority_name_et.getText().toString().trim().isEmpty())
{
Toast.makeText(getApplicationContext(), "Authority name should not be empty", Toast.LENGTH_SHORT).show();
}
else if(address_et.getText().toString().trim().isEmpty())
{
Toast.makeText(getApplicationContext(), "Address should not be empty", Toast.LENGTH_SHORT).show();
}
else if(mobile_number_et.getText().toString().trim().isEmpty())
{
Toast.makeText(getApplicationContext(), "Mobile number should not be empty", Toast.LENGTH_SHORT).show();
}
else if(mobile_number_et.getText().toString().trim().length()<10 || mobile_number_et.getText().toString().trim().length()>10 )
{
Toast.makeText(getApplicationContext(), "Mobile number length should be 10 digit only", Toast.LENGTH_SHORT).show();
}
else {
mDialog.setMessage("Registering..");
mDialog.show();
hotel_name = hotel_name_et.getText().toString().trim();
authority_name = authority_name_et.getText().toString().trim();
address = address_et.getText().toString().trim();
mobile_number = mobile_number_et.getText().toString().trim();
otp = Integer.toString(new Random().nextInt(600000));
if (sellers_locations.getSelectedItem().toString().equals("Select location..")) {
Toast.makeText(this, "Please select location", Toast.LENGTH_SHORT).show();
mDialog.hide();
} else {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(mobile_number, null, otp, PendingIntent.getBroadcast(this, 0, new Intent(SMS_SENT), 0), null);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
{
if (requestCode == 123) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(this,"Permission for sending sms is granted",Toast.LENGTH_SHORT).show();
setToReadSmsStatus();
register_bt.setEnabled(true);
}
else
{
Toast.makeText(this,"Permission for sending sms is not granted",Toast.LENGTH_SHORT).show();
finish();
}
}
}
void setToReadSmsStatus()
{
sms_sent_notifier= new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
switch (getResultCode()) {
case Activity.RESULT_OK:
mDialog.hide();
Toast.makeText(context, "OTP sent successfully", Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), OTPVerificationForHotel.class);
i.putExtra("hotel_name",hotel_name);
i.putExtra("authority_name",authority_name);
i.putExtra("address",address);
i.putExtra("mobile_number",mobile_number);
i.putExtra("otp",otp);
i.putExtra("location",sellers_locations.getSelectedItem().toString());
startActivity(i);
finish();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
mDialog.hide();
Toast.makeText(context, "Failed to send OTP", Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
mDialog.hide();
Toast.makeText(context, "Failed to send OTP", Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
mDialog.hide();
Toast.makeText(context, "Failed to send OTP", Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
mDialog.hide();
Toast.makeText(context, "Failed to send OTP", Toast.LENGTH_SHORT).show();
break;
}
}
};
registerReceiver(sms_sent_notifier, new IntentFilter(SMS_SENT));
}
@Override
public void onDestroy()
{
super.onDestroy();
mDialog.dismiss();
unregisterReceiver(sms_sent_notifier);
}
public void resetLocationList()
{
locations.clear();
locations.add("Select location..");
}
public void getSellersLocations()
{
mDialog.setMessage("Getting available locations...");
mDialog.show();
String url="http://"+Config.SERVER_ADDRESS+"/android/get_sellers_location.php";
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>()
{
@Override
public void onResponse(String response)
{
try
{
resetLocationList();
if(!response.contains("null"))
{
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
if(!locations.contains(jsonObject.getString("location")))
{
locations.add(jsonObject.getString("location"));
}
}
}
sellers_locations.setAdapter(new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_spinner_dropdown_item, locations));
sellers_locations.invalidate();
mDialog.hide();
}
catch (Exception e)
{
mDialog.hide();
Toast.makeText(getApplicationContext(), e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error)
{
mDialog.hide();
Toast.makeText(getApplicationContext(), error.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
})
{
@Override
protected Map<String,String> getParams()
{
Map<String,String> data=new HashMap<String, String>();
data.put("data","null");
return data;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError
{
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","application/x-www-form-urlencoded");
return params;
}
};
volleyRequestQueue.add(request);
}
}
| UTF-8 | Java | 10,817 | java | HotelRegistration.java | Java | [
{
"context": "l.Map;\nimport java.util.Random;\n\n/**\n * Created by Pravin on 4/7/2018.\n */\n\npublic class HotelRegistration ",
"end": 1148,
"score": 0.9990103840827942,
"start": 1142,
"tag": "NAME",
"value": "Pravin"
}
] | null | [] | package com.vps.smartpantry;
import android.Manifest;
import android.app.Activity;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
* Created by Pravin on 4/7/2018.
*/
public class HotelRegistration extends AppCompatActivity implements View.OnClickListener
{
private EditText hotel_name_et,authority_name_et,address_et,mobile_number_et;
private Button register_bt;
private String SMS_SENT = "SMS_SENT";
private static final int PERMISSION_REQUEST_CODE = 1;
private ProgressDialog mDialog;
private String hotel_name,authority_name,address,mobile_number,otp;
private BroadcastReceiver sms_sent_notifier;
private Spinner sellers_locations;
private RequestQueue volleyRequestQueue;
private ArrayList<String> locations;
@Override
public void onCreate(Bundle b)
{
super.onCreate(b);
setContentView(R.layout.hotel_registration);
hotel_name_et=(EditText)findViewById(R.id.hotel_name_hotel_registration_et);
authority_name_et=(EditText)findViewById(R.id.authority_name_hotel_registration_et);
address_et=(EditText)findViewById(R.id.address_hotel_registration_et);
mobile_number_et=(EditText)findViewById(R.id.mobile_number_hotel_registration_et);
register_bt=(Button)findViewById(R.id.register_hotel_registration_bt);
sellers_locations=(Spinner)findViewById(R.id.sellers_locations_spinner);
mDialog = new ProgressDialog(this);
mDialog.setCancelable(false);
volleyRequestQueue = Volley.newRequestQueue(this);
locations=new ArrayList<String>();
resetLocationList();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS}, 123);
register_bt.setEnabled(false);
}
else
{
setToReadSmsStatus();
register_bt.setEnabled(true);
}
register_bt.setOnClickListener(this);
sellers_locations.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, locations));
getSellersLocations();
}
@Override
public void onClick(View v)
{
if(hotel_name_et.getText().toString().trim().isEmpty())
{
Toast.makeText(getApplicationContext(), "Hotel name should not be empty", Toast.LENGTH_SHORT).show();
}
else if(authority_name_et.getText().toString().trim().isEmpty())
{
Toast.makeText(getApplicationContext(), "Authority name should not be empty", Toast.LENGTH_SHORT).show();
}
else if(address_et.getText().toString().trim().isEmpty())
{
Toast.makeText(getApplicationContext(), "Address should not be empty", Toast.LENGTH_SHORT).show();
}
else if(mobile_number_et.getText().toString().trim().isEmpty())
{
Toast.makeText(getApplicationContext(), "Mobile number should not be empty", Toast.LENGTH_SHORT).show();
}
else if(mobile_number_et.getText().toString().trim().length()<10 || mobile_number_et.getText().toString().trim().length()>10 )
{
Toast.makeText(getApplicationContext(), "Mobile number length should be 10 digit only", Toast.LENGTH_SHORT).show();
}
else {
mDialog.setMessage("Registering..");
mDialog.show();
hotel_name = hotel_name_et.getText().toString().trim();
authority_name = authority_name_et.getText().toString().trim();
address = address_et.getText().toString().trim();
mobile_number = mobile_number_et.getText().toString().trim();
otp = Integer.toString(new Random().nextInt(600000));
if (sellers_locations.getSelectedItem().toString().equals("Select location..")) {
Toast.makeText(this, "Please select location", Toast.LENGTH_SHORT).show();
mDialog.hide();
} else {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(mobile_number, null, otp, PendingIntent.getBroadcast(this, 0, new Intent(SMS_SENT), 0), null);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
{
if (requestCode == 123) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(this,"Permission for sending sms is granted",Toast.LENGTH_SHORT).show();
setToReadSmsStatus();
register_bt.setEnabled(true);
}
else
{
Toast.makeText(this,"Permission for sending sms is not granted",Toast.LENGTH_SHORT).show();
finish();
}
}
}
void setToReadSmsStatus()
{
sms_sent_notifier= new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
switch (getResultCode()) {
case Activity.RESULT_OK:
mDialog.hide();
Toast.makeText(context, "OTP sent successfully", Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), OTPVerificationForHotel.class);
i.putExtra("hotel_name",hotel_name);
i.putExtra("authority_name",authority_name);
i.putExtra("address",address);
i.putExtra("mobile_number",mobile_number);
i.putExtra("otp",otp);
i.putExtra("location",sellers_locations.getSelectedItem().toString());
startActivity(i);
finish();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
mDialog.hide();
Toast.makeText(context, "Failed to send OTP", Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
mDialog.hide();
Toast.makeText(context, "Failed to send OTP", Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
mDialog.hide();
Toast.makeText(context, "Failed to send OTP", Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
mDialog.hide();
Toast.makeText(context, "Failed to send OTP", Toast.LENGTH_SHORT).show();
break;
}
}
};
registerReceiver(sms_sent_notifier, new IntentFilter(SMS_SENT));
}
@Override
public void onDestroy()
{
super.onDestroy();
mDialog.dismiss();
unregisterReceiver(sms_sent_notifier);
}
public void resetLocationList()
{
locations.clear();
locations.add("Select location..");
}
public void getSellersLocations()
{
mDialog.setMessage("Getting available locations...");
mDialog.show();
String url="http://"+Config.SERVER_ADDRESS+"/android/get_sellers_location.php";
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>()
{
@Override
public void onResponse(String response)
{
try
{
resetLocationList();
if(!response.contains("null"))
{
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
if(!locations.contains(jsonObject.getString("location")))
{
locations.add(jsonObject.getString("location"));
}
}
}
sellers_locations.setAdapter(new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_spinner_dropdown_item, locations));
sellers_locations.invalidate();
mDialog.hide();
}
catch (Exception e)
{
mDialog.hide();
Toast.makeText(getApplicationContext(), e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error)
{
mDialog.hide();
Toast.makeText(getApplicationContext(), error.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
})
{
@Override
protected Map<String,String> getParams()
{
Map<String,String> data=new HashMap<String, String>();
data.put("data","null");
return data;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError
{
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","application/x-www-form-urlencoded");
return params;
}
};
volleyRequestQueue.add(request);
}
}
| 10,817 | 0.585282 | 0.582324 | 276 | 38.192028 | 32.737141 | 151 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.775362 | false | false | 3 |
706c5abd3f82c84663ea9c56ea2b39981e357795 | 33,809,982,559,434 | ee5125c32c07fe331d7a0fb27a038a958cd6526b | /reading-service/src/main/java/com/synapse/reading/respository/MediaCountsRespository.java | 4fb9ac8aa770d99a8f76112e378f0e8c0a4a34aa | [] | no_license | 1241545483/terrace-cloud | https://github.com/1241545483/terrace-cloud | 581a99c5532ffdbcdf2d293c54113276b36eebe8 | a18d0044501ad959cbd1bbc18d5a939fcd37d01a | refs/heads/master | 2022-06-21T10:59:43.913000 | 2019-09-03T08:26:18 | 2019-09-03T08:26:18 | 254,294,081 | 0 | 0 | null | false | 2022-03-08T21:25:54 | 2020-04-09T06:51:16 | 2020-04-09T06:55:16 | 2022-03-08T21:25:54 | 3,495 | 0 | 0 | 7 | TSQL | false | false | package com.synapse.reading.respository;
import com.synapse.reading.mapper.MediaCountsMapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
* <p>
* 统计播放量 Respository 接口
* </p>
*
* @author liuguangfu
* @since 2018-12-25
*/
public interface MediaCountsRespository extends MediaCountsMapper {
Integer countByCreateId(@Param("mediaId") String mediaId,@Param("createTime")String createTime,@Param("mediaType")String mediaType);
Integer updateByCreateId(@Param("mediaId") String mediaId,@Param("createTime")String createTime,@Param("mediaType")String mediaType);
Integer updateFinishedByCreateId(@Param("mediaId") String mediaId,@Param("createTime")String createTime,@Param("mediaType")String mediaType);
List<Map<String,String>> clickCountByTime(@Param("startTime")String startTime, @Param("endTime") String endTime, @Param("mediaId") String mediaId);
List<Map<String,String>> finishCountByTime(@Param("startTime")String startTime, @Param("endTime") String endTime, @Param("mediaId") String mediaId);
List<Map<String,String>> finishRateByTime(@Param("startTime")String startTime, @Param("endTime") String endTime, @Param("mediaId") String mediaId);
}
| UTF-8 | Java | 1,243 | java | MediaCountsRespository.java | Java | [
{
"context": " <p>\n * 统计播放量 Respository 接口\n * </p>\n *\n * @author liuguangfu\n * @since 2018-12-25\n */\npublic interface MediaCo",
"end": 253,
"score": 0.9989461898803711,
"start": 243,
"tag": "USERNAME",
"value": "liuguangfu"
}
] | null | [] | package com.synapse.reading.respository;
import com.synapse.reading.mapper.MediaCountsMapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
* <p>
* 统计播放量 Respository 接口
* </p>
*
* @author liuguangfu
* @since 2018-12-25
*/
public interface MediaCountsRespository extends MediaCountsMapper {
Integer countByCreateId(@Param("mediaId") String mediaId,@Param("createTime")String createTime,@Param("mediaType")String mediaType);
Integer updateByCreateId(@Param("mediaId") String mediaId,@Param("createTime")String createTime,@Param("mediaType")String mediaType);
Integer updateFinishedByCreateId(@Param("mediaId") String mediaId,@Param("createTime")String createTime,@Param("mediaType")String mediaType);
List<Map<String,String>> clickCountByTime(@Param("startTime")String startTime, @Param("endTime") String endTime, @Param("mediaId") String mediaId);
List<Map<String,String>> finishCountByTime(@Param("startTime")String startTime, @Param("endTime") String endTime, @Param("mediaId") String mediaId);
List<Map<String,String>> finishRateByTime(@Param("startTime")String startTime, @Param("endTime") String endTime, @Param("mediaId") String mediaId);
}
| 1,243 | 0.762408 | 0.755899 | 26 | 46.26923 | 56.967979 | 152 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 3 |
462a0f72f3b939308b5ba298ae01786044338331 | 2,585,570,369,901 | bfa86baf0afa6e868ad3dcdaf495124104111261 | /107. Binary Tree Level Order Traversal II.java | 05b1d0b1afd5dad67278c26ad5dcc38cbd38ebe3 | [] | no_license | di-wendy/LeetcodeJava | https://github.com/di-wendy/LeetcodeJava | 4dc0193306b6eeaf173f868ce25546d589a331a8 | c44063a60503670a3008d390344223b65d03dffc | refs/heads/master | 2021-01-19T12:26:28.214000 | 2018-09-27T05:52:11 | 2018-09-27T05:52:11 | 82,331,794 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> ans = new LinkedList<>();
Queue<TreeNode> q = new LinkedList<>();
if(root == null) return ans;
q.add(root);
while(!q.isEmpty()){
int n = q.size();
List<Integer> temp = new ArrayList<>();
for (int i = 0; i < n; i++){
TreeNode cur = q.poll();
temp.add(cur.val);
if (cur.left != null) q.add(cur.left);
if (cur.right != null) q.add(cur.right);
}
ans.add(0, temp);
}
return ans;
}
}
| UTF-8 | Java | 689 | java | 107. Binary Tree Level Order Traversal II.java | Java | [] | null | [] | public class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> ans = new LinkedList<>();
Queue<TreeNode> q = new LinkedList<>();
if(root == null) return ans;
q.add(root);
while(!q.isEmpty()){
int n = q.size();
List<Integer> temp = new ArrayList<>();
for (int i = 0; i < n; i++){
TreeNode cur = q.poll();
temp.add(cur.val);
if (cur.left != null) q.add(cur.left);
if (cur.right != null) q.add(cur.right);
}
ans.add(0, temp);
}
return ans;
}
}
| 689 | 0.45283 | 0.449927 | 22 | 30.318182 | 18.286573 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.681818 | false | false | 3 |
8f35cf69a1ea0908509f1aea548d709abe78a0a8 | 31,653,909,011,866 | aba07ba69652ff7313adca541c37d397b81551e9 | /baseball-elimination/src/BaseballElimination.java | 97d784de86e4a3bd7fe7fde4f464b35e50f40e56 | [] | no_license | feranco/princeton-algorithms-part-2 | https://github.com/feranco/princeton-algorithms-part-2 | d91cb47dc116b665135739c0fe5a1fa701c69ac0 | c0474040677627e93bed93c3888956902d67e4bb | refs/heads/master | 2021-08-23T22:25:29.906000 | 2017-12-06T21:38:13 | 2017-12-06T21:38:13 | 113,078,295 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.FlowEdge;
import edu.princeton.cs.algs4.FlowNetwork;
import edu.princeton.cs.algs4.FordFulkerson;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class BaseballElimination {
private final int teams;
private String leader;
private final int[] wins;
private final int[] losses;
private final int[] remaining;
private final int[][] games;
private final Map<String, Integer> teamToId;
private boolean isTriviallyEliminated(int id) {
return (wins[id] + remaining[id] < wins[teamToId.get(leader)]) ? true : false;
}
// @id = candidate to be eliminated
private FlowNetwork buildFlowNetwork(int id) {
int numGames = (teams * (teams - 1)) / 2; // number of games
int vertices = numGames + teams + 2; // number of vertices = number of games + number of teams + source + sink
int source = 0; // source = first ID
int sink = vertices - 1; // target = last ID
FlowNetwork flowNetwork = new FlowNetwork(vertices);
int gameVertex = 1; //id of first game vertex
//cycle on all teams (gamesRow)
for (int i = 0; i < teams; i++) {//games.length
if (i == id) continue; //skip candidate
//cycle on all remaining teams (gamesCol)
for (int j = i + 1; j < teams; j++) {//games[i].length
if (j == id) continue; //skip candidate
// add edges from source to games vertices
flowNetwork.addEdge(new FlowEdge(source, gameVertex, games[i][j]));
// add edges from games vertices to teams vertices (+ 1 is for the source)
flowNetwork.addEdge(new FlowEdge(gameVertex, numGames + i + 1, Double.POSITIVE_INFINITY));
flowNetwork.addEdge(new FlowEdge(gameVertex, numGames + j + 1, Double.POSITIVE_INFINITY));
gameVertex++;
}
// add edges from teams vertices to target
int teamVertex = numGames + i + 1;
flowNetwork.addEdge(new FlowEdge(teamVertex, sink, Math.max(0, wins[id] + remaining[id] - wins[i])));
}
return flowNetwork;
}
// create a baseball division from given filename in format specified below
public BaseballElimination(String filename) {
In in = new In(filename);
int maxWins = 0;
teams = in.readInt();
wins = new int[teams];
losses = new int[teams];
remaining = new int[teams];
games = new int[teams][teams];
teamToId = new HashMap<String, Integer>();
for (int i = 0; i < teams; i++) {
String team = in.readString();
teamToId.put(team, i);
wins[i] = in.readInt();
losses[i] = in.readInt();
remaining[i] = in.readInt();
for (int j = 0; j < teams; j++) {
games[i][j] = in.readInt();
}
if (wins[i] > maxWins) {
maxWins = wins[i];
leader = team;
}
}
}
// number of teams
public int numberOfTeams() {
return teams;
}
// all teams
public Iterable<String> teams() {
return teamToId.keySet();
}
// number of wins for given team
public int wins(String team) {
if (!teamToId.containsKey(team)) {
throw new IllegalArgumentException("The team is not valid!");
}
return wins[teamToId.get(team)];
}
// number of losses for given team
public int losses(String team) {
if (!teamToId.containsKey(team)) {
throw new IllegalArgumentException("The team is not valid!");
}
return losses[teamToId.get(team)];
}
// number of remaining games for given team
public int remaining(String team) {
if (!teamToId.containsKey(team)) {
throw new IllegalArgumentException("The team is not valid!");
}
return remaining[teamToId.get(team)];
}
// number of remaining games between team1 and team2
public int against(String team1, String team2) {
if (!teamToId.containsKey(team1) || !teamToId.containsKey(team2)) {
throw new IllegalArgumentException("The teams are not valid!");
}
return games[teamToId.get(team1)][teamToId.get(team2)];
}
// is given team eliminated?
public boolean isEliminated(String team) {
if (!teamToId.containsKey(team)) {
throw new IllegalArgumentException("The team is not valid!");
}
int id = teamToId.get(team);
// check for trivial elimination
if (isTriviallyEliminated(id)) {
return true;
}
// check for elimination: team is eliminated if a flow from source to games vertices is not
// equal to the capacity (not all game can be played without eliminating the input team
FlowNetwork flowNetwork = buildFlowNetwork(id);
int source = 0;
int sink = flowNetwork.V() - 1;
FordFulkerson ff = new FordFulkerson(flowNetwork, source, sink);
for (FlowEdge edge : flowNetwork.adj(source)) {
if (edge.flow() < edge.capacity()) return true;
}
return false;
}
// subset R of teams that eliminates given team; null if not eliminated
public Iterable<String> certificateOfElimination(String team) {
if (!teamToId.containsKey(team)) {
throw new IllegalArgumentException("The team is not valid!");
}
Set<String> set = new HashSet<>();
if (isTriviallyEliminated(teamToId.get(team))) {
set.add(leader);
return set;
}
FlowNetwork flowNetwork = buildFlowNetwork(teamToId.get(team));
int source = 0;
int sink = flowNetwork.V() - 1;
FordFulkerson ff = new FordFulkerson(flowNetwork, 0, sink);
for (FlowEdge edge : flowNetwork.adj(source)) {
if (edge.flow() < edge.capacity()) {
for (String t : teams()) {
int teamId = teamToId.get(t);
if (ff.inCut(teamId)) {
set.add(t);
}
}
}
}
return set.isEmpty() ? null : set;
}
}
| UTF-8 | Java | 5,947 | java | BaseballElimination.java | Java | [] | null | [] | import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.FlowEdge;
import edu.princeton.cs.algs4.FlowNetwork;
import edu.princeton.cs.algs4.FordFulkerson;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class BaseballElimination {
private final int teams;
private String leader;
private final int[] wins;
private final int[] losses;
private final int[] remaining;
private final int[][] games;
private final Map<String, Integer> teamToId;
private boolean isTriviallyEliminated(int id) {
return (wins[id] + remaining[id] < wins[teamToId.get(leader)]) ? true : false;
}
// @id = candidate to be eliminated
private FlowNetwork buildFlowNetwork(int id) {
int numGames = (teams * (teams - 1)) / 2; // number of games
int vertices = numGames + teams + 2; // number of vertices = number of games + number of teams + source + sink
int source = 0; // source = first ID
int sink = vertices - 1; // target = last ID
FlowNetwork flowNetwork = new FlowNetwork(vertices);
int gameVertex = 1; //id of first game vertex
//cycle on all teams (gamesRow)
for (int i = 0; i < teams; i++) {//games.length
if (i == id) continue; //skip candidate
//cycle on all remaining teams (gamesCol)
for (int j = i + 1; j < teams; j++) {//games[i].length
if (j == id) continue; //skip candidate
// add edges from source to games vertices
flowNetwork.addEdge(new FlowEdge(source, gameVertex, games[i][j]));
// add edges from games vertices to teams vertices (+ 1 is for the source)
flowNetwork.addEdge(new FlowEdge(gameVertex, numGames + i + 1, Double.POSITIVE_INFINITY));
flowNetwork.addEdge(new FlowEdge(gameVertex, numGames + j + 1, Double.POSITIVE_INFINITY));
gameVertex++;
}
// add edges from teams vertices to target
int teamVertex = numGames + i + 1;
flowNetwork.addEdge(new FlowEdge(teamVertex, sink, Math.max(0, wins[id] + remaining[id] - wins[i])));
}
return flowNetwork;
}
// create a baseball division from given filename in format specified below
public BaseballElimination(String filename) {
In in = new In(filename);
int maxWins = 0;
teams = in.readInt();
wins = new int[teams];
losses = new int[teams];
remaining = new int[teams];
games = new int[teams][teams];
teamToId = new HashMap<String, Integer>();
for (int i = 0; i < teams; i++) {
String team = in.readString();
teamToId.put(team, i);
wins[i] = in.readInt();
losses[i] = in.readInt();
remaining[i] = in.readInt();
for (int j = 0; j < teams; j++) {
games[i][j] = in.readInt();
}
if (wins[i] > maxWins) {
maxWins = wins[i];
leader = team;
}
}
}
// number of teams
public int numberOfTeams() {
return teams;
}
// all teams
public Iterable<String> teams() {
return teamToId.keySet();
}
// number of wins for given team
public int wins(String team) {
if (!teamToId.containsKey(team)) {
throw new IllegalArgumentException("The team is not valid!");
}
return wins[teamToId.get(team)];
}
// number of losses for given team
public int losses(String team) {
if (!teamToId.containsKey(team)) {
throw new IllegalArgumentException("The team is not valid!");
}
return losses[teamToId.get(team)];
}
// number of remaining games for given team
public int remaining(String team) {
if (!teamToId.containsKey(team)) {
throw new IllegalArgumentException("The team is not valid!");
}
return remaining[teamToId.get(team)];
}
// number of remaining games between team1 and team2
public int against(String team1, String team2) {
if (!teamToId.containsKey(team1) || !teamToId.containsKey(team2)) {
throw new IllegalArgumentException("The teams are not valid!");
}
return games[teamToId.get(team1)][teamToId.get(team2)];
}
// is given team eliminated?
public boolean isEliminated(String team) {
if (!teamToId.containsKey(team)) {
throw new IllegalArgumentException("The team is not valid!");
}
int id = teamToId.get(team);
// check for trivial elimination
if (isTriviallyEliminated(id)) {
return true;
}
// check for elimination: team is eliminated if a flow from source to games vertices is not
// equal to the capacity (not all game can be played without eliminating the input team
FlowNetwork flowNetwork = buildFlowNetwork(id);
int source = 0;
int sink = flowNetwork.V() - 1;
FordFulkerson ff = new FordFulkerson(flowNetwork, source, sink);
for (FlowEdge edge : flowNetwork.adj(source)) {
if (edge.flow() < edge.capacity()) return true;
}
return false;
}
// subset R of teams that eliminates given team; null if not eliminated
public Iterable<String> certificateOfElimination(String team) {
if (!teamToId.containsKey(team)) {
throw new IllegalArgumentException("The team is not valid!");
}
Set<String> set = new HashSet<>();
if (isTriviallyEliminated(teamToId.get(team))) {
set.add(leader);
return set;
}
FlowNetwork flowNetwork = buildFlowNetwork(teamToId.get(team));
int source = 0;
int sink = flowNetwork.V() - 1;
FordFulkerson ff = new FordFulkerson(flowNetwork, 0, sink);
for (FlowEdge edge : flowNetwork.adj(source)) {
if (edge.flow() < edge.capacity()) {
for (String t : teams()) {
int teamId = teamToId.get(t);
if (ff.inCut(teamId)) {
set.add(t);
}
}
}
}
return set.isEmpty() ? null : set;
}
}
| 5,947 | 0.619472 | 0.613923 | 184 | 31.320652 | 24.690485 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.983696 | false | false | 3 |
65612385ebb59dd399b76e634e841a29d5d540e3 | 31,653,909,011,115 | 4a74304e1df4879dabad7b29750fbd0953aefd20 | /src/servlet/CadastroUsuario.java | d87b1a428dd50040c4040529b8127698f3c3ae13 | [] | no_license | Jonhcs/projeto-jdbc-servlet-jsp | https://github.com/Jonhcs/projeto-jdbc-servlet-jsp | 307fbbcb45240af554e9d37588a310607700c068 | bfc72ad2203fbcd6fcbfc35d8da626cf74aae384 | refs/heads/master | 2022-11-23T11:45:26.006000 | 2020-07-15T20:26:22 | 2020-07-15T20:26:22 | 279,971,076 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package servlet;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.tomcat.util.codec.binary.Base64;
import beans.BeanCursoJsp;
import dao.DaoLogin;
import dao.DaoUsuario;
/**
* Servlet implementation class CadastroUsuario
*/
@WebServlet("/CadastroUsuario")
@MultipartConfig
public class CadastroUsuario extends HttpServlet {
private static final long serialVersionUID = 1L;
private DaoUsuario daoUsuario = new DaoUsuario();
/**
* @see HttpServlet#HttpServlet()
*/
public CadastroUsuario() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
String acao = request.getParameter("acao");
String user = request.getParameter("user");
String tipo = request.getParameter("tipo");
if (acao == null) {
RequestDispatcher view = request.getRequestDispatcher("cadastroUsuario.jsp");
request.setAttribute("usuarios", daoUsuario.listarTodos());
view.forward(request, response);
} else if (acao.equals("delete")) {
daoUsuario.deletar(user);
System.out.println("Açăo delete ok!");
RequestDispatcher view = request.getRequestDispatcher("cadastroUsuario.jsp");
request.setAttribute("usuarios", daoUsuario.listarTodos());
view.forward(request, response);
} else if (acao.equals("editar")) {
BeanCursoJsp beancursojsp = daoUsuario.consultar(user);
RequestDispatcher view = request.getRequestDispatcher("cadastroUsuario.jsp");
request.setAttribute("user", beancursojsp);
view.forward(request, response);
} else if (acao.equals("listarTodos")) {
RequestDispatcher view = request.getRequestDispatcher("cadastroUsuario.jsp");
request.setAttribute("usuarios", daoUsuario.listarTodos());
view.forward(request, response);
} else if (acao.equals("download")) {
BeanCursoJsp usuario = daoUsuario.consultar(user);
if (usuario != null) {
String contentType = "";
byte[] fileBytes = null;
if (tipo.equals("imagem")) {
contentType = usuario.getContentType();
fileBytes = new Base64().decodeBase64(usuario.getFotoBase64());
response.setHeader("Content-Disposition",
"attachment; filename = arquivo." + contentType.split("\\/")[1]);
}
if (tipo.equals("pdf")) {
contentType = usuario.getContentTypePdf();
fileBytes = new Base64().decodeBase64(usuario.getPdfBase64());
response.setHeader("Content-Disposition",
"attachment; filename = pdf." + contentType.split("\\/")[1]);
}
InputStream is = new ByteArrayInputStream(fileBytes);
int read = 0;
byte[] bytes = new byte[1024];
OutputStream os = response.getOutputStream();
while ((read = is.read(bytes)) != -1) {
os.write(bytes, 0, read);
}
os.flush();
os.close();
}
RequestDispatcher view = request.getRequestDispatcher("cadastroUsuario.jsp");
request.setAttribute("usuarios", daoUsuario.listarTodos());
view.forward(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
BeanCursoJsp usuario = new BeanCursoJsp();
String acao = request.getParameter("acao");
boolean podeInserir = true;
if (acao != null && acao.equalsIgnoreCase("resetar")) {
try {
RequestDispatcher view = request.getRequestDispatcher("cadastroUsuario.jsp");
request.setAttribute("usuarios", daoUsuario.listarTodos());
view.forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
} else {
String id = request.getParameter("id");
String nome = request.getParameter("nome");
String login = request.getParameter("login");
String senha = request.getParameter("senha");
String telefoneString = request.getParameter("telefone");
String cep = request.getParameter("cep");
String rua = request.getParameter("rua");
String bairro = request.getParameter("bairro");
String cidade = request.getParameter("cidade");
String uf = request.getParameter("uf");
String ibge = request.getParameter("ibge");
usuario.setId(!id.isEmpty() ? Long.parseLong(id) : null);
usuario.setLogin(login);
usuario.setPassword(senha);
usuario.setNome(nome);
usuario.setTelefone(!telefoneString.isEmpty() ? Long.parseLong(telefoneString) : null);
usuario.setCep(cep);
usuario.setRua(rua);
usuario.setBairro(bairro);
usuario.setCidade(cidade);
usuario.setUf(uf);
usuario.setIbge(ibge);
List<String> msg = new ArrayList<String>();
try {
if (ServletFileUpload.isMultipartContent(request)) {
Part imagemFoto = request.getPart("foto");
if (imagemFoto != null) {
String fotoBase64 = new Base64()
.encodeBase64String(converteStremParaByte(imagemFoto.getInputStream()));
usuario.setFotoBase64(fotoBase64);
usuario.setContentType(imagemFoto.getContentType());
}
/**
* Processamento de pdf
*/
Part pdf = request.getPart("pdf");
if (pdf != null) {
String pdf64 = new Base64().encodeBase64String(converteStremParaByte(pdf.getInputStream()));
usuario.setPdfBase64(pdf64);
usuario.setContentTypePdf(pdf.getContentType());
}
}
if (login == null || login.isEmpty()) {
String msgLogin = "Campo obrigatório: LOGIN";
msg.add(msgLogin);
podeInserir = false;
} else if (senha == null || senha.isEmpty()) {
String msgSenha = "Campo obrigatório: SENHA";
msg.add(msgSenha);
podeInserir = false;
} else if (telefoneString == null || telefoneString.isEmpty()) {
String msgTelefone = "Campo obrigatório: TELEFONE";
msg.add(msgTelefone);
podeInserir = false;
} else if (nome == null || nome.isEmpty()) {
String msgNome = "Campo obrigatório: NOME";
msg.add(msgNome);
podeInserir = false;
} else if (id == null || id.isEmpty() && !daoUsuario.validarLogin(login)) {
String msgLogin = " Usuário já existe com o mesmo login. Cadastre outro login.";
msg.add(msgLogin);
podeInserir = false;
} else if (id == null || id.isEmpty() && !daoUsuario.validarSenha(senha)) {
String msgSenha = " Senha já existe para outro usuário.";
msg.add(msgSenha);
podeInserir = false;
}
if (msg != null && !podeInserir) {
request.setAttribute("msg", msg);
request.setAttribute("user", usuario);
} else if (id == null || id.isEmpty() && daoUsuario.validarLogin(login) && podeInserir) {
daoUsuario.salvar(usuario);
String msgSalvo = "Salvo com sucesso";
msg.add(msgSalvo);
podeInserir = true;
System.out.println("Usuario salvo");
} else if (id != null && !id.isEmpty()) {
if (!daoUsuario.validarLoginUpdate(login, id)) {
String msgUpdate = " Login já existe em outra conta de usuário. Atualize outro login.";
msg.add(msgUpdate);
podeInserir = false;
} else {
daoUsuario.atualizar(usuario);
System.out.println("Usuario Atualizado");
String msgAtualizado = "Atualizado com sucesso";
msg.add(msgAtualizado);
podeInserir = true;
}
}
if (msg != null && podeInserir) {
request.setAttribute("msg", msg);
}
RequestDispatcher view = request.getRequestDispatcher("cadastroUsuario.jsp");
request.setAttribute("usuarios", daoUsuario.listarTodos());
request.setAttribute("podeInserir", podeInserir);
view.forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* Converte para um array de Bytes
*
* @param imagem
* @return
* @throws IOException
*/
private byte[] converteStremParaByte(InputStream imagem) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int reads = imagem.read();
while (reads != -1) {
baos.write(reads);
reads = imagem.read();
}
return baos.toByteArray();
}
}
| ISO-8859-2 | Java | 8,919 | java | CadastroUsuario.java | Java | [
{
"context": "\t\tusuario.setLogin(login);\n\t\t\tusuario.setPassword(senha);\n\t\t\tusuario.setNome(nome);\n\t\t\tusuario.setTelefon",
"end": 5226,
"score": 0.9974673986434937,
"start": 5221,
"tag": "PASSWORD",
"value": "senha"
},
{
"context": "\t\t\tusuario.setPassword(senha);\n\t\... | null | [] | package servlet;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.tomcat.util.codec.binary.Base64;
import beans.BeanCursoJsp;
import dao.DaoLogin;
import dao.DaoUsuario;
/**
* Servlet implementation class CadastroUsuario
*/
@WebServlet("/CadastroUsuario")
@MultipartConfig
public class CadastroUsuario extends HttpServlet {
private static final long serialVersionUID = 1L;
private DaoUsuario daoUsuario = new DaoUsuario();
/**
* @see HttpServlet#HttpServlet()
*/
public CadastroUsuario() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
String acao = request.getParameter("acao");
String user = request.getParameter("user");
String tipo = request.getParameter("tipo");
if (acao == null) {
RequestDispatcher view = request.getRequestDispatcher("cadastroUsuario.jsp");
request.setAttribute("usuarios", daoUsuario.listarTodos());
view.forward(request, response);
} else if (acao.equals("delete")) {
daoUsuario.deletar(user);
System.out.println("Açăo delete ok!");
RequestDispatcher view = request.getRequestDispatcher("cadastroUsuario.jsp");
request.setAttribute("usuarios", daoUsuario.listarTodos());
view.forward(request, response);
} else if (acao.equals("editar")) {
BeanCursoJsp beancursojsp = daoUsuario.consultar(user);
RequestDispatcher view = request.getRequestDispatcher("cadastroUsuario.jsp");
request.setAttribute("user", beancursojsp);
view.forward(request, response);
} else if (acao.equals("listarTodos")) {
RequestDispatcher view = request.getRequestDispatcher("cadastroUsuario.jsp");
request.setAttribute("usuarios", daoUsuario.listarTodos());
view.forward(request, response);
} else if (acao.equals("download")) {
BeanCursoJsp usuario = daoUsuario.consultar(user);
if (usuario != null) {
String contentType = "";
byte[] fileBytes = null;
if (tipo.equals("imagem")) {
contentType = usuario.getContentType();
fileBytes = new Base64().decodeBase64(usuario.getFotoBase64());
response.setHeader("Content-Disposition",
"attachment; filename = arquivo." + contentType.split("\\/")[1]);
}
if (tipo.equals("pdf")) {
contentType = usuario.getContentTypePdf();
fileBytes = new Base64().decodeBase64(usuario.getPdfBase64());
response.setHeader("Content-Disposition",
"attachment; filename = pdf." + contentType.split("\\/")[1]);
}
InputStream is = new ByteArrayInputStream(fileBytes);
int read = 0;
byte[] bytes = new byte[1024];
OutputStream os = response.getOutputStream();
while ((read = is.read(bytes)) != -1) {
os.write(bytes, 0, read);
}
os.flush();
os.close();
}
RequestDispatcher view = request.getRequestDispatcher("cadastroUsuario.jsp");
request.setAttribute("usuarios", daoUsuario.listarTodos());
view.forward(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
BeanCursoJsp usuario = new BeanCursoJsp();
String acao = request.getParameter("acao");
boolean podeInserir = true;
if (acao != null && acao.equalsIgnoreCase("resetar")) {
try {
RequestDispatcher view = request.getRequestDispatcher("cadastroUsuario.jsp");
request.setAttribute("usuarios", daoUsuario.listarTodos());
view.forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
} else {
String id = request.getParameter("id");
String nome = request.getParameter("nome");
String login = request.getParameter("login");
String senha = request.getParameter("senha");
String telefoneString = request.getParameter("telefone");
String cep = request.getParameter("cep");
String rua = request.getParameter("rua");
String bairro = request.getParameter("bairro");
String cidade = request.getParameter("cidade");
String uf = request.getParameter("uf");
String ibge = request.getParameter("ibge");
usuario.setId(!id.isEmpty() ? Long.parseLong(id) : null);
usuario.setLogin(login);
usuario.setPassword(<PASSWORD>);
usuario.setNome(nome);
usuario.setTelefone(!telefoneString.isEmpty() ? Long.parseLong(telefoneString) : null);
usuario.setCep(cep);
usuario.setRua(rua);
usuario.setBairro(bairro);
usuario.setCidade(cidade);
usuario.setUf(uf);
usuario.setIbge(ibge);
List<String> msg = new ArrayList<String>();
try {
if (ServletFileUpload.isMultipartContent(request)) {
Part imagemFoto = request.getPart("foto");
if (imagemFoto != null) {
String fotoBase64 = new Base64()
.encodeBase64String(converteStremParaByte(imagemFoto.getInputStream()));
usuario.setFotoBase64(fotoBase64);
usuario.setContentType(imagemFoto.getContentType());
}
/**
* Processamento de pdf
*/
Part pdf = request.getPart("pdf");
if (pdf != null) {
String pdf64 = new Base64().encodeBase64String(converteStremParaByte(pdf.getInputStream()));
usuario.setPdfBase64(pdf64);
usuario.setContentTypePdf(pdf.getContentType());
}
}
if (login == null || login.isEmpty()) {
String msgLogin = "Campo obrigatório: LOGIN";
msg.add(msgLogin);
podeInserir = false;
} else if (senha == null || senha.isEmpty()) {
String msgSenha = "Campo obrigatório: SENHA";
msg.add(msgSenha);
podeInserir = false;
} else if (telefoneString == null || telefoneString.isEmpty()) {
String msgTelefone = "Campo obrigatório: TELEFONE";
msg.add(msgTelefone);
podeInserir = false;
} else if (nome == null || nome.isEmpty()) {
String msgNome = "Campo obrigatório: NOME";
msg.add(msgNome);
podeInserir = false;
} else if (id == null || id.isEmpty() && !daoUsuario.validarLogin(login)) {
String msgLogin = " Usuário já existe com o mesmo login. Cadastre outro login.";
msg.add(msgLogin);
podeInserir = false;
} else if (id == null || id.isEmpty() && !daoUsuario.validarSenha(senha)) {
String msgSenha = " Senha já existe para outro usuário.";
msg.add(msgSenha);
podeInserir = false;
}
if (msg != null && !podeInserir) {
request.setAttribute("msg", msg);
request.setAttribute("user", usuario);
} else if (id == null || id.isEmpty() && daoUsuario.validarLogin(login) && podeInserir) {
daoUsuario.salvar(usuario);
String msgSalvo = "Salvo com sucesso";
msg.add(msgSalvo);
podeInserir = true;
System.out.println("Usuario salvo");
} else if (id != null && !id.isEmpty()) {
if (!daoUsuario.validarLoginUpdate(login, id)) {
String msgUpdate = " Login já existe em outra conta de usuário. Atualize outro login.";
msg.add(msgUpdate);
podeInserir = false;
} else {
daoUsuario.atualizar(usuario);
System.out.println("Usuario Atualizado");
String msgAtualizado = "Atualizado com sucesso";
msg.add(msgAtualizado);
podeInserir = true;
}
}
if (msg != null && podeInserir) {
request.setAttribute("msg", msg);
}
RequestDispatcher view = request.getRequestDispatcher("cadastroUsuario.jsp");
request.setAttribute("usuarios", daoUsuario.listarTodos());
request.setAttribute("podeInserir", podeInserir);
view.forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* Converte para um array de Bytes
*
* @param imagem
* @return
* @throws IOException
*/
private byte[] converteStremParaByte(InputStream imagem) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int reads = imagem.read();
while (reads != -1) {
baos.write(reads);
reads = imagem.read();
}
return baos.toByteArray();
}
}
| 8,924 | 0.687549 | 0.682497 | 278 | 31.039568 | 24.191872 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.489209 | false | false | 3 |
05ecae7f6f99f43d44ab860f753fc73049026e5d | 21,028,159,946,807 | b3faa5d23008f915c4574b707e7e231e4a3aa8d4 | /RCS/InputMethod/src/com/buxiubianfu/IME/command/CutCommand.java | 8d7fb0fe333d105bd89222d2518874372a07d426 | [] | no_license | DebugOfTheRoad/android | https://github.com/DebugOfTheRoad/android | 98ad4fbb75d350a540baac17ff34f4fa2a7bbe9c | 973727203a7716c4a9b5e08482953f2f86eb7f0c | refs/heads/master | 2021-06-04T16:14:26.763000 | 2016-10-04T16:58:05 | 2016-10-04T16:58:05 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.buxiubianfu.IME.command;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.view.inputmethod.InputConnection;
import com.buxiubianfu.IME.command.Data.CommandData;
public class CutCommand extends BaseCommand {
public InputConnection _InputConnection;
public ClipboardManager _ClipboardManager;
public OutputStream _oStream;
public CutCommand(InputConnection inputConnection,
ClipboardManager clipboardManager, OutputStream oStream)
{
_InputConnection=inputConnection;
_ClipboardManager=clipboardManager;
_oStream=oStream;
}
@SuppressLint("NewApi")
@Override
public String Do( CommandData commandData) {
try {
CharSequence clipText = _InputConnection.getSelectedText(0);
String CopyText = clipText.toString();
_InputConnection.commitText("", 1);
String SendText = CopyText;
_ClipboardManager.setPrimaryClip(ClipData.newPlainText(null,
CopyText));
super.send(CopyText,_oStream);
} catch (UnsupportedEncodingException e) {
} catch (IOException e) {
}
return "";
}
}
| UTF-8 | Java | 1,211 | java | CutCommand.java | Java | [] | null | [] | package com.buxiubianfu.IME.command;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.view.inputmethod.InputConnection;
import com.buxiubianfu.IME.command.Data.CommandData;
public class CutCommand extends BaseCommand {
public InputConnection _InputConnection;
public ClipboardManager _ClipboardManager;
public OutputStream _oStream;
public CutCommand(InputConnection inputConnection,
ClipboardManager clipboardManager, OutputStream oStream)
{
_InputConnection=inputConnection;
_ClipboardManager=clipboardManager;
_oStream=oStream;
}
@SuppressLint("NewApi")
@Override
public String Do( CommandData commandData) {
try {
CharSequence clipText = _InputConnection.getSelectedText(0);
String CopyText = clipText.toString();
_InputConnection.commitText("", 1);
String SendText = CopyText;
_ClipboardManager.setPrimaryClip(ClipData.newPlainText(null,
CopyText));
super.send(CopyText,_oStream);
} catch (UnsupportedEncodingException e) {
} catch (IOException e) {
}
return "";
}
}
| 1,211 | 0.786953 | 0.785301 | 42 | 27.833334 | 19.359896 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.880952 | false | false | 3 |
8db255e0ff1bbb96dcfa6c3b956cd272de879f35 | 27,565,100,135,247 | a5de97af54055beca26563e0dd1c52d99182d8f6 | /common/common-config/src/main/java/gov/nist/hit/hl7/igamt/common/config/domain/VersionRepresntation.java | 46c4cb7e501b2261e07b71b92dbc569626066bec | [] | no_license | usnistgov/hl7-igamt | https://github.com/usnistgov/hl7-igamt | 77331007562eeb03aad96d17a4b627165ef4cdc5 | dcee50821ea1f3cc2ee9a3ea66709661760bd4f6 | refs/heads/master | 2023-09-02T15:38:18.271000 | 2021-11-29T17:41:35 | 2021-11-29T17:41:35 | 122,214,311 | 10 | 2 | null | false | 2023-07-19T16:50:00 | 2018-02-20T15:10:33 | 2023-04-11T15:22:27 | 2023-07-19T16:49:59 | 70,793 | 6 | 2 | 109 | Java | false | false | package gov.nist.hit.hl7.igamt.common.config.domain;
public class VersionRepresntation {
String value;
public VersionRepresntation(String value) {
super();
this.value = value;
}
}
| UTF-8 | Java | 194 | java | VersionRepresntation.java | Java | [] | null | [] | package gov.nist.hit.hl7.igamt.common.config.domain;
public class VersionRepresntation {
String value;
public VersionRepresntation(String value) {
super();
this.value = value;
}
}
| 194 | 0.726804 | 0.721649 | 13 | 13.923077 | 17.735065 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 3 |
72173cbbc9d1568a5381d8531b3d5b465fd13e56 | 19,421,842,157,442 | 449d76162215a95a793d2a401d74d87fdd599853 | /app/src/main/java/com/rlk/mi/FindPwByEmail.java | ee65b16002cc3c3feb25aa1853b911cd18864e59 | [
"Apache-2.0"
] | permissive | AISHANSHAN/RlkAccount | https://github.com/AISHANSHAN/RlkAccount | 090224b6d53a671fadb5dcd39d03c43fb9b3bb08 | 81b990843bab70ed47e35eb58bc3ddc1a6f7eae2 | refs/heads/master | 2016-09-16T20:42:23.484000 | 2016-07-29T10:06:23 | 2016-07-29T10:06:23 | 64,470,861 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.rlk.mi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.andexert.library.RippleView;
import com.rlk.misdk.account.UserAccountStore;
import com.rlk.misdk.http.HttpCallback;
import com.rlk.misdk.http.HttpResult;
import com.rlk.misdk.utils.Util;
public class FindPwByEmail extends Activity implements OnClickListener {
private ImageView mBack, mCaptchaImage;
private EditText mUsernameEmail, mCaptcha;
private RippleView mSubmit;
private UserAccountStore mUserAccountStore;
private Context mContext = this;
private String key;
private Dialog dialog;
TextView mTitle;
int genType = 11;
@Override
protected void onCreate(Bundle arg0) {
// TODO Auto-generated method stub
super.onCreate(arg0);
MyUtil.selectTheme(this);
if (Constants.LAN_AR.equals(Constants.getLocalLanguage(this))
|| Constants.LAN_UR.equals(Constants.getLocalLanguage(this))) {
setContentView(R.layout.find_password_by_email_ar);
} else {
setContentView(R.layout.find_password_by_email);
}
initView();
}
private void initView() {
// TODO Auto-generated method stub
mBack = (ImageView) findViewById(R.id.findPwByEmail_back);
mSubmit = (RippleView) findViewById(R.id.findPwByEmail_submit);
mCaptcha = (EditText) findViewById(R.id.findPwByEmail_captcha);
mTitle = (TextView) findViewById(R.id.findPwByEmail_title);
mCaptchaImage = (ImageView) findViewById(R.id.findPwByEmail_captcha_image);
mUsernameEmail = (EditText) findViewById(R.id.findPwByEmail_username_or_email);
mUserAccountStore = new UserAccountStore(this);
mBack.setOnClickListener(this);
mSubmit.setOnClickListener(this);
mCaptchaImage.setOnClickListener(this);
if ("verifyEmail".equals(getIntent().getStringExtra("type"))) {
mTitle.setText(R.string.verify_email);
mUsernameEmail.setText(getIntent().getStringExtra("email"));
mUsernameEmail.setEnabled(false);
mCaptcha.getShowSoftInputOnFocus();
mCaptcha.setFocusable(true);
mCaptcha.setFocusableInTouchMode(true);
mCaptcha.requestFocus();
genType = 40;
} else {
MyUtil.showSoftInput(mUsernameEmail);
}
mUsernameEmail.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if (hasFocus) {
} else {
String username = mUsernameEmail.getText().toString();
if (!"".equals(username)) {
if (mUsernameEmail.length() < 3) {
mUsernameEmail
.setError(getString(R.string.length_info_error));
} else if (username
.contains("@")
&& !Util.isEmailAccount(username)) {
mUsernameEmail
.setError(getString(R.string.email_error));
}
}
}
}
});
mUserAccountStore.genCaptcha(genType, new HttpCallback() {
@Override
public void httpUploadProcess(long arg0) {
}
@Override
public void httpResult(HttpResult result) {
if (result.mErrorNo == HttpResult.EN_OK) {
Bitmap bmp = (Bitmap) result.getResultObject();
mCaptchaImage.setImageBitmap(bmp);
key = result.getMessage();
Log.e("yzd", "key---" + key);
}
}
@Override
public void httpDownloadProcess(long arg0) {
}
});
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.findPwByEmail_back:
MyUtil.displaySoftInput(FindPwByEmail.this);
finish();
break;
case R.id.findPwByEmail_captcha_image:
mUserAccountStore.genCaptcha(genType, new HttpCallback() {
@Override
public void httpUploadProcess(long arg0) {
}
@Override
public void httpResult(HttpResult result) {
if (result.mErrorNo == HttpResult.EN_OK) {
Bitmap bmp = (Bitmap) result.getResultObject();
mCaptchaImage.setImageBitmap(bmp);
key = result.getMessage();
Log.e("yzd", "key---" + key);
}
}
@Override
public void httpDownloadProcess(long arg0) {
}
});
break;
case R.id.findPwByEmail_submit:
if ("".equals(mUsernameEmail.getText().toString()) || "".equals(mCaptcha.getText().toString())) {
MyUtil.toastShow(mContext, getString(R.string.info_error));
} else if (mUsernameEmail.getText().toString().contains("@")
&& !Util.isEmailAccount(mUsernameEmail.getText().toString())) {
mUsernameEmail.setError(getString(R.string.email_error));
} else if (Util.isConnected(this)) {
if ("verifyEmail".equals(getIntent().getStringExtra("type"))) {
dialog = MyUtil.getDialog(mContext, getString(R.string.loading));
dialog.show();
mUserAccountStore.reSendActiveEmail(MyUtil.getUid(mContext), mUsernameEmail.getText().toString(), getIntent().getStringExtra("username"), mCaptcha.getText()
.toString(), key,new HttpCallback() {
@Override
public void httpResult(HttpResult result) {
dialog.dismiss();
if (result.mErrorNo == HttpResult.EN_OK) {
Intent intent = new Intent();
intent.putExtra("type", "verifyEmail");
intent.setClass(mContext,
FindPwByEmail2.class);
startActivity(intent);
} else {
int status = result.getStatus();
Log.e("yzd","verifyEmail step 1 is "+status);
switch (status){
case 6101:
MyUtil.toastShow(mContext,
getString(R.string.captcha_input_error));
break;
case 6114:
MyUtil.toastShow(mContext,
getString(R.string.error_invalid_email));
break;
}
}
}
@Override
public void httpUploadProcess(long l) {
}
@Override
public void httpDownloadProcess(long l) {
}
});
} else {
dialog = MyUtil.getDialog(mContext, getString(R.string.retrieve_progress));
dialog.show();
mUserAccountStore.findpassword(mUsernameEmail.getText()
.toString(), "en", MyUtil.getBrand(mContext), null, mCaptcha.getText()
.toString(), key, new HttpCallback() {
@Override
public void httpUploadProcess(long arg0) {
// TODO Auto-generated method stub
}
@Override
public void httpResult(HttpResult result) {
// TODO Auto-generated method stub
dialog.dismiss();
if (result.mErrorNo == HttpResult.EN_OK) {
MyUtil.toastShow(mContext,
getString(R.string.retrieve_email_send));
Intent intent = new Intent();
intent.setClass(mContext,
FindPwByEmail2.class);
MyUtil.setUid(mContext, result.getMessage());
startActivity(intent);
} else {
int status = result.getStatus();
switch (status) {
case 6110:
MyUtil.toastShow(mContext,
getString(R.string.user_not_exist));
break;
case 13:
MyUtil.toastShow(mContext,
getString(R.string.service_error));
break;
case 6101:
MyUtil.toastShow(
mContext,
getString(R.string.captcha_input_error));
break;
default:
MyUtil.toastShow(
mContext,
getString(R.string.service_no_response));
break;
}
}
}
@Override
public void httpDownloadProcess(long arg0) {
// TODO Auto-generated method stub
}
});
}
} else
{
MyUtil.toastShow(
mContext,
getString(R.string.network_error));
}
break;
default:
break;
}
}
}
| UTF-8 | Java | 11,657 | java | FindPwByEmail.java | Java | [] | null | [] | package com.rlk.mi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.andexert.library.RippleView;
import com.rlk.misdk.account.UserAccountStore;
import com.rlk.misdk.http.HttpCallback;
import com.rlk.misdk.http.HttpResult;
import com.rlk.misdk.utils.Util;
public class FindPwByEmail extends Activity implements OnClickListener {
private ImageView mBack, mCaptchaImage;
private EditText mUsernameEmail, mCaptcha;
private RippleView mSubmit;
private UserAccountStore mUserAccountStore;
private Context mContext = this;
private String key;
private Dialog dialog;
TextView mTitle;
int genType = 11;
@Override
protected void onCreate(Bundle arg0) {
// TODO Auto-generated method stub
super.onCreate(arg0);
MyUtil.selectTheme(this);
if (Constants.LAN_AR.equals(Constants.getLocalLanguage(this))
|| Constants.LAN_UR.equals(Constants.getLocalLanguage(this))) {
setContentView(R.layout.find_password_by_email_ar);
} else {
setContentView(R.layout.find_password_by_email);
}
initView();
}
private void initView() {
// TODO Auto-generated method stub
mBack = (ImageView) findViewById(R.id.findPwByEmail_back);
mSubmit = (RippleView) findViewById(R.id.findPwByEmail_submit);
mCaptcha = (EditText) findViewById(R.id.findPwByEmail_captcha);
mTitle = (TextView) findViewById(R.id.findPwByEmail_title);
mCaptchaImage = (ImageView) findViewById(R.id.findPwByEmail_captcha_image);
mUsernameEmail = (EditText) findViewById(R.id.findPwByEmail_username_or_email);
mUserAccountStore = new UserAccountStore(this);
mBack.setOnClickListener(this);
mSubmit.setOnClickListener(this);
mCaptchaImage.setOnClickListener(this);
if ("verifyEmail".equals(getIntent().getStringExtra("type"))) {
mTitle.setText(R.string.verify_email);
mUsernameEmail.setText(getIntent().getStringExtra("email"));
mUsernameEmail.setEnabled(false);
mCaptcha.getShowSoftInputOnFocus();
mCaptcha.setFocusable(true);
mCaptcha.setFocusableInTouchMode(true);
mCaptcha.requestFocus();
genType = 40;
} else {
MyUtil.showSoftInput(mUsernameEmail);
}
mUsernameEmail.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if (hasFocus) {
} else {
String username = mUsernameEmail.getText().toString();
if (!"".equals(username)) {
if (mUsernameEmail.length() < 3) {
mUsernameEmail
.setError(getString(R.string.length_info_error));
} else if (username
.contains("@")
&& !Util.isEmailAccount(username)) {
mUsernameEmail
.setError(getString(R.string.email_error));
}
}
}
}
});
mUserAccountStore.genCaptcha(genType, new HttpCallback() {
@Override
public void httpUploadProcess(long arg0) {
}
@Override
public void httpResult(HttpResult result) {
if (result.mErrorNo == HttpResult.EN_OK) {
Bitmap bmp = (Bitmap) result.getResultObject();
mCaptchaImage.setImageBitmap(bmp);
key = result.getMessage();
Log.e("yzd", "key---" + key);
}
}
@Override
public void httpDownloadProcess(long arg0) {
}
});
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.findPwByEmail_back:
MyUtil.displaySoftInput(FindPwByEmail.this);
finish();
break;
case R.id.findPwByEmail_captcha_image:
mUserAccountStore.genCaptcha(genType, new HttpCallback() {
@Override
public void httpUploadProcess(long arg0) {
}
@Override
public void httpResult(HttpResult result) {
if (result.mErrorNo == HttpResult.EN_OK) {
Bitmap bmp = (Bitmap) result.getResultObject();
mCaptchaImage.setImageBitmap(bmp);
key = result.getMessage();
Log.e("yzd", "key---" + key);
}
}
@Override
public void httpDownloadProcess(long arg0) {
}
});
break;
case R.id.findPwByEmail_submit:
if ("".equals(mUsernameEmail.getText().toString()) || "".equals(mCaptcha.getText().toString())) {
MyUtil.toastShow(mContext, getString(R.string.info_error));
} else if (mUsernameEmail.getText().toString().contains("@")
&& !Util.isEmailAccount(mUsernameEmail.getText().toString())) {
mUsernameEmail.setError(getString(R.string.email_error));
} else if (Util.isConnected(this)) {
if ("verifyEmail".equals(getIntent().getStringExtra("type"))) {
dialog = MyUtil.getDialog(mContext, getString(R.string.loading));
dialog.show();
mUserAccountStore.reSendActiveEmail(MyUtil.getUid(mContext), mUsernameEmail.getText().toString(), getIntent().getStringExtra("username"), mCaptcha.getText()
.toString(), key,new HttpCallback() {
@Override
public void httpResult(HttpResult result) {
dialog.dismiss();
if (result.mErrorNo == HttpResult.EN_OK) {
Intent intent = new Intent();
intent.putExtra("type", "verifyEmail");
intent.setClass(mContext,
FindPwByEmail2.class);
startActivity(intent);
} else {
int status = result.getStatus();
Log.e("yzd","verifyEmail step 1 is "+status);
switch (status){
case 6101:
MyUtil.toastShow(mContext,
getString(R.string.captcha_input_error));
break;
case 6114:
MyUtil.toastShow(mContext,
getString(R.string.error_invalid_email));
break;
}
}
}
@Override
public void httpUploadProcess(long l) {
}
@Override
public void httpDownloadProcess(long l) {
}
});
} else {
dialog = MyUtil.getDialog(mContext, getString(R.string.retrieve_progress));
dialog.show();
mUserAccountStore.findpassword(mUsernameEmail.getText()
.toString(), "en", MyUtil.getBrand(mContext), null, mCaptcha.getText()
.toString(), key, new HttpCallback() {
@Override
public void httpUploadProcess(long arg0) {
// TODO Auto-generated method stub
}
@Override
public void httpResult(HttpResult result) {
// TODO Auto-generated method stub
dialog.dismiss();
if (result.mErrorNo == HttpResult.EN_OK) {
MyUtil.toastShow(mContext,
getString(R.string.retrieve_email_send));
Intent intent = new Intent();
intent.setClass(mContext,
FindPwByEmail2.class);
MyUtil.setUid(mContext, result.getMessage());
startActivity(intent);
} else {
int status = result.getStatus();
switch (status) {
case 6110:
MyUtil.toastShow(mContext,
getString(R.string.user_not_exist));
break;
case 13:
MyUtil.toastShow(mContext,
getString(R.string.service_error));
break;
case 6101:
MyUtil.toastShow(
mContext,
getString(R.string.captcha_input_error));
break;
default:
MyUtil.toastShow(
mContext,
getString(R.string.service_no_response));
break;
}
}
}
@Override
public void httpDownloadProcess(long arg0) {
// TODO Auto-generated method stub
}
});
}
} else
{
MyUtil.toastShow(
mContext,
getString(R.string.network_error));
}
break;
default:
break;
}
}
}
| 11,657 | 0.44351 | 0.440422 | 275 | 41.389091 | 27.696495 | 180 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.527273 | false | false | 3 |
4580c9ccf3c4c49a9513497c77842457afaf4ca0 | 27,298,812,145,366 | c1823200be91b33d048f73aa08eb164c04399a65 | /src/main/java/com/ssafy/vue/dao/noticeDao.java | 946bd24bdc283925b60d1a074520c22c5a69b90e | [] | no_license | hyaherl/HappyHouse | https://github.com/hyaherl/HappyHouse | ae02feeb44e41b7effd9c67fbf3dbf405e4e3f0a | 2793857fd8c3a1dcfbed52854f2d4decb63cf34c | refs/heads/master | 2022-12-25T04:22:27.608000 | 2020-09-02T09:40:16 | 2020-09-02T09:40:16 | 292,240,914 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ssafy.vue.dao;
import java.sql.SQLException;
import java.util.List;
import com.ssafy.vue.dto.notice;
public interface noticeDao {
List<notice> listnotice() throws SQLException;
notice contentNotice(int content) throws SQLException;
void noticeWrite(notice nt) throws SQLException;
}
| UTF-8 | Java | 304 | java | noticeDao.java | Java | [] | null | [] | package com.ssafy.vue.dao;
import java.sql.SQLException;
import java.util.List;
import com.ssafy.vue.dto.notice;
public interface noticeDao {
List<notice> listnotice() throws SQLException;
notice contentNotice(int content) throws SQLException;
void noticeWrite(notice nt) throws SQLException;
}
| 304 | 0.789474 | 0.789474 | 15 | 19.266666 | 19.793827 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 3 |
a631079da840a799f256b082ca31c5a4733a2aa4 | 27,298,812,147,097 | 935918151da809461215f7c37b03a9254403a3ca | /src/main/java/controle/Genetica.java | d5168fdda5d15112f7f967fa7e54b490967bb715 | [] | no_license | mateusmed/monografia | https://github.com/mateusmed/monografia | 673f661e355d3e37471633ce1386e73bc13b15bb | efcf148af75be6a29e965d64a4adbded98492ef1 | refs/heads/master | 2020-05-29T22:29:04.982000 | 2018-11-25T21:44:32 | 2018-11-25T21:44:32 | 189,409,696 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package controle;
import entity.Individuo;
import java.util.*;
import java.util.logging.Logger;
public class Genetica {
private List<Integer> l1 = Arrays.asList(1, 2, 3);
private List<Integer> l2 = Arrays.asList(1, 3, 2);
private List<Integer> l3 = Arrays.asList(2, 1, 3);
private List<Integer> l4 = Arrays.asList(2, 3, 1);
private List<Integer> l5 = Arrays.asList(3, 1, 2);
private List<Integer> l6 = Arrays.asList(3, 2, 1);
private List<List<Integer>> listaDeListas;
//tentar ver uma forma melhor de tornar isso aqui estático
public Genetica() {
listaDeListas = new ArrayList<List<Integer>>();
listaDeListas.add(l1);
listaDeListas.add(l2);
listaDeListas.add(l3);
listaDeListas.add(l4);
listaDeListas.add(l5);
listaDeListas.add(l6);
}
private List<Integer> pontosDeCorte(){
Random gerador = new Random();
int tamanhoLista = listaDeListas.size();
return listaDeListas.get(gerador.nextInt(tamanhoLista));
}
/**
* seria interessante já atribuir a mutação ? ainda não.
* nem todos devem sofrer mutação, podemos tentar depois
* mais pra frente.
* **/
private List<Individuo> individuosValidos(Individuo filhoA, Individuo filhoB){
List<Individuo> filhos = new ArrayList<Individuo>();
if(filhoA.valido()){
// a.mutação
filhos.add(filhoA);
}
if(filhoB.valido()){
//b.mutação
filhos.add(filhoB);
}
return filhos;
}
public void mutacaoAleatoria(List<Individuo> individuos, Integer qtdMutacao, Logger log){
Random gerador = new Random();
for (int i = 0 ; i < qtdMutacao; i++){
int pos = gerador.nextInt(individuos.size() + 1);
// faça a mutação apenas se existir a posição
if( pos < individuos.size()){
individuos.get(pos).mutacao(log);
}
}
}
public List<Individuo> cruzamento(Individuo a, Individuo b){
List<Integer> pontosDeCorte = pontosDeCorte();
for (Integer corte : pontosDeCorte){
if (corte == 0) {
Individuo filhoZero1 = new Individuo(a.getForca(), b.getInteligencia(), b.getAgilidade(), b.getDestreza());
Individuo filhoZero2 = new Individuo(b.getForca(), a.getInteligencia(), a.getAgilidade(), a.getDestreza());
List<Individuo> filhosValidos = individuosValidos(filhoZero1, filhoZero2);
if(!filhosValidos.isEmpty()){
return filhosValidos;
}
}
if (corte == 1) {
Individuo filhoUm1 = new Individuo(a.getForca(), a.getInteligencia(), b.getAgilidade(), b.getDestreza());
Individuo filhoUm2 = new Individuo(b.getForca(), b.getInteligencia(), a.getAgilidade(), a.getDestreza());
List<Individuo> filhosValidos = individuosValidos(filhoUm1, filhoUm2);
if(!filhosValidos.isEmpty()){
return filhosValidos;
}
}
if (corte == 2) {
Individuo filhoDois1 = new Individuo(a.getForca(), a.getInteligencia(), a.getAgilidade(), b.getDestreza());
Individuo filhoDois2 = new Individuo(b.getForca(), b.getInteligencia(), b.getAgilidade(), a.getDestreza());
List<Individuo> filhosValidos = individuosValidos(filhoDois1, filhoDois2);
if(!filhosValidos.isEmpty()){
return filhosValidos;
}
}
}
System.out.println("em nenhum dos 3 cortes o individuo é valido");
return null;
}
}
| UTF-8 | Java | 3,791 | java | Genetica.java | Java | [] | null | [] | package controle;
import entity.Individuo;
import java.util.*;
import java.util.logging.Logger;
public class Genetica {
private List<Integer> l1 = Arrays.asList(1, 2, 3);
private List<Integer> l2 = Arrays.asList(1, 3, 2);
private List<Integer> l3 = Arrays.asList(2, 1, 3);
private List<Integer> l4 = Arrays.asList(2, 3, 1);
private List<Integer> l5 = Arrays.asList(3, 1, 2);
private List<Integer> l6 = Arrays.asList(3, 2, 1);
private List<List<Integer>> listaDeListas;
//tentar ver uma forma melhor de tornar isso aqui estático
public Genetica() {
listaDeListas = new ArrayList<List<Integer>>();
listaDeListas.add(l1);
listaDeListas.add(l2);
listaDeListas.add(l3);
listaDeListas.add(l4);
listaDeListas.add(l5);
listaDeListas.add(l6);
}
private List<Integer> pontosDeCorte(){
Random gerador = new Random();
int tamanhoLista = listaDeListas.size();
return listaDeListas.get(gerador.nextInt(tamanhoLista));
}
/**
* seria interessante já atribuir a mutação ? ainda não.
* nem todos devem sofrer mutação, podemos tentar depois
* mais pra frente.
* **/
private List<Individuo> individuosValidos(Individuo filhoA, Individuo filhoB){
List<Individuo> filhos = new ArrayList<Individuo>();
if(filhoA.valido()){
// a.mutação
filhos.add(filhoA);
}
if(filhoB.valido()){
//b.mutação
filhos.add(filhoB);
}
return filhos;
}
public void mutacaoAleatoria(List<Individuo> individuos, Integer qtdMutacao, Logger log){
Random gerador = new Random();
for (int i = 0 ; i < qtdMutacao; i++){
int pos = gerador.nextInt(individuos.size() + 1);
// faça a mutação apenas se existir a posição
if( pos < individuos.size()){
individuos.get(pos).mutacao(log);
}
}
}
public List<Individuo> cruzamento(Individuo a, Individuo b){
List<Integer> pontosDeCorte = pontosDeCorte();
for (Integer corte : pontosDeCorte){
if (corte == 0) {
Individuo filhoZero1 = new Individuo(a.getForca(), b.getInteligencia(), b.getAgilidade(), b.getDestreza());
Individuo filhoZero2 = new Individuo(b.getForca(), a.getInteligencia(), a.getAgilidade(), a.getDestreza());
List<Individuo> filhosValidos = individuosValidos(filhoZero1, filhoZero2);
if(!filhosValidos.isEmpty()){
return filhosValidos;
}
}
if (corte == 1) {
Individuo filhoUm1 = new Individuo(a.getForca(), a.getInteligencia(), b.getAgilidade(), b.getDestreza());
Individuo filhoUm2 = new Individuo(b.getForca(), b.getInteligencia(), a.getAgilidade(), a.getDestreza());
List<Individuo> filhosValidos = individuosValidos(filhoUm1, filhoUm2);
if(!filhosValidos.isEmpty()){
return filhosValidos;
}
}
if (corte == 2) {
Individuo filhoDois1 = new Individuo(a.getForca(), a.getInteligencia(), a.getAgilidade(), b.getDestreza());
Individuo filhoDois2 = new Individuo(b.getForca(), b.getInteligencia(), b.getAgilidade(), a.getDestreza());
List<Individuo> filhosValidos = individuosValidos(filhoDois1, filhoDois2);
if(!filhosValidos.isEmpty()){
return filhosValidos;
}
}
}
System.out.println("em nenhum dos 3 cortes o individuo é valido");
return null;
}
}
| 3,791 | 0.581346 | 0.568627 | 131 | 27.80916 | 32.03841 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.633588 | false | false | 3 |
47c5041d4cd921dff35f7867dcbbeced8a5935c8 | 27,221,502,779,115 | d48cfe7bb65c3169dea931f605d62b4340222d75 | /chinahrd-hrbi/base/src/main/java/net/chinahrd/entity/dto/pc/promotionBoard/PromotionTotalDto.java | 798521debc79d32e0b83f21508e8185b21dc69ae | [] | no_license | a559927z/doc | https://github.com/a559927z/doc | 7b65aeff1d4606bab1d7f71307d6163b010a226d | 04e812838a5614ed78f8bbfa16a377e7398843fc | refs/heads/master | 2022-12-23T12:09:32.360000 | 2019-07-15T17:52:54 | 2019-07-15T17:52:54 | 195,972,411 | 0 | 0 | null | false | 2022-12-16T07:47:50 | 2019-07-09T09:02:38 | 2019-07-15T17:53:19 | 2022-12-16T07:47:46 | 127,475 | 0 | 0 | 55 | JavaScript | false | false | package net.chinahrd.entity.dto.pc.promotionBoard;
import java.io.Serializable;
import java.util.Date;
/**
* Created by Administrator on 2016/7/14.
*/
public class PromotionTotalDto implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Date getTotalDate() {
return totalDate;
}
public void setTotalDate(Date totalDate) {
this.totalDate = totalDate;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
private String userName;
private Date totalDate;
private Integer total;
}
| UTF-8 | Java | 851 | java | PromotionTotalDto.java | Java | [] | null | [] | package net.chinahrd.entity.dto.pc.promotionBoard;
import java.io.Serializable;
import java.util.Date;
/**
* Created by Administrator on 2016/7/14.
*/
public class PromotionTotalDto implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Date getTotalDate() {
return totalDate;
}
public void setTotalDate(Date totalDate) {
this.totalDate = totalDate;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
private String userName;
private Date totalDate;
private Integer total;
}
| 851 | 0.620447 | 0.611046 | 41 | 18.756098 | 17.372225 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.414634 | false | false | 3 |
d1a7b9df02b63fa5e8db904ded32fae088a3db2d | 39,213,051,432,601 | 9cde12e8bbb75477d0fc9e3a24d487d05ed094e6 | /app/src/main/java/pem/tema4/vista/VistaAgregacion.java | 612770251a4add0bcf52adf8dfc34c14fbbc4aa1 | [] | no_license | eche23/Recetas-PA2.S3 | https://github.com/eche23/Recetas-PA2.S3 | 86b81c8503894d4bc43857ca34054599cabee4a2 | 8ed3199326d660fb45dc280f3bd0b01ee88a7cb4 | refs/heads/master | 2020-04-10T10:26:58.752000 | 2018-12-08T18:22:14 | 2018-12-08T18:22:14 | 160,966,842 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pem.tema4.vista;
import pem.tema4.AppMediador;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
public class VistaAgregacion extends AppCompatActivity implements IVistaAgregacion {
private AppMediador appMediador;
private EditText nombre, identificador, aparato;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vista_agregacion);
appMediador = AppMediador.getInstance();
// TODO Añadir el codigo necesario para que el AppMediador conozca a este objeto.
appMediador.setVistaAgregacion(this);
nombre = (EditText) this.findViewById(R.id.nombre);
identificador = (EditText) this.findViewById(R.id.identificador);
aparato = (EditText) this.findViewById(R.id.aparato);
}
@Override
protected void onDestroy() {
super.onDestroy();
appMediador.removePresentadorAgregacion();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.vista_agregacion, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_guardar) {
// TODO Solicitar al presentador de agregacion que trate la opcion correspondiente a guardar receta.
appMediador.getPresentadorAgregacion().tratarGuardar();
}
return super.onOptionsItemSelected(item);
}
// TODO Implementar el metodo getNombre() que devuelva el nombre almacenado en el objeto EditText
// con identificador "nombre" de la vista.
@Override
public String getNombre() {
return nombre.getText().toString();
}
// TODO Implementar el metodo getIdentificador() que devuelva el nombre almacenado en el objeto EditText
// con identificador "identificador" de la vista.
@Override
public String getIdentificador() {
return identificador.getText().toString();
}
// TODO Implementar el metodo getAparato() que devuelva el nombre almacenado en el objeto EditText
// con identificador "aparato" de la vista.
@Override
public String getAparato() {
return aparato.getText().toString();
}
}
| UTF-8 | Java | 2,294 | java | VistaAgregacion.java | Java | [] | null | [] | package pem.tema4.vista;
import pem.tema4.AppMediador;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
public class VistaAgregacion extends AppCompatActivity implements IVistaAgregacion {
private AppMediador appMediador;
private EditText nombre, identificador, aparato;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vista_agregacion);
appMediador = AppMediador.getInstance();
// TODO Añadir el codigo necesario para que el AppMediador conozca a este objeto.
appMediador.setVistaAgregacion(this);
nombre = (EditText) this.findViewById(R.id.nombre);
identificador = (EditText) this.findViewById(R.id.identificador);
aparato = (EditText) this.findViewById(R.id.aparato);
}
@Override
protected void onDestroy() {
super.onDestroy();
appMediador.removePresentadorAgregacion();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.vista_agregacion, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_guardar) {
// TODO Solicitar al presentador de agregacion que trate la opcion correspondiente a guardar receta.
appMediador.getPresentadorAgregacion().tratarGuardar();
}
return super.onOptionsItemSelected(item);
}
// TODO Implementar el metodo getNombre() que devuelva el nombre almacenado en el objeto EditText
// con identificador "nombre" de la vista.
@Override
public String getNombre() {
return nombre.getText().toString();
}
// TODO Implementar el metodo getIdentificador() que devuelva el nombre almacenado en el objeto EditText
// con identificador "identificador" de la vista.
@Override
public String getIdentificador() {
return identificador.getText().toString();
}
// TODO Implementar el metodo getAparato() que devuelva el nombre almacenado en el objeto EditText
// con identificador "aparato" de la vista.
@Override
public String getAparato() {
return aparato.getText().toString();
}
}
| 2,294 | 0.769734 | 0.768426 | 72 | 30.847221 | 28.334637 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.458333 | false | false | 3 |
cb265dc34a01070e122708db5d6966cdc1a7df7d | 38,130,719,675,343 | 717747955ef23f59ccd4b11d3af9eb8f0f73dc9c | /graphoptimization/src/edu/ucf/cs/multicore/project/datastructure/Queuable.java | 07f03e9cb1f3edcf2a48e145fb0b2401ac77018b | [] | no_license | iramin/multicore | https://github.com/iramin/multicore | 91a04f52a2f93c9a09a2b388d96914fb0dc56093 | 4eaeacf3a2a5ab7b28ad99939afafed52938d72e | refs/heads/master | 2020-06-03T21:14:30.577000 | 2014-11-07T23:02:35 | 2014-11-07T23:02:35 | 24,343,074 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.ucf.cs.multicore.project.datastructure;
public interface Queuable<E> {
public void enqueue(E element);
public E dequeue() throws Exception;
public boolean isEmpty();
}
| UTF-8 | Java | 196 | java | Queuable.java | Java | [] | null | [] | package edu.ucf.cs.multicore.project.datastructure;
public interface Queuable<E> {
public void enqueue(E element);
public E dequeue() throws Exception;
public boolean isEmpty();
}
| 196 | 0.72449 | 0.72449 | 9 | 19.777779 | 18.41363 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.888889 | false | false | 3 |
b8b9e1a57f1316b1baf46d0600ac0da9726552a7 | 37,469,294,716,280 | 9dc8b5d97a95ebd9e6c84818ab67ee1595089f58 | /TradingServiceApplication2/src/main/java/com/cg/tradingservice/controller/InvestorController.java | e4882c758421b0727198d7b1dbd008c916a43ec8 | [] | no_license | S-BHAVANI/TradingServiceApplication | https://github.com/S-BHAVANI/TradingServiceApplication | 6ad0436cdfd5945efe20f6ebcc9ddd206fded35d | e358e1bc9545ba7fd20b78a8ab73f33327b3c14f | refs/heads/master | 2023-01-30T09:15:52.418000 | 2020-12-14T06:26:00 | 2020-12-14T06:26:00 | 314,207,438 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cg.tradingservice.controller;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.cg.tradingservice.exception.ResourceNotFoundException;
import com.cg.tradingservice.model.CompanyManager;
import com.cg.tradingservice.model.Investment;
import com.cg.tradingservice.model.Investor;
import com.cg.tradingservice.model.Stock;
import com.cg.tradingservice.services.InvestorService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
/** This is a Controller class for Investor details
*
* @author Akhil's
* @version 2.0
*
*/
@CrossOrigin(origins = "http://localhost:3000")
@Api(value = "InvestorController", description = "REST Apis related to Investment and Stock Entity!!!!")
@RestController
@RequestMapping("/api/v2")
public class InvestorController {
@Autowired
private InvestorService investor;
private static final Logger logger = LogManager.getLogger(InvestorController.class);
@ApiOperation(value = "Get list of Stocks from the System ", response = Iterable.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Suceess|OK"),
@ApiResponse(code = 401, message = "not authorized!"),
@ApiResponse(code = 403, message = "forbidden!!!"),
@ApiResponse(code = 404, message = "not found!!!") })
/** This method returns list of all Stock details
*
* @return list of all Stock details
*
*
*/
@GetMapping("/stock")
public List<Stock> getstock(){
logger.info("Get all Stock Details");
return investor.getAllStock();
}
@ApiOperation(value = "Getting specific Stock from the System ", response = Stock.class)
/** This method returns stock details
*
* @param delivery - company Id details
*
*
*/
@GetMapping("/stock/{companyId}")
@ResponseBody
public Stock getStockById(@PathVariable("companyId") int companyId){
logger.info("Getting Stock Details");
return investor.getStockById(companyId);
}
@ApiOperation(value = "Getting specific Watchlist Stock from the System ", response = Investment.class)
/** This method returns list of all Investment details
*
* @param delivery - Investor Id details
*
*
*/
@GetMapping("/watchlist/{investorId}")
@ResponseBody
public List<Investment> getwatchlist(@PathVariable("investorId") int investorId){
logger.info("Getting Watchlist Stock Details");
return investor.getwatchList(investorId);
}
@ApiOperation(value = "Adding specific Stock in the Investment ", response = Investment.class)
/** This method adds the Stock details which needs to buy to the investment table
*
* @param delivery - Stock entity details
*
*
*/
@PostMapping("/stock")
@ResponseBody
public Investment buyStock(Investment investment) {
logger.info("Buying the Stock");
return investor.buyStock(investment);
}
@ApiOperation(value = "Deleting specific Stock from the Investment ", response = Investment.class)
/** This method deletes the investment details
*
* @param delivery - investment Id details
*
*
*/
@DeleteMapping("/sell/{investmentId}")
@ResponseBody
public boolean sellStock(@PathVariable(value="investmentId") Integer investmentId) {
logger.info("Selling the Stock");
investor.sellStock( investmentId);
return true;
}
}
| UTF-8 | Java | 4,069 | java | InvestorController.java | Java | [
{
"context": "troller class for Investor details \n * \n * @author Akhil's\n * @version 2.0\n *\n */\n@CrossOrigin(origins = \"h",
"end": 1302,
"score": 0.9994896650314331,
"start": 1295,
"tag": "NAME",
"value": "Akhil's"
}
] | null | [] | package com.cg.tradingservice.controller;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.cg.tradingservice.exception.ResourceNotFoundException;
import com.cg.tradingservice.model.CompanyManager;
import com.cg.tradingservice.model.Investment;
import com.cg.tradingservice.model.Investor;
import com.cg.tradingservice.model.Stock;
import com.cg.tradingservice.services.InvestorService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
/** This is a Controller class for Investor details
*
* @author Akhil's
* @version 2.0
*
*/
@CrossOrigin(origins = "http://localhost:3000")
@Api(value = "InvestorController", description = "REST Apis related to Investment and Stock Entity!!!!")
@RestController
@RequestMapping("/api/v2")
public class InvestorController {
@Autowired
private InvestorService investor;
private static final Logger logger = LogManager.getLogger(InvestorController.class);
@ApiOperation(value = "Get list of Stocks from the System ", response = Iterable.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Suceess|OK"),
@ApiResponse(code = 401, message = "not authorized!"),
@ApiResponse(code = 403, message = "forbidden!!!"),
@ApiResponse(code = 404, message = "not found!!!") })
/** This method returns list of all Stock details
*
* @return list of all Stock details
*
*
*/
@GetMapping("/stock")
public List<Stock> getstock(){
logger.info("Get all Stock Details");
return investor.getAllStock();
}
@ApiOperation(value = "Getting specific Stock from the System ", response = Stock.class)
/** This method returns stock details
*
* @param delivery - company Id details
*
*
*/
@GetMapping("/stock/{companyId}")
@ResponseBody
public Stock getStockById(@PathVariable("companyId") int companyId){
logger.info("Getting Stock Details");
return investor.getStockById(companyId);
}
@ApiOperation(value = "Getting specific Watchlist Stock from the System ", response = Investment.class)
/** This method returns list of all Investment details
*
* @param delivery - Investor Id details
*
*
*/
@GetMapping("/watchlist/{investorId}")
@ResponseBody
public List<Investment> getwatchlist(@PathVariable("investorId") int investorId){
logger.info("Getting Watchlist Stock Details");
return investor.getwatchList(investorId);
}
@ApiOperation(value = "Adding specific Stock in the Investment ", response = Investment.class)
/** This method adds the Stock details which needs to buy to the investment table
*
* @param delivery - Stock entity details
*
*
*/
@PostMapping("/stock")
@ResponseBody
public Investment buyStock(Investment investment) {
logger.info("Buying the Stock");
return investor.buyStock(investment);
}
@ApiOperation(value = "Deleting specific Stock from the Investment ", response = Investment.class)
/** This method deletes the investment details
*
* @param delivery - investment Id details
*
*
*/
@DeleteMapping("/sell/{investmentId}")
@ResponseBody
public boolean sellStock(@PathVariable(value="investmentId") Integer investmentId) {
logger.info("Selling the Stock");
investor.sellStock( investmentId);
return true;
}
}
| 4,069 | 0.740968 | 0.735807 | 138 | 28.485508 | 27.857878 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.362319 | false | false | 3 |
d8c6a096a2601ff9f5540fbed52224bdb14cc177 | 37,469,294,716,863 | 33ce288ecf28744fda0fd20951a1a6587a58b0c8 | /src/java/thinkinjava/test/Mock.java | c95e455500b3374cb4573a8160544653dfecff36 | [] | no_license | yelianghuo/CodeDemo | https://github.com/yelianghuo/CodeDemo | 114ee2d6e28369e4bd4f61522e93686a1f1fb9b7 | 0bb409d58653ea3fa32a6b8f1fc3d7c8e2878aef | refs/heads/master | 2020-05-09T19:50:45.331000 | 2019-04-15T01:03:25 | 2019-04-15T01:03:25 | 181,388,838 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package thinkinjava.test;
/**
* Created by yelianghuo on 2018/7/13.
*/
public class Mock {
private static int getInt(boolean b) {
if(b) {
return 9;
}else {
return 10;
}
}
public static void main(String[] args) {
String a = "aaa";
String b = new String("aaa");
System.out.println(a.equals(b));
}
}
| UTF-8 | Java | 392 | java | Mock.java | Java | [
{
"context": "package thinkinjava.test;\n\n/**\n * Created by yelianghuo on 2018/7/13.\n */\npublic class Mock {\n\n privat",
"end": 55,
"score": 0.9991762042045593,
"start": 45,
"tag": "USERNAME",
"value": "yelianghuo"
}
] | null | [] | package thinkinjava.test;
/**
* Created by yelianghuo on 2018/7/13.
*/
public class Mock {
private static int getInt(boolean b) {
if(b) {
return 9;
}else {
return 10;
}
}
public static void main(String[] args) {
String a = "aaa";
String b = new String("aaa");
System.out.println(a.equals(b));
}
}
| 392 | 0.510204 | 0.484694 | 22 | 16.772728 | 15.165546 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.272727 | false | false | 3 |
551b6bbdb08fc98e72e457b14285b2085298cb1b | 39,290,360,842,415 | 9c8b66ed6c8281b6c1827e356589d875bb9027da | /TestNG2/src/test/java/com/practice2/GmailTest.java | 4ae8d0b086e5328ce884e5ed8b0f4b52e86893a7 | [] | no_license | Mehmetjan/seleniumPractice | https://github.com/Mehmetjan/seleniumPractice | 8b29d13894bc08babc6fbb3d6f0e5e3cc51793f2 | 1673f268aa0b1652dcd1d2c977c7dccb0eb8e34c | refs/heads/main | 2023-05-05T13:26:51.292000 | 2021-05-29T01:50:33 | 2021-05-29T01:50:33 | 371,857,405 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.practice2;
import org.openqa.selenium.By;
import org.testng.annotations.Test;
public class GmailTest extends TestBase {
@Test
public void gmail() {
driver.get("https://www.gmail.com");
driver.findElement(By.xpath("//*[@id=\"identifierId\"]")).sendKeys("mbbugra1986");
driver.findElement(By.xpath("//*[@id=\"yDmH0d\"]")).click();
}
@Test
public void recoverPswd() {
driver.findElement(By.xpath("//*[@id=\"yDmH0d\"]")).click();
}
}
| UTF-8 | Java | 463 | java | GmailTest.java | Java | [
{
"context": "(By.xpath(\"//*[@id=\\\"identifierId\\\"]\")).sendKeys(\"mbbugra1986\");\n\t\tdriver.findElement(By.xpath(\"//*[@id=\\\"yDmH0",
"end": 286,
"score": 0.9800621867179871,
"start": 275,
"tag": "PASSWORD",
"value": "mbbugra1986"
}
] | null | [] | package com.practice2;
import org.openqa.selenium.By;
import org.testng.annotations.Test;
public class GmailTest extends TestBase {
@Test
public void gmail() {
driver.get("https://www.gmail.com");
driver.findElement(By.xpath("//*[@id=\"identifierId\"]")).sendKeys("<PASSWORD>");
driver.findElement(By.xpath("//*[@id=\"yDmH0d\"]")).click();
}
@Test
public void recoverPswd() {
driver.findElement(By.xpath("//*[@id=\"yDmH0d\"]")).click();
}
}
| 462 | 0.667387 | 0.652268 | 22 | 20.045454 | 24.296421 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.954545 | false | false | 3 |
0e4160f0a2db0d50193c62868b53db8993bf8c0e | 19,610,820,734,453 | 2d8aaab79eb7931ef844b8aa4c1fec1a9b7342e8 | /TEST/src/IO/ReadConsole.java | 5b5d51a9883b0f8c6b28bde2e77b3f685b0f8e38 | [] | no_license | jyotijava80/TestProj | https://github.com/jyotijava80/TestProj | 7864c18d2118b2a69add342f9c76d0dd6412aa81 | f48421adcd74bcc935021d7147d0cd1304e206e4 | refs/heads/master | 2021-01-20T08:55:41.656000 | 2018-02-19T18:35:12 | 2018-02-19T18:35:12 | 101,575,155 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package IO;
import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStreamReader;
public class ReadConsole {
public static void main(String[] args) {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.println(br.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| UTF-8 | Java | 511 | java | ReadConsole.java | Java | [] | null | [] | package IO;
import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStreamReader;
public class ReadConsole {
public static void main(String[] args) {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.println(br.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| 511 | 0.655577 | 0.655577 | 28 | 16.25 | 18.280796 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.428571 | false | false | 3 |
8ec13c7d5c865d24ee60d874961724b448caa59b | 36,137,854,865,434 | d27c392be40502f56113d7e7e0bcb35f85d4acd9 | /springmvc-01-hello/src/main/java/com/jiang/controller/FirstController.java | b3b332aa2dfe31fc93616cbef2f86c08a8673b8c | [] | no_license | CodePen9/SpringMVC-code | https://github.com/CodePen9/SpringMVC-code | 3a7ecc6d577f70d42ef5f83caf3162fdab3b8ce4 | b03ea45a1ee9af881ab1de65d1d2a2972db74f8a | refs/heads/master | 2022-11-14T00:37:25.679000 | 2020-07-06T04:34:29 | 2020-07-06T04:34:29 | 277,442,634 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jiang.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* @Title:
* @author: JiangPeng
*/
@Controller
public class FirstController {
/*
1.告诉SpringMVC这是一个处理器,可以处理请求;
@Controller 标识那个组件是控制器
*/
//@RequestMapping:请求映射注解 /hello 表示当前项目下的hello请求
@RequestMapping("/hello")
public String myFirstRequest(){
System.out.println("request recover....");
return "hello";
}
@RequestMapping(value = "/demo",method = RequestMethod.POST)
public String demo01(){
return "demo";
}
}
| UTF-8 | Java | 788 | java | FirstController.java | Java | [
{
"context": "otation.RequestMethod;\n\n/**\n * @Title:\n * @author: JiangPeng\n */\n@Controller\npublic class FirstController {\n ",
"end": 243,
"score": 0.9998266696929932,
"start": 234,
"tag": "NAME",
"value": "JiangPeng"
}
] | null | [] | package com.jiang.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* @Title:
* @author: JiangPeng
*/
@Controller
public class FirstController {
/*
1.告诉SpringMVC这是一个处理器,可以处理请求;
@Controller 标识那个组件是控制器
*/
//@RequestMapping:请求映射注解 /hello 表示当前项目下的hello请求
@RequestMapping("/hello")
public String myFirstRequest(){
System.out.println("request recover....");
return "hello";
}
@RequestMapping(value = "/demo",method = RequestMethod.POST)
public String demo01(){
return "demo";
}
}
| 788 | 0.684286 | 0.68 | 29 | 23.137932 | 20.595821 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.275862 | false | false | 3 |
5360f0b039fba8acb4c242ca96b4eae8a64914c1 | 36,301,063,626,095 | ca5944c1ecada66b5a98db133c299821d8b48c06 | /app/src/main/java/com/jaszczurowskip/recyclerlivedata/datasource/ListItemDAO.java | 99d14e950999b2377bec3453d44a2593d2c0f3d9 | [] | no_license | JaszczurowskiP/RecyclerLiveData | https://github.com/JaszczurowskiP/RecyclerLiveData | e93743bb1951f1fae21d778ed23555f1cebb439f | 6decd26f317a856f6cae8e1c4f6e861f6059c540 | refs/heads/master | 2020-04-03T20:37:32.275000 | 2018-11-06T09:20:48 | 2018-11-06T09:20:48 | 155,551,793 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jaszczurowskip.recyclerlivedata.datasource;
import android.arch.lifecycle.LiveData;
import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Delete;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.OnConflictStrategy;
import android.arch.persistence.room.Query;
import java.util.List;
/**
* Created by jaszczurowskip on 15.10.2018
*/
@Dao
public interface ListItemDAO {
@Query("SELECT * FROM ListItem WHERE itemId = :itemId")
LiveData<ListItem> getListItemById(final String itemId);
@Query("SELECT * FROM ListItem ")
LiveData<List<ListItem>> getListItems();
@Insert(onConflict = OnConflictStrategy.REPLACE)
Long insertListItem(final ListItem listItem);
@Delete()
void deleteListItem(final ListItem listItem);
}
| UTF-8 | Java | 820 | java | ListItemDAO.java | Java | [
{
"context": "package com.jaszczurowskip.recyclerlivedata.datasource;\n\nimport android.arch",
"end": 26,
"score": 0.7653098106384277,
"start": 15,
"tag": "USERNAME",
"value": "zczurowskip"
},
{
"context": ".Query;\n\nimport java.util.List;\n\n/**\n * Created by jaszczurowskip on 15.... | null | [] | package com.jaszczurowskip.recyclerlivedata.datasource;
import android.arch.lifecycle.LiveData;
import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Delete;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.OnConflictStrategy;
import android.arch.persistence.room.Query;
import java.util.List;
/**
* Created by jaszczurowskip on 15.10.2018
*/
@Dao
public interface ListItemDAO {
@Query("SELECT * FROM ListItem WHERE itemId = :itemId")
LiveData<ListItem> getListItemById(final String itemId);
@Query("SELECT * FROM ListItem ")
LiveData<List<ListItem>> getListItems();
@Insert(onConflict = OnConflictStrategy.REPLACE)
Long insertListItem(final ListItem listItem);
@Delete()
void deleteListItem(final ListItem listItem);
}
| 820 | 0.768293 | 0.758537 | 29 | 27.241379 | 22.596392 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.413793 | false | false | 3 |
d169b5046923043a84f5ba1e9590f95f2bf37ca9 | 38,912,403,721,995 | ef75b4955143797c1ac30a9bd0ba12a5e63c9a66 | /src/main/java/org/twitter/model/Users.java | f9b0a210c503fb2e88babf57d20d243c095b03e8 | [] | no_license | knhakan/twitter-streaming-api | https://github.com/knhakan/twitter-streaming-api | b56cdc776ea91e4a017f70158e9e2a7f2f98471e | 62e058364bacdf6fcf5d14c41d56e3c6f498c92d | refs/heads/master | 2023-04-29T02:17:42.731000 | 2021-05-18T19:48:54 | 2021-05-18T19:48:54 | 368,641,613 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.twitter.model;
public class Users {
private String name;
private String username;
private String id;
private String created_at;
/**
* @return String
*/
public String getName() {
return name;
}
/**
* @param name
*/
public void setName(String name) {
this.name = name;
}
/**
* @return String
*/
public String getUsername() {
return username;
}
/**
* @param username
*/
public void setUsername(String username) {
this.username = username;
}
/**
* @return String
*/
public String getId() {
return id;
}
/**
* @param id
*/
public void setId(String id) {
this.id = id;
}
/**
* @return String
*/
public String getCreated_at() {
return created_at;
}
/**
* @param created_at
*/
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
/**
* @return String the format chosen is json compatible
*/
@Override
public String toString() {
return "{ \"Name\":" + "\"" + getName() + "\", \"Username\":" + "\"" + getUsername() + "\", \"Id\":" + "\""
+ getId() + "\", \"Created_at\":" + "\"" + getCreated_at() + "\"}";
}
}
| UTF-8 | Java | 1,251 | java | Users.java | Java | [] | null | [] | package org.twitter.model;
public class Users {
private String name;
private String username;
private String id;
private String created_at;
/**
* @return String
*/
public String getName() {
return name;
}
/**
* @param name
*/
public void setName(String name) {
this.name = name;
}
/**
* @return String
*/
public String getUsername() {
return username;
}
/**
* @param username
*/
public void setUsername(String username) {
this.username = username;
}
/**
* @return String
*/
public String getId() {
return id;
}
/**
* @param id
*/
public void setId(String id) {
this.id = id;
}
/**
* @return String
*/
public String getCreated_at() {
return created_at;
}
/**
* @param created_at
*/
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
/**
* @return String the format chosen is json compatible
*/
@Override
public String toString() {
return "{ \"Name\":" + "\"" + getName() + "\", \"Username\":" + "\"" + getUsername() + "\", \"Id\":" + "\""
+ getId() + "\", \"Created_at\":" + "\"" + getCreated_at() + "\"}";
}
}
| 1,251 | 0.521982 | 0.521982 | 84 | 13.892858 | 17.957634 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.202381 | false | false | 3 |
d0fb0891e2eeacf3ef3b8a9097e5ba569ceab8d1 | 34,505,767,313,583 | 83c1b5529a2ec8b8f5953f8d5860efa20cbd5e18 | /app/src/main/java/com/nemator/needle/tasks/db/addPostLocationRequest/AddPostLocationRequestTask.java | c663c931008aba33227b2b8b3ef2422b3147744b | [] | no_license | as00paf/Needle | https://github.com/as00paf/Needle | 6f279fbbb67965728f01d35cacfa81587c5489d2 | 9f6f894897a22237b886314e00a0d03968d9ec48 | refs/heads/master | 2021-01-01T16:59:03.005000 | 2017-07-21T16:55:59 | 2017-07-21T16:55:59 | 34,182,306 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.nemator.needle.tasks.db.addPostLocationRequest;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import com.nemator.needle.broadcastReceiver.PostLocationRequestAlarm;
import com.nemator.needle.data.LocationServiceDBHelper;
import com.nemator.needle.api.result.TaskResult;
import com.nemator.needle.data.PostLocationRequest;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class AddPostLocationRequestTask extends AsyncTask<Void, Void, TaskResult> {
private static final String TAG = "AddPostLocationRequestTask";
private AddPostLocationRequestHandler delegate;
private AddPostLocationRequestParams params;
private LocationServiceDBHelper dbHelper;
public AddPostLocationRequestTask(AddPostLocationRequestParams params, AddPostLocationRequestHandler delegate){
this.params = params;
this.delegate = delegate;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
dbHelper = LocationServiceDBHelper.getInstance(params.context);
}
@Override
protected TaskResult doInBackground(Void... args) {
TaskResult result = new TaskResult();
//DB ENTRY
SQLiteDatabase db = dbHelper.getWritableDatabase();
// Create a new map of values, where column names are the keys
//Date/Time Limit
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
int hours = calendar.getTime().getHours()+1;
int minutes = calendar.getTime().getMinutes() + 10;
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm", Locale.US);
String currentDate = sdf.format(new Date(year-1900, month, day, hours, minutes));
ContentValues values = new ContentValues();
values.put(PostLocationRequest.COLUMN_NAME_TYPE, params.type);
values.put(PostLocationRequest.COLUMN_NAME_DATE, currentDate);
values.put(PostLocationRequest.COLUMN_NAME_EXPIRATION, params.expiration);
values.put(PostLocationRequest.COLUMN_NAME_POSTER_ID, params.posterId);
values.put(PostLocationRequest.COLUMN_NAME_ITEM_ID, params.itemId);
// Insert the new row, returning the primary key value of the new row
long newRowId;
newRowId = db.insert(
PostLocationRequest.TABLE_NAME,
null,
values);
//ALARM
new PostLocationRequestAlarm().setAlarm(params.context, newRowId, params.expiration, params.posterId, params.itemId);
return result;
}
protected void onPostExecute(TaskResult result) {
if(delegate != null){
delegate.onLocationRequestPosted(result);
}
}
public interface AddPostLocationRequestHandler {
void onLocationRequestPosted(TaskResult result);
}
} | UTF-8 | Java | 3,050 | java | AddPostLocationRequestTask.java | Java | [] | null | [] | package com.nemator.needle.tasks.db.addPostLocationRequest;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import com.nemator.needle.broadcastReceiver.PostLocationRequestAlarm;
import com.nemator.needle.data.LocationServiceDBHelper;
import com.nemator.needle.api.result.TaskResult;
import com.nemator.needle.data.PostLocationRequest;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class AddPostLocationRequestTask extends AsyncTask<Void, Void, TaskResult> {
private static final String TAG = "AddPostLocationRequestTask";
private AddPostLocationRequestHandler delegate;
private AddPostLocationRequestParams params;
private LocationServiceDBHelper dbHelper;
public AddPostLocationRequestTask(AddPostLocationRequestParams params, AddPostLocationRequestHandler delegate){
this.params = params;
this.delegate = delegate;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
dbHelper = LocationServiceDBHelper.getInstance(params.context);
}
@Override
protected TaskResult doInBackground(Void... args) {
TaskResult result = new TaskResult();
//DB ENTRY
SQLiteDatabase db = dbHelper.getWritableDatabase();
// Create a new map of values, where column names are the keys
//Date/Time Limit
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
int hours = calendar.getTime().getHours()+1;
int minutes = calendar.getTime().getMinutes() + 10;
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm", Locale.US);
String currentDate = sdf.format(new Date(year-1900, month, day, hours, minutes));
ContentValues values = new ContentValues();
values.put(PostLocationRequest.COLUMN_NAME_TYPE, params.type);
values.put(PostLocationRequest.COLUMN_NAME_DATE, currentDate);
values.put(PostLocationRequest.COLUMN_NAME_EXPIRATION, params.expiration);
values.put(PostLocationRequest.COLUMN_NAME_POSTER_ID, params.posterId);
values.put(PostLocationRequest.COLUMN_NAME_ITEM_ID, params.itemId);
// Insert the new row, returning the primary key value of the new row
long newRowId;
newRowId = db.insert(
PostLocationRequest.TABLE_NAME,
null,
values);
//ALARM
new PostLocationRequestAlarm().setAlarm(params.context, newRowId, params.expiration, params.posterId, params.itemId);
return result;
}
protected void onPostExecute(TaskResult result) {
if(delegate != null){
delegate.onLocationRequestPosted(result);
}
}
public interface AddPostLocationRequestHandler {
void onLocationRequestPosted(TaskResult result);
}
} | 3,050 | 0.70918 | 0.706885 | 87 | 34.068966 | 29.841263 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.724138 | false | false | 3 |
36dfa384dddf8094e1f0e326acb9ed1dda8b22b1 | 39,376,260,195,460 | e4fd6d5fd2ab95320ffbf6ed0d4b94fb2ea0b594 | /src/net/henryhu/andwell/BusyDialog.java | 637e0be6b56bea579f8fad77573ec82f7facd0a1 | [] | no_license | HenryHu/andwell | https://github.com/HenryHu/andwell | d0a20a5ae57e171d81853cb7b3462e54356d88ba | b6731a1331bfaf4e6330da507e00143edde9d8f6 | refs/heads/master | 2021-06-01T13:41:07.661000 | 2018-10-11T03:16:35 | 2018-10-11T03:16:35 | 2,740,115 | 3 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.henryhu.andwell;
import android.app.ProgressDialog;
import android.content.Context;
public class BusyDialog {
ProgressDialog busy;
Context context;
BusyDialog(Context context) {
busy = null;
this.context = context;
}
public void show(String title, String msg) {
hide();
busy = ProgressDialog.show(context, title, msg);
}
public void update(String msg) {
if (busy != null)
busy.setMessage(msg);
}
public void hide() {
if (busy != null) {
busy.dismiss();
busy = null;
}
}
}
| UTF-8 | Java | 549 | java | BusyDialog.java | Java | [] | null | [] | package net.henryhu.andwell;
import android.app.ProgressDialog;
import android.content.Context;
public class BusyDialog {
ProgressDialog busy;
Context context;
BusyDialog(Context context) {
busy = null;
this.context = context;
}
public void show(String title, String msg) {
hide();
busy = ProgressDialog.show(context, title, msg);
}
public void update(String msg) {
if (busy != null)
busy.setMessage(msg);
}
public void hide() {
if (busy != null) {
busy.dismiss();
busy = null;
}
}
}
| 549 | 0.644809 | 0.644809 | 30 | 17.299999 | 13.648321 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.433333 | false | false | 3 |
d5b302ac2ca8e78d59de5dfbdc8b7b6341a8473c | 18,511,309,098,724 | 358dc19a8c1f1bc30adeba16773da6734b6ed62b | /src/main/java/com/msun/dbmigrate/DbmigrateLauncher.java | 9fe5c93ad83c68a3fb8ff773058e079fc6467fed | [
"Apache-2.0"
] | permissive | MSUNorg/dbmigrate | https://github.com/MSUNorg/dbmigrate | 529e6a74b12b0e13e6142f56a364fa7705f803cc | 2d2621d865eb170fbf9b05ba191200c519b2a2dd | refs/heads/master | 2021-01-24T08:33:53.559000 | 2018-06-20T12:34:23 | 2018-06-20T12:34:23 | 69,016,042 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright 2015-2020 msun.com All right reserved.
*/
package com.msun.dbmigrate;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.ErrorPage;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
/**
* @author zxc Aug 28, 2015 11:46:11 AM
*/
@SpringBootApplication
public class DbmigrateLauncher {
public static void main(String[] args) throws Exception {
SpringApplication.run(DbmigrateLauncher.class, args);
}
@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
return new EmbeddedServletContainerCustomizer() {
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
container.addErrorPages(new ErrorPage(HttpStatus.UNAUTHORIZED, "/401.html"),
new ErrorPage(HttpStatus.NOT_FOUND, "/404.html"),
new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500.html"));
}
};
}
}
| UTF-8 | Java | 1,375 | java | DbmigrateLauncher.java | Java | [
{
"context": "pringframework.http.HttpStatus;\r\n\r\n/**\r\n * @author zxc Aug 28, 2015 11:46:11 AM\r\n */\r\n@SpringBootApplica",
"end": 569,
"score": 0.9993167519569397,
"start": 566,
"tag": "USERNAME",
"value": "zxc"
}
] | null | [] | /*
* Copyright 2015-2020 msun.com All right reserved.
*/
package com.msun.dbmigrate;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.ErrorPage;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
/**
* @author zxc Aug 28, 2015 11:46:11 AM
*/
@SpringBootApplication
public class DbmigrateLauncher {
public static void main(String[] args) throws Exception {
SpringApplication.run(DbmigrateLauncher.class, args);
}
@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
return new EmbeddedServletContainerCustomizer() {
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
container.addErrorPages(new ErrorPage(HttpStatus.UNAUTHORIZED, "/401.html"),
new ErrorPage(HttpStatus.NOT_FOUND, "/404.html"),
new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500.html"));
}
};
}
}
| 1,375 | 0.693091 | 0.672 | 37 | 35.162163 | 32.930321 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.486486 | false | false | 3 |
fb51f78d030b3b2dbd084e7ced294ad1c2a82b76 | 27,522,150,465,043 | f09b40c21953b4c0f5c03a0722da17149ed81bc5 | /app/src/main/java/com/example/shouldigoout/dataLayer/HomeAPI.java | 6269684255109bcc21325216bf836a42949d7875 | [] | no_license | AsmaaAlamrawy/should-i-go-out | https://github.com/AsmaaAlamrawy/should-i-go-out | c07f24a307faf888470675d3acff8b3ed8782bdf | 4238a2a6680e1f1efc3d6113010ad4a4434b3c03 | refs/heads/master | 2020-05-24T19:33:10.596000 | 2019-05-19T09:53:57 | 2019-05-19T09:53:57 | 187,437,593 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.shouldigoout.dataLayer;
import com.example.shouldigoout.model.GetWeatherByCoordinatesResponse;
import com.google.android.gms.maps.model.LatLng;
import io.reactivex.Flowable;
public interface HomeAPI {
Flowable<GetWeatherByCoordinatesResponse> getWeatherByCoordinates(LatLng coordinates);
}
| UTF-8 | Java | 317 | java | HomeAPI.java | Java | [] | null | [] | package com.example.shouldigoout.dataLayer;
import com.example.shouldigoout.model.GetWeatherByCoordinatesResponse;
import com.google.android.gms.maps.model.LatLng;
import io.reactivex.Flowable;
public interface HomeAPI {
Flowable<GetWeatherByCoordinatesResponse> getWeatherByCoordinates(LatLng coordinates);
}
| 317 | 0.845426 | 0.845426 | 10 | 30.700001 | 30.4074 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 3 |
ce2ac4692d7698d2064e4b2d96e6540bdd951aa7 | 4,870,492,978,500 | f424d439f5c29ad8716848a731ac5232a65d2576 | /src/main/java/com/feng/util/CpuNumUtils.java | 3a86be0fcdecb315cdff632d961171c2ce5b7953 | [
"Apache-2.0"
] | permissive | fengsam6/webmagic-learn | https://github.com/fengsam6/webmagic-learn | 25c8f78e9420818e8605f9c6522353d5d69f9f9e | b4611de8277a0bc1f6732f45e34be08c23065842 | refs/heads/master | 2022-02-05T04:50:15.461000 | 2022-01-15T08:50:18 | 2022-01-15T08:50:18 | 184,259,441 | 6 | 3 | Apache-2.0 | false | 2022-01-15T08:50:19 | 2019-04-30T12:37:15 | 2021-03-19T03:49:06 | 2022-01-15T08:50:18 | 80,512 | 4 | 1 | 1 | Java | false | false | package com.feng.util;
public class CpuNumUtils {
public static int getCpuNum(){
int n = Runtime.getRuntime().availableProcessors();
return n;
}
}
| UTF-8 | Java | 172 | java | CpuNumUtils.java | Java | [] | null | [] | package com.feng.util;
public class CpuNumUtils {
public static int getCpuNum(){
int n = Runtime.getRuntime().availableProcessors();
return n;
}
}
| 172 | 0.645349 | 0.645349 | 8 | 20.5 | 18.540497 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 3 |
61a501e81b6d8ccd9ee16570601958fe510f1e53 | 10,565,619,549,892 | 454c72743ea748614bc69a7b13fe3eeca707d04b | /base-business/src/main/java/com/bdjbd/service/matches/DataCategoryHandlerService.java | f00e2718c4cd58866c3d57569bef9fb34b523647 | [] | no_license | jojosuccess711/qualification | https://github.com/jojosuccess711/qualification | b82af6232bf489e0c983db3f719b3ee64467430d | c1a6e3588d6b755619626a8f38b927e967766006 | refs/heads/master | 2023-02-05T22:18:39.445000 | 2020-12-23T10:15:41 | 2020-12-23T10:15:41 | 323,866,978 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bdjbd.service.matches;
import com.bdjbd.bo.*;
import com.bdjbd.dao.entity.QaCategory;
import java.util.List;
import java.util.Map;
/**
* @author dbc
* @version 1.0
* @className DataHandlerService 数据处理
* @description TODO
* @date 2020/2/28
**/
public interface DataCategoryHandlerService {
/**
* 创建Category
* @param academic
* @return
*/
Category createCategory(QaCategory academic);
/**
* 创建条件组
* @param categoryId
* @param clause
* @return
*/
ClauseCategory createClauseCategory(String categoryId, MapperClause clause);
/**
* 床见条件项
* @param clauseCategoryId
* @param mapperClause
* @return
*/
Clause createClause(String clauseCategoryId, MapperClause mapperClause);
/***
* 数据分析
* @param academic
* @return
*/
Category analysis(QaCategory academic, List<MapperClause> mapperClauses);
/**
* 关系分组(职称与条件组, 【默认规则:组内或关系,组间与关系】)
* @param academic
* @param clauseCategories
* @return
*/
Map<String, List<ClauseCategory>> relationalGrouping(QaCategory academic, List<ClauseCategory> clauseCategories);
}
| UTF-8 | Java | 1,278 | java | DataCategoryHandlerService.java | Java | [
{
"context": "a.util.List;\nimport java.util.Map;\n\n/**\n * @author dbc\n * @version 1.0\n * @className DataHandlerService ",
"end": 164,
"score": 0.9996857643127441,
"start": 161,
"tag": "USERNAME",
"value": "dbc"
}
] | null | [] | package com.bdjbd.service.matches;
import com.bdjbd.bo.*;
import com.bdjbd.dao.entity.QaCategory;
import java.util.List;
import java.util.Map;
/**
* @author dbc
* @version 1.0
* @className DataHandlerService 数据处理
* @description TODO
* @date 2020/2/28
**/
public interface DataCategoryHandlerService {
/**
* 创建Category
* @param academic
* @return
*/
Category createCategory(QaCategory academic);
/**
* 创建条件组
* @param categoryId
* @param clause
* @return
*/
ClauseCategory createClauseCategory(String categoryId, MapperClause clause);
/**
* 床见条件项
* @param clauseCategoryId
* @param mapperClause
* @return
*/
Clause createClause(String clauseCategoryId, MapperClause mapperClause);
/***
* 数据分析
* @param academic
* @return
*/
Category analysis(QaCategory academic, List<MapperClause> mapperClauses);
/**
* 关系分组(职称与条件组, 【默认规则:组内或关系,组间与关系】)
* @param academic
* @param clauseCategories
* @return
*/
Map<String, List<ClauseCategory>> relationalGrouping(QaCategory academic, List<ClauseCategory> clauseCategories);
}
| 1,278 | 0.647708 | 0.640068 | 56 | 20.035715 | 22.746243 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 3 |
563c5d45218f43bed72090df805f3848584e3491 | 4,054,449,181,378 | bbe34278f3ed99948588984c431e38a27ad34608 | /sources/de/danoeh/antennapod/core/util/-$$Lambda$QueueSorter$tTupnb1yIyh0u8cLyjxslMvwznY.java | fd4c9da195f681d0f51a314c98247b253f90681b | [] | no_license | sapardo10/parcial-pruebas | https://github.com/sapardo10/parcial-pruebas | 7af500f80699697ab9b9291388541c794c281957 | 938a0ceddfc8e0e967a1c7264e08cd9d1fe192f0 | refs/heads/master | 2020-04-28T02:07:08.766000 | 2019-03-10T21:51:36 | 2019-03-10T21:51:36 | 174,885,553 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package de.danoeh.antennapod.core.util;
import de.danoeh.antennapod.core.feed.FeedItem;
import java.util.Comparator;
/* compiled from: lambda */
public final /* synthetic */ class -$$Lambda$QueueSorter$tTupnb1yIyh0u8cLyjxslMvwznY implements Comparator {
public static final /* synthetic */ -$$Lambda$QueueSorter$tTupnb1yIyh0u8cLyjxslMvwznY INSTANCE = new -$$Lambda$QueueSorter$tTupnb1yIyh0u8cLyjxslMvwznY();
private /* synthetic */ -$$Lambda$QueueSorter$tTupnb1yIyh0u8cLyjxslMvwznY() {
}
public final int compare(Object obj, Object obj2) {
return ((FeedItem) obj).getPubDate().compareTo(((FeedItem) obj2).getPubDate());
}
}
| UTF-8 | Java | 656 | java | -$$Lambda$QueueSorter$tTupnb1yIyh0u8cLyjxslMvwznY.java | Java | [] | null | [] | package de.danoeh.antennapod.core.util;
import de.danoeh.antennapod.core.feed.FeedItem;
import java.util.Comparator;
/* compiled from: lambda */
public final /* synthetic */ class -$$Lambda$QueueSorter$tTupnb1yIyh0u8cLyjxslMvwznY implements Comparator {
public static final /* synthetic */ -$$Lambda$QueueSorter$tTupnb1yIyh0u8cLyjxslMvwznY INSTANCE = new -$$Lambda$QueueSorter$tTupnb1yIyh0u8cLyjxslMvwznY();
private /* synthetic */ -$$Lambda$QueueSorter$tTupnb1yIyh0u8cLyjxslMvwznY() {
}
public final int compare(Object obj, Object obj2) {
return ((FeedItem) obj).getPubDate().compareTo(((FeedItem) obj2).getPubDate());
}
}
| 656 | 0.742378 | 0.721037 | 16 | 40 | 45.526093 | 157 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 3 |
398c032fd9ac3952cf448f399d4ad94bfc233528 | 15,857,019,297,006 | dadfba4c79dc3083cda8daf08a036dd3c281124c | /3.JavaMultithreading/src/com/javarush/task/task30/task3001/Solution.java | 28ea4555d63a65519526870b68eaa94af4e42be9 | [] | no_license | CosmicCis/JavaRushTasks | https://github.com/CosmicCis/JavaRushTasks | 6e70f44605ef4d540b940f509c949b41b0613a37 | 4c4a2e437df583908547b94a739211d367073ad1 | refs/heads/master | 2023-07-27T11:22:51.228000 | 2021-09-04T15:12:36 | 2021-09-04T15:12:36 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.javarush.task.task30.task3001;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
/*
Конвертер систем счислений
*/
public class Solution {
private static List<Character> list = new ArrayList<>();
static {
list.add('0');
list.add('1');
list.add('2');
list.add('3');
list.add('4');
list.add('5');
list.add('6');
list.add('7');
list.add('8');
list.add('9');
list.add('a');
list.add('b');
list.add('c');
list.add('d');
list.add('e');
list.add('f');
}
public static void main(String[] args) {
Number number = new Number(NumberSystemType._10, "6");
Number result = convertNumberToOtherNumberSystem(number, NumberSystemType._2);
System.out.println(result); //expected 110
number = new Number(NumberSystemType._16, "6df");
result = convertNumberToOtherNumberSystem(number, NumberSystemType._8);
System.out.println(result); //expected 3337
number = new Number(NumberSystemType._16, "abcdefabcdef");
result = convertNumberToOtherNumberSystem(number, NumberSystemType._16);
System.out.println(result); //expected abcdefabcdef
}
public static Number convertNumberToOtherNumberSystem(Number number, NumberSystem expectedNumberSystem) {
// if (!numberIsCorrect(number)) {
// throw new NumberFormatException("Переданное число некорректно");
// }
//
// BigInteger numberInDecimalSystem = convertNumberToDecimalSystem(number);
//
// String resultNumber = convertDecimalNumberToGivenNumberSystem(numberInDecimalSystem, expectedNumberSystem.getNumberSystemIntValue());
//
// return new Number(expectedNumberSystem, resultNumber);
BigInteger bi = new BigInteger(number.getDigit(), number.getNumberSystem().getNumberSystemIntValue());
String ans = bi.toString(expectedNumberSystem.getNumberSystemIntValue());
return new Number(expectedNumberSystem, ans);
}
private static boolean numberIsCorrect(Number number) {
for (int i = 0; i < number.getDigit().length(); i++) {
char tempChar = number.getDigit().charAt(i);
if (!list.contains(tempChar) || list.indexOf(tempChar) >= number.getNumberSystem().getNumberSystemIntValue()) {
return false;
}
}
return true;
}
private static BigInteger convertNumberToDecimalSystem(Number number) {
BigInteger result = BigInteger.ZERO;
int numberSystem = number.getNumberSystem().getNumberSystemIntValue();
int pow = number.getDigit().length() - 1;
for (int i = 0; i < number.getDigit().length(); i++, pow--) {
int tempNum = list.indexOf(number.getDigit().charAt(i));
result = result.add(BigInteger.valueOf((long) (tempNum * (Math.pow(numberSystem, pow)))));
}
return result;
}
private static String convertDecimalNumberToGivenNumberSystem(BigInteger numberInDecimalSystem, int numberSystemIntValue) {
StringBuilder stringBuilder = new StringBuilder();
while (true) {
BigInteger tempValue = numberInDecimalSystem.remainder(BigInteger.valueOf(numberSystemIntValue));
stringBuilder.append(list.get(tempValue.intValue()));
numberInDecimalSystem = numberInDecimalSystem.divide(BigInteger.valueOf(numberSystemIntValue));
if (numberInDecimalSystem.compareTo(BigInteger.valueOf(numberSystemIntValue)) <= 0 ) {
stringBuilder.append(list.get(numberInDecimalSystem.intValue()));
break;
}
}
return stringBuilder.reverse().toString();
}
}
| UTF-8 | Java | 3,847 | java | Solution.java | Java | [] | null | [] | package com.javarush.task.task30.task3001;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
/*
Конвертер систем счислений
*/
public class Solution {
private static List<Character> list = new ArrayList<>();
static {
list.add('0');
list.add('1');
list.add('2');
list.add('3');
list.add('4');
list.add('5');
list.add('6');
list.add('7');
list.add('8');
list.add('9');
list.add('a');
list.add('b');
list.add('c');
list.add('d');
list.add('e');
list.add('f');
}
public static void main(String[] args) {
Number number = new Number(NumberSystemType._10, "6");
Number result = convertNumberToOtherNumberSystem(number, NumberSystemType._2);
System.out.println(result); //expected 110
number = new Number(NumberSystemType._16, "6df");
result = convertNumberToOtherNumberSystem(number, NumberSystemType._8);
System.out.println(result); //expected 3337
number = new Number(NumberSystemType._16, "abcdefabcdef");
result = convertNumberToOtherNumberSystem(number, NumberSystemType._16);
System.out.println(result); //expected abcdefabcdef
}
public static Number convertNumberToOtherNumberSystem(Number number, NumberSystem expectedNumberSystem) {
// if (!numberIsCorrect(number)) {
// throw new NumberFormatException("Переданное число некорректно");
// }
//
// BigInteger numberInDecimalSystem = convertNumberToDecimalSystem(number);
//
// String resultNumber = convertDecimalNumberToGivenNumberSystem(numberInDecimalSystem, expectedNumberSystem.getNumberSystemIntValue());
//
// return new Number(expectedNumberSystem, resultNumber);
BigInteger bi = new BigInteger(number.getDigit(), number.getNumberSystem().getNumberSystemIntValue());
String ans = bi.toString(expectedNumberSystem.getNumberSystemIntValue());
return new Number(expectedNumberSystem, ans);
}
private static boolean numberIsCorrect(Number number) {
for (int i = 0; i < number.getDigit().length(); i++) {
char tempChar = number.getDigit().charAt(i);
if (!list.contains(tempChar) || list.indexOf(tempChar) >= number.getNumberSystem().getNumberSystemIntValue()) {
return false;
}
}
return true;
}
private static BigInteger convertNumberToDecimalSystem(Number number) {
BigInteger result = BigInteger.ZERO;
int numberSystem = number.getNumberSystem().getNumberSystemIntValue();
int pow = number.getDigit().length() - 1;
for (int i = 0; i < number.getDigit().length(); i++, pow--) {
int tempNum = list.indexOf(number.getDigit().charAt(i));
result = result.add(BigInteger.valueOf((long) (tempNum * (Math.pow(numberSystem, pow)))));
}
return result;
}
private static String convertDecimalNumberToGivenNumberSystem(BigInteger numberInDecimalSystem, int numberSystemIntValue) {
StringBuilder stringBuilder = new StringBuilder();
while (true) {
BigInteger tempValue = numberInDecimalSystem.remainder(BigInteger.valueOf(numberSystemIntValue));
stringBuilder.append(list.get(tempValue.intValue()));
numberInDecimalSystem = numberInDecimalSystem.divide(BigInteger.valueOf(numberSystemIntValue));
if (numberInDecimalSystem.compareTo(BigInteger.valueOf(numberSystemIntValue)) <= 0 ) {
stringBuilder.append(list.get(numberInDecimalSystem.intValue()));
break;
}
}
return stringBuilder.reverse().toString();
}
}
| 3,847 | 0.644193 | 0.633922 | 99 | 37.353535 | 35.478065 | 143 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.737374 | false | false | 3 |
73214b1baf2a91f3f13cee475ebba2b0bf1966c7 | 5,128,190,958,781 | a0b98e9fa95246ac2f92a1b15473e0f5b352e11e | /web-busnet/src/main/java/com/iliashenko/account/repository/BusRouteRepository.java | 841340908d785b5c52e2f0e14765bfd7fd027d4d | [] | no_license | iliashenkoa/bus_net | https://github.com/iliashenkoa/bus_net | 83d67fb168502182ef121b17c9514dde54350071 | 822376b33368950cd04ab65e44c8bd52c15aaaf2 | refs/heads/master | 2020-04-28T23:31:00.709000 | 2019-04-21T14:33:01 | 2019-04-21T14:33:01 | 175,657,628 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.iliashenko.account.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.iliashenko.account.model.BusRoute;
public interface BusRouteRepository extends JpaRepository<BusRoute, Integer> {
}
| UTF-8 | Java | 236 | java | BusRouteRepository.java | Java | [] | null | [] | package com.iliashenko.account.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.iliashenko.account.model.BusRoute;
public interface BusRouteRepository extends JpaRepository<BusRoute, Integer> {
}
| 236 | 0.838983 | 0.838983 | 9 | 25.222221 | 29.570171 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false | 3 |
6619b563a0c2ce3aa9e8d35f2e9439252e61c4f7 | 12,799,002,547,178 | fc12b808efb05f2c9c2063132e77a3fc072cad3a | /src/main/java/ru/sberbank/autotests/pages/InsurancePage.java | 78c3111b72d76e99e8d39c89f717a33a52426304 | [] | no_license | jhupanen95/Aplana-DZ9 | https://github.com/jhupanen95/Aplana-DZ9 | 428206a0bf47783dcc88926d2ec045dcd8390959 | c51e61a026a4429700ba31ddc9446384a6f47e97 | refs/heads/master | 2021-07-21T03:45:46.835000 | 2019-11-25T13:14:33 | 2019-11-25T13:14:33 | 222,784,579 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ru.sberbank.autotests.pages;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.ExpectedConditions;
import ru.sberbank.autotests.utils.DriverManager;
public class InsurancePage extends BasePageObject{
@FindBy(xpath = "(//a[@class='kit-button kit-button_default kit-button_type_big'])[1]")
public WebElement buttonToStatement;
public void clickToButton () {
wait.until(ExpectedConditions.visibilityOf(buttonToStatement));
String href = buttonToStatement.getAttribute("href");
DriverManager.getDriver().navigate().to(href);
}
}
| UTF-8 | Java | 648 | java | InsurancePage.java | Java | [] | null | [] | package ru.sberbank.autotests.pages;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.ExpectedConditions;
import ru.sberbank.autotests.utils.DriverManager;
public class InsurancePage extends BasePageObject{
@FindBy(xpath = "(//a[@class='kit-button kit-button_default kit-button_type_big'])[1]")
public WebElement buttonToStatement;
public void clickToButton () {
wait.until(ExpectedConditions.visibilityOf(buttonToStatement));
String href = buttonToStatement.getAttribute("href");
DriverManager.getDriver().navigate().to(href);
}
}
| 648 | 0.753086 | 0.751543 | 18 | 35 | 27.414515 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 3 |
91cca812c393b216c0dff31b6dc3b092ef59b9eb | 1,125,281,500,118 | 09fa5476aa13e570adfa33d532fb739395a41c0c | /src/adicse/sigweb/servicio/impl/MaterialredServicioImpl.java | 37ac6c5ed0e75b917d12f8a00d4ec4e562bebb1a | [] | no_license | crojasadicse/sigweb | https://github.com/crojasadicse/sigweb | b3dc9f1001c0d4bbff2b69f4ec7d8fc9a43f2c22 | ff682ee120e11a3bdbabaad5b4bc25633045eb14 | refs/heads/master | 2020-07-09T20:05:51.610000 | 2017-06-13T22:37:04 | 2017-06-13T22:37:04 | 94,261,692 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package adicse.sigweb.servicio.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import adicse.base.util.Pagination;
import adicse.sigweb.model.Materialred;
import adicse.sigweb.repositorio.IMaterialredDao;
import adicse.sigweb.servicio.IMaterialredServicio;
@Service
@Transactional
public class MaterialredServicioImpl implements IMaterialredServicio {
@Autowired
private IMaterialredDao iMaterialredDao;
@Override
public void saveorupdate(Materialred materialred) {
// TODO Auto-generated method stub
iMaterialredDao.saveorupdate(materialred);
}
@Override
public void delete(Materialred materialred) {
// TODO Auto-generated method stub
iMaterialredDao.delete(materialred);
}
@Override
public Materialred getMaterialred(Materialred materialred) {
// TODO Auto-generated method stub
return null;
}
@Override
public Materialred getMaterialredById(Integer id) {
// TODO Auto-generated method stub
return iMaterialredDao.getMaterialredById(id);
}
@Override
public List<Materialred> getMaterialreds() {
// TODO Auto-generated method stub
return iMaterialredDao.getMaterialreds();
}
@Override
public List<Materialred> getMaterialredPaginado(Pagination pagination) {
// TODO Auto-generated method stub
return iMaterialredDao.getMaterialredPaginado(pagination);
}
}
| UTF-8 | Java | 1,476 | java | MaterialredServicioImpl.java | Java | [] | null | [] | package adicse.sigweb.servicio.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import adicse.base.util.Pagination;
import adicse.sigweb.model.Materialred;
import adicse.sigweb.repositorio.IMaterialredDao;
import adicse.sigweb.servicio.IMaterialredServicio;
@Service
@Transactional
public class MaterialredServicioImpl implements IMaterialredServicio {
@Autowired
private IMaterialredDao iMaterialredDao;
@Override
public void saveorupdate(Materialred materialred) {
// TODO Auto-generated method stub
iMaterialredDao.saveorupdate(materialred);
}
@Override
public void delete(Materialred materialred) {
// TODO Auto-generated method stub
iMaterialredDao.delete(materialred);
}
@Override
public Materialred getMaterialred(Materialred materialred) {
// TODO Auto-generated method stub
return null;
}
@Override
public Materialred getMaterialredById(Integer id) {
// TODO Auto-generated method stub
return iMaterialredDao.getMaterialredById(id);
}
@Override
public List<Materialred> getMaterialreds() {
// TODO Auto-generated method stub
return iMaterialredDao.getMaterialreds();
}
@Override
public List<Materialred> getMaterialredPaginado(Pagination pagination) {
// TODO Auto-generated method stub
return iMaterialredDao.getMaterialredPaginado(pagination);
}
}
| 1,476 | 0.802846 | 0.802846 | 62 | 22.806452 | 22.940203 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.983871 | false | false | 3 |
8a1a75da5680586058c17500306e1fb6d3d86ae6 | 14,628,658,621,200 | 6adf38c29933367e7e0de98739b215ea301645a7 | /src/LocalSearch/Statement.java | 8ffd9a0597ecde847259580de3f9303671d99507 | [] | no_license | GonMolon/AI_LocalSearch | https://github.com/GonMolon/AI_LocalSearch | a348c315373c1cec32ca0607df506301d0e5d3ea | 64c65fe981513ef258210410b8e41a880d525753 | refs/heads/master | 2021-04-30T22:21:27.880000 | 2016-11-09T18:38:09 | 2016-11-09T18:38:09 | 70,160,006 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package LocalSearch;
import IA.Azamon.Oferta;
import IA.Azamon.Paquete;
import IA.Azamon.Paquetes;
import IA.Azamon.Transporte;
import javax.jws.soap.SOAPBinding;
import java.util.Comparator;
public class Statement {
private static Statement statement;
private Paquetes packages;
private Transporte transport;
protected int[][] offers;
private double totalWeight = 0;
private double totalOfferedWeight = 0;
public static void generateStatement(int n, double prop, int seed, SortMode sortMode) {
statement = new Statement(n, prop, seed, sortMode);
}
private Statement(int n, double prop, int seed, SortMode sortMode) {
packages = new Paquetes(n, seed);
packages.sort(new Comparator<Paquete>() {
@Override
public int compare(Paquete a, Paquete b) {
if(a.getPrioridad() < b.getPrioridad()) {
return -1;
} else if(a.getPrioridad() > b.getPrioridad()) {
return 1;
} else {
return 0;
}
}
});
transport = new Transporte(packages, prop, seed);
transport.sort(new Comparator<Oferta>() {
@Override
public int compare(Oferta a, Oferta b) {
if(a.getDias() < b.getDias()) {
return -1;
} else if(a.getDias() > b.getDias()) {
return 1;
} else {
if(sortMode != SortMode.RANDOM) {
if(a.getPrecio() < b.getPrecio()) {
return sortMode == SortMode.OPTIMUM ? -1 : 1;
} else if(a.getPrecio() > b.getPrecio()) {
return sortMode == SortMode.OPTIMUM ? 1 : -1;
} else {
return 0;
}
} else {
return 0;
}
}
}
});
for(Paquete paquete : packages) {
totalWeight += paquete.getPeso();
}
offers = new int[5][];
for(int i = 0; i < 5; ++i) {
offers[i] = new int[0];
}
int t = 0;
int T = 0;
for(int i = 0; i < transport.size(); ++i) {
++t;
++T;
Oferta offer = transport.get(i);
totalOfferedWeight += offer.getPesomax();
if(i == transport.size()-1 || offer.getDias() != transport.get(i+1).getDias()) {
offers[offer.getDias()-1] = new int[t];
int k = 0;
for(int j = T-t; j < T; ++j) {
offers[offer.getDias()-1][k] = j;
++k;
}
t = 0;
}
}
}
public static Statement getStatement() {
return statement;
}
public int totalPackages() {
return packages.size();
}
public int totalOffers() {
return transport.size();
}
public int totalOffersFromDays(int days) {
return offers[days-1].length;
}
public Oferta getOffer(int ID) {
return transport.get(ID);
}
public Paquete getPackage(int ID) {
return packages.get(ID);
}
private void print() {
print2();
}
private void print1() {
System.out.println("PACKAGES");
int id = 0;
int total_weight = 0;
for(Paquete paquete : packages) {
System.out.println("Package ID: " + id++);
System.out.println(" " + "Priority: " + paquete.getPrioridad());
System.out.println(" " + "Weight: " + paquete.getPeso());
total_weight += paquete.getPeso();
}
System.out.println("Total weight: " + total_weight + "kg");
System.out.println("OFFERS");
for(int days = 0; days < 5; ++days) {
System.out.println(days+1 + " days: ");
for(int offerID : offers[days]) {
Oferta oferta = getOffer(offerID);
System.out.println(" " + "Offer ID: " + offerID);
System.out.println(" " + "Price (kg): " + oferta.getPrecio());
System.out.println(" " + "Max weight : " + oferta.getPesomax());
}
}
/*
System.out.println("TOTAL WEIGHT = " + totalWeight);
System.out.println("TOTAL OFFERED WEIGHT = " + totalOfferedWeight);
System.out.println("REAL PROPORTION = " + totalOfferedWeight/totalWeight);
*/
}
private void print2() {
System.out.println("--------STATEMENT---------");
int id = 0;
float total_weight = 0;
System.out.print("Package ID:\t");
for(Paquete paquete : packages) {
System.out.format("%5d",id++);
total_weight += paquete.getPeso();
}
System.out.println();
System.out.print("Priority:\t");
for(Paquete paquete : packages) {
System.out.format("%5d",paquete.getPrioridad());
}
System.out.println();
System.out.print("Weight:\t\t");
for(Paquete paquete : packages) {
System.out.format("%5.1f",paquete.getPeso());
}
System.out.println();
System.out.println(total_weight + " total weight");
System.out.println();
id = 0;
System.out.print("Offer ID:\t");
for (Oferta offer : transport) {
System.out.format("%5d",id++);
}
System.out.println();
System.out.print("Days:\t\t");
for (Oferta offer : transport) {
System.out.format("%5d",offer.getDias());
}
System.out.println();
System.out.print("Price(kg):\t");
for (Oferta offer : transport) {
System.out.format("%5.2f",offer.getPrecio());
}
System.out.println();
System.out.print("Max weight:\t");
for (Oferta offer : transport) {
System.out.format("%5.1f",offer.getPesomax());
}
System.out.println();
System.out.println("--------/STATEMENT--------");
}
}
| UTF-8 | Java | 6,207 | java | Statement.java | Java | [] | null | [] | package LocalSearch;
import IA.Azamon.Oferta;
import IA.Azamon.Paquete;
import IA.Azamon.Paquetes;
import IA.Azamon.Transporte;
import javax.jws.soap.SOAPBinding;
import java.util.Comparator;
public class Statement {
private static Statement statement;
private Paquetes packages;
private Transporte transport;
protected int[][] offers;
private double totalWeight = 0;
private double totalOfferedWeight = 0;
public static void generateStatement(int n, double prop, int seed, SortMode sortMode) {
statement = new Statement(n, prop, seed, sortMode);
}
private Statement(int n, double prop, int seed, SortMode sortMode) {
packages = new Paquetes(n, seed);
packages.sort(new Comparator<Paquete>() {
@Override
public int compare(Paquete a, Paquete b) {
if(a.getPrioridad() < b.getPrioridad()) {
return -1;
} else if(a.getPrioridad() > b.getPrioridad()) {
return 1;
} else {
return 0;
}
}
});
transport = new Transporte(packages, prop, seed);
transport.sort(new Comparator<Oferta>() {
@Override
public int compare(Oferta a, Oferta b) {
if(a.getDias() < b.getDias()) {
return -1;
} else if(a.getDias() > b.getDias()) {
return 1;
} else {
if(sortMode != SortMode.RANDOM) {
if(a.getPrecio() < b.getPrecio()) {
return sortMode == SortMode.OPTIMUM ? -1 : 1;
} else if(a.getPrecio() > b.getPrecio()) {
return sortMode == SortMode.OPTIMUM ? 1 : -1;
} else {
return 0;
}
} else {
return 0;
}
}
}
});
for(Paquete paquete : packages) {
totalWeight += paquete.getPeso();
}
offers = new int[5][];
for(int i = 0; i < 5; ++i) {
offers[i] = new int[0];
}
int t = 0;
int T = 0;
for(int i = 0; i < transport.size(); ++i) {
++t;
++T;
Oferta offer = transport.get(i);
totalOfferedWeight += offer.getPesomax();
if(i == transport.size()-1 || offer.getDias() != transport.get(i+1).getDias()) {
offers[offer.getDias()-1] = new int[t];
int k = 0;
for(int j = T-t; j < T; ++j) {
offers[offer.getDias()-1][k] = j;
++k;
}
t = 0;
}
}
}
public static Statement getStatement() {
return statement;
}
public int totalPackages() {
return packages.size();
}
public int totalOffers() {
return transport.size();
}
public int totalOffersFromDays(int days) {
return offers[days-1].length;
}
public Oferta getOffer(int ID) {
return transport.get(ID);
}
public Paquete getPackage(int ID) {
return packages.get(ID);
}
private void print() {
print2();
}
private void print1() {
System.out.println("PACKAGES");
int id = 0;
int total_weight = 0;
for(Paquete paquete : packages) {
System.out.println("Package ID: " + id++);
System.out.println(" " + "Priority: " + paquete.getPrioridad());
System.out.println(" " + "Weight: " + paquete.getPeso());
total_weight += paquete.getPeso();
}
System.out.println("Total weight: " + total_weight + "kg");
System.out.println("OFFERS");
for(int days = 0; days < 5; ++days) {
System.out.println(days+1 + " days: ");
for(int offerID : offers[days]) {
Oferta oferta = getOffer(offerID);
System.out.println(" " + "Offer ID: " + offerID);
System.out.println(" " + "Price (kg): " + oferta.getPrecio());
System.out.println(" " + "Max weight : " + oferta.getPesomax());
}
}
/*
System.out.println("TOTAL WEIGHT = " + totalWeight);
System.out.println("TOTAL OFFERED WEIGHT = " + totalOfferedWeight);
System.out.println("REAL PROPORTION = " + totalOfferedWeight/totalWeight);
*/
}
private void print2() {
System.out.println("--------STATEMENT---------");
int id = 0;
float total_weight = 0;
System.out.print("Package ID:\t");
for(Paquete paquete : packages) {
System.out.format("%5d",id++);
total_weight += paquete.getPeso();
}
System.out.println();
System.out.print("Priority:\t");
for(Paquete paquete : packages) {
System.out.format("%5d",paquete.getPrioridad());
}
System.out.println();
System.out.print("Weight:\t\t");
for(Paquete paquete : packages) {
System.out.format("%5.1f",paquete.getPeso());
}
System.out.println();
System.out.println(total_weight + " total weight");
System.out.println();
id = 0;
System.out.print("Offer ID:\t");
for (Oferta offer : transport) {
System.out.format("%5d",id++);
}
System.out.println();
System.out.print("Days:\t\t");
for (Oferta offer : transport) {
System.out.format("%5d",offer.getDias());
}
System.out.println();
System.out.print("Price(kg):\t");
for (Oferta offer : transport) {
System.out.format("%5.2f",offer.getPrecio());
}
System.out.println();
System.out.print("Max weight:\t");
for (Oferta offer : transport) {
System.out.format("%5.1f",offer.getPesomax());
}
System.out.println();
System.out.println("--------/STATEMENT--------");
}
}
| 6,207 | 0.488803 | 0.48107 | 191 | 31.497383 | 21.489527 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.65445 | false | false | 3 |
dec9ab245a0e194ebb17c3c06d5d1a0d6585ca68 | 14,628,658,622,870 | 0a6c07bb80c2ceee241a82597ea14c985b042038 | /huashu/src/main/java/com/tuodanhuashu/app/receiver/PushMessageBean.java | 1792ca7a33424400f1b3baa57dd7d08b0486ad13 | [] | no_license | syg-todo/P01TalkSkillAPP_Android | https://github.com/syg-todo/P01TalkSkillAPP_Android | 9a1458d351b33fe686a92df2c88bc30612d132b7 | def83426e9efeb7b06d38181130388a936b17dcc | refs/heads/master | 2022-01-12T22:57:19.314000 | 2019-06-27T01:04:10 | 2019-06-27T01:04:10 | 190,511,728 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tuodanhuashu.app.receiver;
public class PushMessageBean {
private String articleId = "";
private String keywords = "";
private int type = 0;
private String courseId = "";
public String getCourseId() {
return courseId;
}
public void setCourseId(String courseId) {
this.courseId = courseId;
}
public PushMessageBean() {
}
public String getArticleId() {
return articleId;
}
public void setArticleId(String articleId) {
this.articleId = articleId;
}
public String getKeywords() {
return keywords;
}
public void setKeywords(String keywords) {
this.keywords = keywords;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
}
| UTF-8 | Java | 836 | java | PushMessageBean.java | Java | [] | null | [] | package com.tuodanhuashu.app.receiver;
public class PushMessageBean {
private String articleId = "";
private String keywords = "";
private int type = 0;
private String courseId = "";
public String getCourseId() {
return courseId;
}
public void setCourseId(String courseId) {
this.courseId = courseId;
}
public PushMessageBean() {
}
public String getArticleId() {
return articleId;
}
public void setArticleId(String articleId) {
this.articleId = articleId;
}
public String getKeywords() {
return keywords;
}
public void setKeywords(String keywords) {
this.keywords = keywords;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
}
| 836 | 0.601675 | 0.600478 | 47 | 16.787233 | 16.084797 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.276596 | false | false | 3 |
db07939570b146affd2339f2489efe085b361f3a | 26,731,876,451,939 | 3f1f91ac1a6c43f7be9f2f6002c7831060f077b3 | /Hanhan_ERP/src/main/java/com/hanhan/service/device/DeviceTypeServiceImpl.java | 9436d094c91bbede73293dae6e56bb8ec2ca8a9c | [
"Apache-2.0"
] | permissive | vrigl/Hanhan_ERP | https://github.com/vrigl/Hanhan_ERP | 3ea7b7a09c245ecc5d5398cc90e62968c51032f8 | 2126ecf89d83d740142fb7a317230e7060253060 | refs/heads/master | 2020-07-03T03:09:05.795000 | 2019-08-11T15:42:58 | 2019-08-11T15:42:58 | 201,765,486 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hanhan.service.device;
import com.hanhan.bean.DeviceType;
import com.hanhan.bean.DeviceTypeExample;
import com.hanhan.mapper.DeviceMapper;
import com.hanhan.mapper.DeviceTypeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class DeviceTypeServiceImpl implements DeviceTypeService {
@Autowired
DeviceTypeMapper deviceTypeMapper;
@Override
public List<DeviceType> getData() {
DeviceTypeExample typeExample = new DeviceTypeExample();
return deviceTypeMapper.selectByExample(typeExample);
}
}
| UTF-8 | Java | 649 | java | DeviceTypeServiceImpl.java | Java | [] | null | [] | package com.hanhan.service.device;
import com.hanhan.bean.DeviceType;
import com.hanhan.bean.DeviceTypeExample;
import com.hanhan.mapper.DeviceMapper;
import com.hanhan.mapper.DeviceTypeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class DeviceTypeServiceImpl implements DeviceTypeService {
@Autowired
DeviceTypeMapper deviceTypeMapper;
@Override
public List<DeviceType> getData() {
DeviceTypeExample typeExample = new DeviceTypeExample();
return deviceTypeMapper.selectByExample(typeExample);
}
}
| 649 | 0.795069 | 0.795069 | 22 | 28.5 | 22.600784 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 3 |
2f9e62840398654b36be8526827e6e27c8c2c6d3 | 26,723,286,582,667 | f380b14a0a37c2d2ecf11438cbb470021198eecb | /user_interface/src/main/java/cn/denua/user_interface/MultiTypeAdapter.java | 7e5c1c006463401dd6a5a812849012b1e9f96a4c | [] | no_license | dengzii/AndroidTest | https://github.com/dengzii/AndroidTest | 89945b023b421ef593323011ef7b8fc1356622ac | f608dfa2646dcf70ac089f17bff9a17b7e2a784d | refs/heads/master | 2020-03-19T04:05:43.184000 | 2019-07-14T14:46:18 | 2019-07-14T14:46:18 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.denua.user_interface;
import android.content.Context;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.ArrayMap;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;
public class MultiTypeAdapter extends RecyclerView.Adapter<MultiTypeAdapter.AbsViewHolder> {
private List<Object> mItems;
private Context mContext;
private SparseArray<Class<? extends AbsViewHolder>> mItemType;
private Map<Integer, Integer> mItemLayoutRes;
private Map<Integer, IViewHolderGenerator> mHolderGenerators;
public MultiTypeAdapter(List<Object> data, Context context) {
mItems = data;
mContext = context;
mItemType = new SparseArray<>();
mHolderGenerators = new ArrayMap<>();
mItemLayoutRes = new ArrayMap<>();
}
public void register(Class<?> type, Class<? extends AbsViewHolder> holder){
mItemType.put(type.hashCode(), holder);
}
public void register(Class<?> type, Class<? extends AbsViewHolder> holder, @LayoutRes int res){
register(type, holder);
mItemLayoutRes.put(type.hashCode(), res);
}
public void addViewHolderGenerator(Class<?> type, IViewHolderGenerator generator){
mHolderGenerators.put(type.hashCode(), generator);
}
@NonNull
@Override
public AbsViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
if (mHolderGenerators.containsKey(i)){
return mHolderGenerators.get(i).onCreateViewHolder(viewGroup, i);
}
return getHolder(mItemType.get(i), viewGroup, i);
}
@Override
public void onBindViewHolder(@NonNull AbsViewHolder absViewHolder, int position) {
absViewHolder.bindData(mItems.get(position));
}
@Override
public int getItemViewType(int position) {
return mItems.get(position).getClass().hashCode();
}
@Override
public int getItemCount() {
return mItems.size();
}
private AbsViewHolder getHolder(Class<? extends AbsViewHolder> clazz,
ViewGroup parent, int type){
try {
for (Constructor c:clazz.getDeclaredConstructors()) {
c.setAccessible(true);
int parameterCount = c.getParameterTypes().length;
if (parameterCount == 3 && c.getParameterTypes()[1] == ViewGroup.class
&& c.getParameterTypes()[2] == int.class){
return (AbsViewHolder) c.newInstance(
null, parent, getLayoutResForType(type));
}else if (parameterCount == 2 ){
if (c.getParameterTypes()[1] == ViewGroup.class
|| c.getParameterTypes()[1] == View.class){
return (AbsViewHolder) c.newInstance(null, parent);
}if (c.getParameterTypes()[0] == ViewGroup.class
&& c.getParameterTypes()[1] == int.class){
return (AbsViewHolder) c.newInstance(parent, getLayoutResForType(type));
}
}
}
throw new RuntimeException("No suitable constructor find with " + clazz.getName());
} catch (IllegalAccessException|InvocationTargetException|InstantiationException e) {
e.printStackTrace();
throw new RuntimeException(e);
} catch (NullPointerException e){
throw new RuntimeException("No layout res find with type " + clazz.getName());
}
}
private int getLayoutResForType(int type){
if (mItemLayoutRes.get(type) == null) {
throw new RuntimeException("No layout res specified for type " + type
+ ", Or you can override the constructor whose argument is ViewGroup.");
}
return mItemLayoutRes.get(type);
}
public interface IViewHolderGenerator{
@NonNull AbsViewHolder onCreateViewHolder(ViewGroup parent, int type);
}
public static abstract class AbsViewHolder extends RecyclerView.ViewHolder{
public AbsViewHolder(@NonNull ViewGroup parent, int layoutRes){
this(LayoutInflater.from(parent.getContext()).inflate(layoutRes, parent,false));
}
public AbsViewHolder(@NonNull View itemView) {
super(itemView);
bindView();
}
public abstract void bindData(Object data);
public void bindView(){
}
}
}
| UTF-8 | Java | 4,767 | java | MultiTypeAdapter.java | Java | [] | null | [] | package cn.denua.user_interface;
import android.content.Context;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.ArrayMap;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;
public class MultiTypeAdapter extends RecyclerView.Adapter<MultiTypeAdapter.AbsViewHolder> {
private List<Object> mItems;
private Context mContext;
private SparseArray<Class<? extends AbsViewHolder>> mItemType;
private Map<Integer, Integer> mItemLayoutRes;
private Map<Integer, IViewHolderGenerator> mHolderGenerators;
public MultiTypeAdapter(List<Object> data, Context context) {
mItems = data;
mContext = context;
mItemType = new SparseArray<>();
mHolderGenerators = new ArrayMap<>();
mItemLayoutRes = new ArrayMap<>();
}
public void register(Class<?> type, Class<? extends AbsViewHolder> holder){
mItemType.put(type.hashCode(), holder);
}
public void register(Class<?> type, Class<? extends AbsViewHolder> holder, @LayoutRes int res){
register(type, holder);
mItemLayoutRes.put(type.hashCode(), res);
}
public void addViewHolderGenerator(Class<?> type, IViewHolderGenerator generator){
mHolderGenerators.put(type.hashCode(), generator);
}
@NonNull
@Override
public AbsViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
if (mHolderGenerators.containsKey(i)){
return mHolderGenerators.get(i).onCreateViewHolder(viewGroup, i);
}
return getHolder(mItemType.get(i), viewGroup, i);
}
@Override
public void onBindViewHolder(@NonNull AbsViewHolder absViewHolder, int position) {
absViewHolder.bindData(mItems.get(position));
}
@Override
public int getItemViewType(int position) {
return mItems.get(position).getClass().hashCode();
}
@Override
public int getItemCount() {
return mItems.size();
}
private AbsViewHolder getHolder(Class<? extends AbsViewHolder> clazz,
ViewGroup parent, int type){
try {
for (Constructor c:clazz.getDeclaredConstructors()) {
c.setAccessible(true);
int parameterCount = c.getParameterTypes().length;
if (parameterCount == 3 && c.getParameterTypes()[1] == ViewGroup.class
&& c.getParameterTypes()[2] == int.class){
return (AbsViewHolder) c.newInstance(
null, parent, getLayoutResForType(type));
}else if (parameterCount == 2 ){
if (c.getParameterTypes()[1] == ViewGroup.class
|| c.getParameterTypes()[1] == View.class){
return (AbsViewHolder) c.newInstance(null, parent);
}if (c.getParameterTypes()[0] == ViewGroup.class
&& c.getParameterTypes()[1] == int.class){
return (AbsViewHolder) c.newInstance(parent, getLayoutResForType(type));
}
}
}
throw new RuntimeException("No suitable constructor find with " + clazz.getName());
} catch (IllegalAccessException|InvocationTargetException|InstantiationException e) {
e.printStackTrace();
throw new RuntimeException(e);
} catch (NullPointerException e){
throw new RuntimeException("No layout res find with type " + clazz.getName());
}
}
private int getLayoutResForType(int type){
if (mItemLayoutRes.get(type) == null) {
throw new RuntimeException("No layout res specified for type " + type
+ ", Or you can override the constructor whose argument is ViewGroup.");
}
return mItemLayoutRes.get(type);
}
public interface IViewHolderGenerator{
@NonNull AbsViewHolder onCreateViewHolder(ViewGroup parent, int type);
}
public static abstract class AbsViewHolder extends RecyclerView.ViewHolder{
public AbsViewHolder(@NonNull ViewGroup parent, int layoutRes){
this(LayoutInflater.from(parent.getContext()).inflate(layoutRes, parent,false));
}
public AbsViewHolder(@NonNull View itemView) {
super(itemView);
bindView();
}
public abstract void bindData(Object data);
public void bindView(){
}
}
}
| 4,767 | 0.637298 | 0.63541 | 131 | 35.389313 | 30.027105 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.610687 | false | false | 3 |
e0d564b5bec4c5e56e5d742f18e01cfc83481455 | 6,914,897,353,997 | 5297e664a22201b7b136358fc3046e5558881d99 | /DomainModelDesigner/src/main/java/com/diguits/domainmodeldesigner/domainmodel/views/DomainModelTreeView.java | d928b279d1eb49fb7beaed3bbc23420c91b7c022 | [
"Apache-2.0"
] | permissive | diguits/domainmodeldesigner | https://github.com/diguits/domainmodeldesigner | 804b2210f3b4f2fa6932a09d2299e7998ee8a116 | 212ea0ce34f69e1eb08be7dcb52f45fe65ec82db | refs/heads/master | 2021-08-26T08:32:56.588000 | 2017-11-15T15:16:59 | 2017-11-15T15:16:59 | 110,843,509 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.diguits.domainmodeldesigner.domainmodel.views;
import com.diguits.domainmodeldesigner.domainmodel.models.BaseDefModel;
import com.diguits.javafx.container.views.TreeContainerView;
import javafx.scene.control.TreeItem;
public class DomainModelTreeView extends TreeContainerView<BaseDefModel>{
@Override
public void collapse() {
TreeItem<BaseDefModel> root = treeView.getRoot();
if(root!=null){
for (TreeItem<BaseDefModel> item : root.getChildren()) {
for (TreeItem<BaseDefModel> subitem : item.getChildren()) {
subitem.setExpanded(false);
}
}
}
}
}
| UTF-8 | Java | 592 | java | DomainModelTreeView.java | Java | [] | null | [] | package com.diguits.domainmodeldesigner.domainmodel.views;
import com.diguits.domainmodeldesigner.domainmodel.models.BaseDefModel;
import com.diguits.javafx.container.views.TreeContainerView;
import javafx.scene.control.TreeItem;
public class DomainModelTreeView extends TreeContainerView<BaseDefModel>{
@Override
public void collapse() {
TreeItem<BaseDefModel> root = treeView.getRoot();
if(root!=null){
for (TreeItem<BaseDefModel> item : root.getChildren()) {
for (TreeItem<BaseDefModel> subitem : item.getChildren()) {
subitem.setExpanded(false);
}
}
}
}
}
| 592 | 0.763514 | 0.763514 | 21 | 27.190475 | 27.01079 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.619048 | false | false | 3 |
517e5a18e66fba052f6fda882317aeb56ca5d99d | 8,847,632,645,578 | fa0efa5993e3a5f6947e46ffcd6a40f07f6bda42 | /Primero Pasos/Courrier/src/Tabla2.java | 656b0138fcf8b1b2d0be53425711b10c817289de | [] | no_license | SandyMorel/Java-Basico | https://github.com/SandyMorel/Java-Basico | 113f7fe680d8e4d7ad2d57c22bc8fedbb486411a | 6a69e13d728188ab2f52c0c9e31793b6a23cf13e | refs/heads/master | 2021-05-14T18:34:59.395000 | 2018-02-28T20:56:53 | 2018-02-28T20:56:53 | 116,079,010 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class Tabla2 {
public void pasarvalores_paquetes(JTable to) {
String[] Columnas = {"Nombres", "Apellido", "Cedula", "Telefono", "Direccion", "Codigo", "Cantidad", "Tipo", "Peso", "Destino", "Estatus"};
DefaultTableModel dtm2 = new DefaultTableModel(null, Columnas);
to.setModel(dtm2);
}
}
| UTF-8 | Java | 403 | java | Tabla2.java | Java | [
{
"context": "uetes(JTable to) {\n\n String[] Columnas = {\"Nombres\", \"Apellido\", \"Cedula\", \"Telefono\", \"Direccion\", ",
"end": 185,
"score": 0.9807445406913757,
"start": 178,
"tag": "NAME",
"value": "Nombres"
},
{
"context": "e to) {\n\n String[] Columnas = {\"... | null | [] |
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class Tabla2 {
public void pasarvalores_paquetes(JTable to) {
String[] Columnas = {"Nombres", "Apellido", "Cedula", "Telefono", "Direccion", "Codigo", "Cantidad", "Tipo", "Peso", "Destino", "Estatus"};
DefaultTableModel dtm2 = new DefaultTableModel(null, Columnas);
to.setModel(dtm2);
}
}
| 403 | 0.669975 | 0.662531 | 12 | 32.5 | 40.970516 | 147 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.333333 | false | false | 3 |
ff91e093418a91d2e43c05f92de37c94d75372bc | 30,202,210,035,216 | dcb0a3399c0122870277cf13bab5959b9055f69b | /Back to Physics/src/items/PowerUp.java | c0b24c50e54a033a6ffec55ebdca1bee1f0730b9 | [] | no_license | kennyeni/back-to-physics | https://github.com/kennyeni/back-to-physics | 08bcf5eb69fa426f4b8b80aceaf405ef7f8cdf52 | 33f1a90217d90e962f17770500429551efd5366c | refs/heads/master | 2016-09-03T07:27:10.616000 | 2011-12-08T17:47:50 | 2011-12-08T17:47:50 | 32,117,120 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package items;
public class PowerUp {
}
| UTF-8 | Java | 42 | java | PowerUp.java | Java | [] | null | [] | package items;
public class PowerUp {
}
| 42 | 0.714286 | 0.714286 | 5 | 7.4 | 9.024411 | 22 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false | 3 |
0f83d7ed2d8dc986e2bd62fb87c76e02de892699 | 24,129,126,272,736 | 7d616b234fac011ec26024ba53e9cbcbc84ff1ea | /shopcart-core/src/test/java/com/devworkz/shopcart/service/impl/CustomUserDetailsServiceTest.java | 38a2c76e778f5c840de311d44cdbd463f1462585 | [] | no_license | bobsantos/shop-cart | https://github.com/bobsantos/shop-cart | 87eb1495ff230defa0c157591bc37e684a41f561 | 23d9f6999d686ac9a5e75d39db1beee28a2bd2c8 | refs/heads/master | 2021-01-01T17:32:07.453000 | 2012-10-05T12:11:55 | 2012-10-05T12:11:55 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.devworkz.shopcart.service.impl;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import com.devworkz.shopcart.domain.User;
import com.devworkz.shopcart.domain.UserRole;
import com.devworkz.shopcart.domain.UserRole.UserRoleType;
import com.devworkz.shopcart.repository.UserRepository;
public class CustomUserDetailsServiceTest {
private static final String TEST_PASSWORD = "test";
private static final Long TEST_ID = 1L;
private static final String TEST_EMAIL = "test";
private CustomUserDetailsService service;
@Mock
private UserRepository userRepository;
@Before
public void init(){
MockitoAnnotations.initMocks(this);
service = new CustomUserDetailsService();
service.setUserRepository(userRepository);
}
@Test
public void shouldReturnUserDetailsOfExistingUser(){
// given
User user= createUser();
when(userRepository.findByEmail(TEST_EMAIL)).thenReturn(user);
// when
UserDetails actual = service.loadUserByUsername(TEST_EMAIL);
// then
assertNotNull(actual);
assertEquals(user.getEmail(), actual.getUsername());
assertEquals(user.getPassword(), actual.getPassword());
assertNotNull(actual.getAuthorities());
assertEquals(user.getRoles().size(), actual.getAuthorities().size());
}
@Test(expected=UsernameNotFoundException.class)
public void shouldNotReturnUserDetailsForNonExistingUser(){
// given
when(userRepository.findByEmail(TEST_EMAIL)).thenReturn(null);
// when
service.loadUserByUsername(TEST_EMAIL);
}
private User createUser() {
User user = new User();
user.setEmail(TEST_EMAIL);
user.setId(TEST_ID);
user.setPassword(TEST_PASSWORD);
Set<UserRole> roles = new HashSet<UserRole>();
UserRole role = createRole(user);
role.setRole(UserRoleType.ROLE_ADMIN);
roles.add(role);
user.setRoles(roles);
return user;
}
private UserRole createRole(User user) {
UserRole role = new UserRole();
role.setId(TEST_ID);
role.setUser(user);
return role;
}
}
| UTF-8 | Java | 2,471 | java | CustomUserDetailsServiceTest.java | Java | [
{
"context": "t {\n\tprivate static final String TEST_PASSWORD = \"test\";\n\tprivate static final Long TEST_ID = 1L;\n\tpriva",
"end": 878,
"score": 0.9995266199111938,
"start": 874,
"tag": "PASSWORD",
"value": "test"
},
{
"context": "EMAIL);\n\t\tuser.setId(TEST_ID);\n\t\tuser.setP... | null | [] | package com.devworkz.shopcart.service.impl;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import com.devworkz.shopcart.domain.User;
import com.devworkz.shopcart.domain.UserRole;
import com.devworkz.shopcart.domain.UserRole.UserRoleType;
import com.devworkz.shopcart.repository.UserRepository;
public class CustomUserDetailsServiceTest {
private static final String TEST_PASSWORD = "<PASSWORD>";
private static final Long TEST_ID = 1L;
private static final String TEST_EMAIL = "test";
private CustomUserDetailsService service;
@Mock
private UserRepository userRepository;
@Before
public void init(){
MockitoAnnotations.initMocks(this);
service = new CustomUserDetailsService();
service.setUserRepository(userRepository);
}
@Test
public void shouldReturnUserDetailsOfExistingUser(){
// given
User user= createUser();
when(userRepository.findByEmail(TEST_EMAIL)).thenReturn(user);
// when
UserDetails actual = service.loadUserByUsername(TEST_EMAIL);
// then
assertNotNull(actual);
assertEquals(user.getEmail(), actual.getUsername());
assertEquals(user.getPassword(), actual.getPassword());
assertNotNull(actual.getAuthorities());
assertEquals(user.getRoles().size(), actual.getAuthorities().size());
}
@Test(expected=UsernameNotFoundException.class)
public void shouldNotReturnUserDetailsForNonExistingUser(){
// given
when(userRepository.findByEmail(TEST_EMAIL)).thenReturn(null);
// when
service.loadUserByUsername(TEST_EMAIL);
}
private User createUser() {
User user = new User();
user.setEmail(TEST_EMAIL);
user.setId(TEST_ID);
user.setPassword(<PASSWORD>);
Set<UserRole> roles = new HashSet<UserRole>();
UserRole role = createRole(user);
role.setRole(UserRoleType.ROLE_ADMIN);
roles.add(role);
user.setRoles(roles);
return user;
}
private UserRole createRole(User user) {
UserRole role = new UserRole();
role.setId(TEST_ID);
role.setUser(user);
return role;
}
}
| 2,474 | 0.766896 | 0.766491 | 93 | 25.569893 | 21.461342 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.688172 | false | false | 3 |
24ea21f8ae8566d4bed8df438fa066f748b6989a | 18,571,438,597,962 | dc3e53f15daff933c3cc6cdd3a5e0ee22e38035d | /service/src/main/java/cn/people/cms/modules/cms/service/impl/SiteService.java | b58c11340c4223c714cd1ce8d38314128c2c1188 | [] | no_license | nickel-fang/cms | https://github.com/nickel-fang/cms | fcb8578a620acf9ee4aa645085a28f5692bd9c24 | 5f68840a2a41e44b0597fa4551efa7c5508be705 | refs/heads/master | 2022-12-20T16:50:10.819000 | 2020-03-05T07:57:14 | 2020-03-05T07:57:14 | 245,101,730 | 0 | 0 | null | false | 2022-12-09T01:19:50 | 2020-03-05T07:56:30 | 2020-03-05T07:57:54 | 2022-12-09T01:19:50 | 6,208 | 0 | 0 | 16 | JavaScript | false | false | package cn.people.cms.modules.cms.service.impl;
import cn.people.cms.base.dao.BaseDao;
import cn.people.cms.base.service.impl.BaseService;
import cn.people.cms.modules.cms.model.Site;
import cn.people.cms.modules.cms.model.front.SiteVO;
import cn.people.cms.modules.cms.service.ISiteService;
import cn.people.cms.modules.sys.service.impl.CategoryService;
import cn.people.cms.modules.user.model.User;
import cn.people.cms.modules.user.service.impl.UserService;
import cn.people.cms.util.base.ShiroUtils;
import cn.people.cms.util.base.UserUtil;
import cn.people.cms.util.mapper.BeanMapper;
import cn.people.domain.IUser;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.QueryResult;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.lang.Lang;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Created by lml on 2016/12/26.
*/
@Transactional(readOnly = true)
@Service
public class SiteService extends BaseService<Site> implements ISiteService {
@Autowired
private BaseDao dao;
@Autowired
private UserService userService;
@Autowired
private CategoryService categoryService;
@Override
@Transactional
public Object save(Site site) {
boolean isInit = site.getId() == null;
super.save(site);
//如果是初始化则建一个同名的频道
if(isInit){
categoryService.initRootCategory(site);
}
return site;
}
@Override
public Site fetch(Integer id) {
return dao.fetchLinks(dao.fetch(Site.class,id),Site.TEMPLATE);
}
@Override
public List all(Boolean role) {
IUser user = ShiroUtils.getUser();
List<Site> sites = dao.query(Site.class,Cnd.where("del_flag","=",Site.STATUS_ONLINE));
if (null != role) {
if(user.getId() == 3 && role){ //超级管理员或者安全保密管理员在角色管理中可以看到全部站点
return sites;
}
}
if(user.isAdmin(user.getId())){ //超级管理员或者安全保密管理员在角色管理中可以看到全部站点
return sites;
}
User entity = BeanMapper.map(user, User.class);
Set<Integer> accessIds = userService.getSiteIds(entity, 2); //1代表前台,2代表后台 目前先全部返回后台的
if(Lang.isEmpty(accessIds)){
return null;
}
sites = sites.stream().filter(site->accessIds.contains(site.getId())).collect(Collectors.toList());
return sites;
}
@Override
public QueryResult findByVO(SiteVO siteVO) {
IUser user = UserUtil.getUser();
User entity = BeanMapper.map(user, User.class);
Set<Integer> accessIds = userService.getSiteIds(entity,2);
if(Lang.isEmpty(accessIds)){
return null;
}
String[] includes= accessIds.stream().map(a->a.toString()).collect(Collectors.toSet()).toArray(new String[accessIds.size()]);
Criteria criteria = Cnd.NEW().getCri();
SqlExpressionGroup cnd = criteria.where().andIn("id", includes);
cnd.and("del_flag","<",Site.STATUS_DELETE);
if(StringUtils.isNotBlank(siteVO.getName())){
cnd.and("name","like","%"+siteVO.getName()+"%");
}
return listPage(siteVO.getPageNumber(),siteVO.getPageSize(),criteria);
}
}
| UTF-8 | Java | 3,620 | java | SiteService.java | Java | [
{
"context": "rt java.util.stream.Collectors;\n\n/**\n * Created by lml on 2016/12/26.\n */\n@Transactional(readOnly = true",
"end": 1114,
"score": 0.9985009431838989,
"start": 1111,
"tag": "USERNAME",
"value": "lml"
}
] | null | [] | package cn.people.cms.modules.cms.service.impl;
import cn.people.cms.base.dao.BaseDao;
import cn.people.cms.base.service.impl.BaseService;
import cn.people.cms.modules.cms.model.Site;
import cn.people.cms.modules.cms.model.front.SiteVO;
import cn.people.cms.modules.cms.service.ISiteService;
import cn.people.cms.modules.sys.service.impl.CategoryService;
import cn.people.cms.modules.user.model.User;
import cn.people.cms.modules.user.service.impl.UserService;
import cn.people.cms.util.base.ShiroUtils;
import cn.people.cms.util.base.UserUtil;
import cn.people.cms.util.mapper.BeanMapper;
import cn.people.domain.IUser;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.QueryResult;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.lang.Lang;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Created by lml on 2016/12/26.
*/
@Transactional(readOnly = true)
@Service
public class SiteService extends BaseService<Site> implements ISiteService {
@Autowired
private BaseDao dao;
@Autowired
private UserService userService;
@Autowired
private CategoryService categoryService;
@Override
@Transactional
public Object save(Site site) {
boolean isInit = site.getId() == null;
super.save(site);
//如果是初始化则建一个同名的频道
if(isInit){
categoryService.initRootCategory(site);
}
return site;
}
@Override
public Site fetch(Integer id) {
return dao.fetchLinks(dao.fetch(Site.class,id),Site.TEMPLATE);
}
@Override
public List all(Boolean role) {
IUser user = ShiroUtils.getUser();
List<Site> sites = dao.query(Site.class,Cnd.where("del_flag","=",Site.STATUS_ONLINE));
if (null != role) {
if(user.getId() == 3 && role){ //超级管理员或者安全保密管理员在角色管理中可以看到全部站点
return sites;
}
}
if(user.isAdmin(user.getId())){ //超级管理员或者安全保密管理员在角色管理中可以看到全部站点
return sites;
}
User entity = BeanMapper.map(user, User.class);
Set<Integer> accessIds = userService.getSiteIds(entity, 2); //1代表前台,2代表后台 目前先全部返回后台的
if(Lang.isEmpty(accessIds)){
return null;
}
sites = sites.stream().filter(site->accessIds.contains(site.getId())).collect(Collectors.toList());
return sites;
}
@Override
public QueryResult findByVO(SiteVO siteVO) {
IUser user = UserUtil.getUser();
User entity = BeanMapper.map(user, User.class);
Set<Integer> accessIds = userService.getSiteIds(entity,2);
if(Lang.isEmpty(accessIds)){
return null;
}
String[] includes= accessIds.stream().map(a->a.toString()).collect(Collectors.toSet()).toArray(new String[accessIds.size()]);
Criteria criteria = Cnd.NEW().getCri();
SqlExpressionGroup cnd = criteria.where().andIn("id", includes);
cnd.and("del_flag","<",Site.STATUS_DELETE);
if(StringUtils.isNotBlank(siteVO.getName())){
cnd.and("name","like","%"+siteVO.getName()+"%");
}
return listPage(siteVO.getPageNumber(),siteVO.getPageSize(),criteria);
}
}
| 3,620 | 0.678488 | 0.674419 | 97 | 34.463917 | 25.933325 | 133 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.701031 | false | false | 3 |
7a0825884ee763158933aacbcf7ea1c200a94bf9 | 14,139,032,349,547 | 126841c2d3b28d134855e2cc3fcfc5ffd5c0072b | /src/main/java/com/shred/greedy/_55_JumpGame.java | b5f3588a5c62a86125490f9aa6b98a77a5baee72 | [] | no_license | shredoreo/algorithm-java | https://github.com/shredoreo/algorithm-java | 112929ebf6665d991ad576a560bd567bd0dea7b6 | 9d178f462b0dac404f4164de8af361fea2409a8a | refs/heads/main | 2023-08-13T09:15:45.024000 | 2021-09-27T10:05:59 | 2021-09-27T10:05:59 | 401,403,120 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.shred.greedy;
/*
55. 跳跃游戏
给定一个非负整数数组 nums ,你最初位于数组的 第一个下标 。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
判断你是否能够到达最后一个下标。
示例 1:
输入:nums = [2,3,1,1,4]
输出:true
解释:可以先跳 1 步,从下标 0 到达下标 1, 然后再从下标 1 跳 3 步到达最后一个下标。
示例 2:
输入:nums = [3,2,1,0,4]
输出:false
解释:无论怎样,总会到达下标为 3 的位置。但该下标的最大跳跃长度是 0 , 所以永远不可能到达最后一个下标。
提示:
1 <= nums.length <= 3 * 104
0 <= nums[i] <= 105
*/
public class _55_JumpGame {
class Solution {
public boolean canJump(int[] nums) {
if (nums.length <=1){
return true;
}
int span=0;
for (int i = 0; i <= span; i++) {
//每次跳最远,取最大的覆盖范围
// i+nums[i]为当前格子的覆盖范围
// span为历史最大的覆盖范围
span=Math.max(i+nums[i], span);
if (span>=nums.length-1){
return true;
}
}
return false;
}
/*
执行用时:
2 ms
, 在所有 Java 提交中击败了
96.25%
的用户
内存消耗:
39.8 MB
, 在所有 Java 提交中击败了
47.88%
的用户
*/
}
public static void main(String[] args) {
}
}
| UTF-8 | Java | 1,554 | java | _55_JumpGame.java | Java | [] | null | [] | package com.shred.greedy;
/*
55. 跳跃游戏
给定一个非负整数数组 nums ,你最初位于数组的 第一个下标 。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
判断你是否能够到达最后一个下标。
示例 1:
输入:nums = [2,3,1,1,4]
输出:true
解释:可以先跳 1 步,从下标 0 到达下标 1, 然后再从下标 1 跳 3 步到达最后一个下标。
示例 2:
输入:nums = [3,2,1,0,4]
输出:false
解释:无论怎样,总会到达下标为 3 的位置。但该下标的最大跳跃长度是 0 , 所以永远不可能到达最后一个下标。
提示:
1 <= nums.length <= 3 * 104
0 <= nums[i] <= 105
*/
public class _55_JumpGame {
class Solution {
public boolean canJump(int[] nums) {
if (nums.length <=1){
return true;
}
int span=0;
for (int i = 0; i <= span; i++) {
//每次跳最远,取最大的覆盖范围
// i+nums[i]为当前格子的覆盖范围
// span为历史最大的覆盖范围
span=Math.max(i+nums[i], span);
if (span>=nums.length-1){
return true;
}
}
return false;
}
/*
执行用时:
2 ms
, 在所有 Java 提交中击败了
96.25%
的用户
内存消耗:
39.8 MB
, 在所有 Java 提交中击败了
47.88%
的用户
*/
}
public static void main(String[] args) {
}
}
| 1,554 | 0.497207 | 0.452514 | 65 | 15.523077 | 15.196262 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.307692 | false | false | 3 |
caddb8c233a971d6dcf0c08ec7fa2fd3bbe4254f | 12,730,283,077,649 | 4df578c2b3d2dfeb661106bcbb1cec8df12b0ead | /picocli-codegen-tests-java9plus/src/main/java/picocli/annotation/processing/tests/CommandSpec2YamlProcessor.java | 30e2d16a27af31090f360ac77c192fd10311662a | [
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"Classpath-exception-2.0",
"GPL-2.0-only"
] | permissive | remkop/picocli | https://github.com/remkop/picocli | 2d2555762ba6cb4d58b5f0b3112342dc8191dbd3 | 8e48885fc25424bd84232a16cfca6f60d088bc96 | refs/heads/main | 2023-09-01T20:17:15.575000 | 2023-08-28T21:51:26 | 2023-08-28T21:51:26 | 80,640,282 | 4,563 | 577 | Apache-2.0 | false | 2023-09-14T11:43:03 | 2017-02-01T16:38:41 | 2023-09-14T11:05:08 | 2023-09-14T11:42:59 | 83,472 | 4,390 | 397 | 120 | Java | false | false | package picocli.annotation.processing.tests;
import picocli.CommandLine.Model.CommandSpec;
import picocli.codegen.annotation.processing.AbstractCommandSpecProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class CommandSpec2YamlProcessor extends AbstractCommandSpecProcessor {
public List<String> strings = new ArrayList<String>();
public Map<Element, CommandSpec> commands;
@Override
protected boolean handleCommands(Map<Element, CommandSpec> commands,
Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
System.out.println(commands);
this.commands = commands;
CommandSpecYamlPrinter printer = new CommandSpecYamlPrinter();
for (Map.Entry<Element, CommandSpec> entry : commands.entrySet()) {
StringWriter sw = new StringWriter();
printer.print(entry.getValue(), new PrintWriter(sw));
strings.add(sw.toString());
}
return false;
}
}
| UTF-8 | Java | 1,292 | java | CommandSpec2YamlProcessor.java | Java | [] | null | [] | package picocli.annotation.processing.tests;
import picocli.CommandLine.Model.CommandSpec;
import picocli.codegen.annotation.processing.AbstractCommandSpecProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class CommandSpec2YamlProcessor extends AbstractCommandSpecProcessor {
public List<String> strings = new ArrayList<String>();
public Map<Element, CommandSpec> commands;
@Override
protected boolean handleCommands(Map<Element, CommandSpec> commands,
Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
System.out.println(commands);
this.commands = commands;
CommandSpecYamlPrinter printer = new CommandSpecYamlPrinter();
for (Map.Entry<Element, CommandSpec> entry : commands.entrySet()) {
StringWriter sw = new StringWriter();
printer.print(entry.getValue(), new PrintWriter(sw));
strings.add(sw.toString());
}
return false;
}
}
| 1,292 | 0.702012 | 0.701238 | 36 | 34.888889 | 25.769035 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 3 |
21dadbb980cfdce8ddacf8d57e73f4ecd56e4e55 | 23,502,061,060,254 | 9512a245259fcc007988f869eee9e17c899d119d | /DictionaryCommandline.java | 03dff73937deb4716c3eb447aafd588da1b01923 | [] | no_license | trunganhvu/Dictionary_OOP | https://github.com/trunganhvu/Dictionary_OOP | 560dbe2ee56c61752cbf6f042389907249b15e8d | 81185089a6539cd826ac999f2950cc88082c2cc5 | refs/heads/master | 2020-03-31T20:38:20.524000 | 2020-02-19T08:35:24 | 2020-02-19T08:35:24 | 152,548,638 | 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 dictionary;
import java.io.IOException;
/**
*
* @author Tommmm^^
*/
public class DictionaryCommandline {
static DictionaryManagement Dict = new DictionaryManagement();
public void showAllWords() { //show tất cả cá từ trong file
int size = Dict.getSize();
System.out.printf("%-10s%-20s%s\n","STT","English","Viet");
for(int i = 0 ; i < size ; i++) {
System.out.printf("%-10s%-20s%s\n", i + 1, Dictionary.Words.get(i).getWord_target(),
Dictionary.Words.get(i).getWord_explain());
}
}
public void dictionaryBasic() { //them ham dictionaryBasic
Dict.insertFromCommandline();
showAllWords();
}
public void dictionaryAdvanced() throws IOException { //them ham dictionaryAdvanced
Dict.insertFromFile();
// showAllWords();
// Dict.repairWord();
// showAllWords();
// Dict.dictionaryLookup();
Dict.addWord();
showAllWords();
}
public static void main(String[] args)throws IOException { // ham main goi ham dictionaryAdvanced va ham dictionaryBasic
DictionaryCommandline dictCom = new DictionaryCommandline();
dictCom.dictionaryAdvanced();
// dictCom.DictionarySearcher();
}
} | UTF-8 | Java | 1,839 | java | DictionaryCommandline.java | Java | [
{
"context": "import java.io.IOException;\r\n\r\n/**\r\n *\r\n * @author Tommmm^^\r\n */\r\npublic class DictionaryCommandline { ",
"end": 270,
"score": 0.9810959100723267,
"start": 264,
"tag": "USERNAME",
"value": "Tommmm"
}
] | 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 dictionary;
import java.io.IOException;
/**
*
* @author Tommmm^^
*/
public class DictionaryCommandline {
static DictionaryManagement Dict = new DictionaryManagement();
public void showAllWords() { //show tất cả cá từ trong file
int size = Dict.getSize();
System.out.printf("%-10s%-20s%s\n","STT","English","Viet");
for(int i = 0 ; i < size ; i++) {
System.out.printf("%-10s%-20s%s\n", i + 1, Dictionary.Words.get(i).getWord_target(),
Dictionary.Words.get(i).getWord_explain());
}
}
public void dictionaryBasic() { //them ham dictionaryBasic
Dict.insertFromCommandline();
showAllWords();
}
public void dictionaryAdvanced() throws IOException { //them ham dictionaryAdvanced
Dict.insertFromFile();
// showAllWords();
// Dict.repairWord();
// showAllWords();
// Dict.dictionaryLookup();
Dict.addWord();
showAllWords();
}
public static void main(String[] args)throws IOException { // ham main goi ham dictionaryAdvanced va ham dictionaryBasic
DictionaryCommandline dictCom = new DictionaryCommandline();
dictCom.dictionaryAdvanced();
// dictCom.DictionarySearcher();
}
} | 1,839 | 0.507642 | 0.502183 | 50 | 34.68 | 33.739853 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.58 | false | false | 3 |
3488090d14cbee79af22521ea4c20b994a5393fc | 32,813,550,142,392 | 49a3e0d246483bfdbda4c79c5b135faf594c1366 | /src/net/sf/ardengine/events/IEvent.java | b940372130d5237b4bdd404a6a32587f7c8edab0 | [] | no_license | Mytrin/ArdEngine | https://github.com/Mytrin/ArdEngine | 506ab07864ff78b0e50ee3fe5386c9f4bcfbd99c | b024ac548b5b19e7bcaef962614bfe0c26b3fcdb | refs/heads/master | 2021-01-17T09:36:23.780000 | 2017-12-21T11:24:47 | 2017-12-21T11:24:47 | 83,989,849 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.sf.ardengine.events;
/**
* Interface for events, which contain information about specific situation.
*
* Node.invokeEvent() processes this event through list of Node listeners
*/
public interface IEvent {
/**
* @return Purpose of event(faster than instanceof)
*/
public EventType getEventType();
/**
* Blocks further propagation of event
*/
public void consume();
/**
* @return True, if event should not be propagated further
*/
public boolean isConsumed();
} | UTF-8 | Java | 533 | java | IEvent.java | Java | [] | null | [] | package net.sf.ardengine.events;
/**
* Interface for events, which contain information about specific situation.
*
* Node.invokeEvent() processes this event through list of Node listeners
*/
public interface IEvent {
/**
* @return Purpose of event(faster than instanceof)
*/
public EventType getEventType();
/**
* Blocks further propagation of event
*/
public void consume();
/**
* @return True, if event should not be propagated further
*/
public boolean isConsumed();
} | 533 | 0.662289 | 0.662289 | 24 | 21.25 | 24.033398 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 3 |
cb55d79778dcbdac8734c1e05b9c9e235aac1b5e | 23,424,751,640,041 | 0a8b5cf49e871ca6d5612c46e06dbb1b71313f6e | /taskPro/taskPro-web/src/main/java/userBean/CheckKantoriBean.java | 7ee90bac5493fa88d3f0d684732a86ecd2d817e8 | [] | no_license | sarzwest/taskPro | https://github.com/sarzwest/taskPro | 60d52854f5fcce1d888830c824dd020c7212bb5c | b1378e0fbcb772fa5583c85610c0f9874e41c911 | refs/heads/master | 2020-04-25T03:17:48.179000 | 2013-02-06T22:18:18 | 2013-02-06T22:18:18 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package userBean;
import BL.IBussiness.ApplicationLocal;
import BL.IBussiness.IUzivatelB;
import BL.Uzivatel.UzivatelB;
import DL.entity.Kantor;
import DL.entity.Student;
import DL.entity.Uzivatel;
import java.io.Serializable;
import java.security.Principal;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
/**
*
* Beana soužící k výpisu a mazání kantoru.
* @author Lurtz
*/
@ManagedBean(name = "checkKantoriBean")
@RequestScoped
public class CheckKantoriBean implements Serializable {
Uzivatel chosen;
List<Kantor> kantori;
IUzivatelB uzivatelB;
// @EJB
@Inject
ApplicationLocal app;
@PostConstruct
public void init(){
uzivatelB = UzivatelB.getInstance(app);
kantori = uzivatelB.getAllKantor();
}
public CheckKantoriBean() {
}
/**
* Metoda pozada business logiku o odstraneni aktualniho vybraneho kantora a aktalizuje
* seznam kantoru v DB
* @return checkstudentAdmin - navigacni pravidlo
*/
public String deleteKantor(){
uzivatelB.removeUser(chosen.getLogin());
kantori = uzivatelB.getAllKantor();
return "checkkantoriAdmin";
}
public String modifyUser(){
uzivatelB.modifyUser(chosen);
return "checkkantoriAdmin";
}
/**
* Metoda slouzi k vraceni aktualne prihlaseneho uzivatele (Principala), JSF
* JAAS framework
* @return aktualne prihlaseneho Principala
*/
private Principal getPrincipal() {
return FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();
}
public List<Kantor> getKantori() {
return kantori;
}
public void setKantori(List<Kantor> kantori) {
this.kantori = kantori;
}
public Uzivatel getChosen() {
return chosen;
}
public void setChosen(Uzivatel chosen) {
this.chosen = chosen;
}
}
| UTF-8 | Java | 2,279 | java | CheckKantoriBean.java | Java | [
{
"context": "eana soužící k výpisu a mazání kantoru.\n * @author Lurtz\n */\n@ManagedBean(name = \"checkKantoriBean\")\n@Requ",
"end": 695,
"score": 0.9969132542610168,
"start": 690,
"tag": "NAME",
"value": "Lurtz"
}
] | null | [] | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package userBean;
import BL.IBussiness.ApplicationLocal;
import BL.IBussiness.IUzivatelB;
import BL.Uzivatel.UzivatelB;
import DL.entity.Kantor;
import DL.entity.Student;
import DL.entity.Uzivatel;
import java.io.Serializable;
import java.security.Principal;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
/**
*
* Beana soužící k výpisu a mazání kantoru.
* @author Lurtz
*/
@ManagedBean(name = "checkKantoriBean")
@RequestScoped
public class CheckKantoriBean implements Serializable {
Uzivatel chosen;
List<Kantor> kantori;
IUzivatelB uzivatelB;
// @EJB
@Inject
ApplicationLocal app;
@PostConstruct
public void init(){
uzivatelB = UzivatelB.getInstance(app);
kantori = uzivatelB.getAllKantor();
}
public CheckKantoriBean() {
}
/**
* Metoda pozada business logiku o odstraneni aktualniho vybraneho kantora a aktalizuje
* seznam kantoru v DB
* @return checkstudentAdmin - navigacni pravidlo
*/
public String deleteKantor(){
uzivatelB.removeUser(chosen.getLogin());
kantori = uzivatelB.getAllKantor();
return "checkkantoriAdmin";
}
public String modifyUser(){
uzivatelB.modifyUser(chosen);
return "checkkantoriAdmin";
}
/**
* Metoda slouzi k vraceni aktualne prihlaseneho uzivatele (Principala), JSF
* JAAS framework
* @return aktualne prihlaseneho Principala
*/
private Principal getPrincipal() {
return FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();
}
public List<Kantor> getKantori() {
return kantori;
}
public void setKantori(List<Kantor> kantori) {
this.kantori = kantori;
}
public Uzivatel getChosen() {
return chosen;
}
public void setChosen(Uzivatel chosen) {
this.chosen = chosen;
}
}
| 2,279 | 0.672239 | 0.672239 | 97 | 22.432989 | 19.698713 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.371134 | false | false | 3 |
d31b47591fbe4e158b03c7faa916eb2c2c883006 | 11,158,325,092,407 | 896298b8f5dd45b8c471bae5912b10bdea9d8524 | /src/main/java/xyz/rushmead/stagelights/util/StageLightsTab.java | 585fae998fc576e5ce04501a3f976aee69d60906 | [] | no_license | Rushmead/Stagelights | https://github.com/Rushmead/Stagelights | c5d19ad8fc7d4da7774d1fba9a9adffb39bc9ba4 | 617f115475523f2f6b21e4af402142cc9ea3b815 | refs/heads/master | 2017-11-30T18:53:55.790000 | 2016-08-06T09:24:44 | 2016-08-06T09:24:44 | 63,876,200 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package xyz.rushmead.stagelights.util;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import xyz.rushmead.stagelights.StageLights;
/**
* Created by Rushmead for StageLights.
*/
public class StageLightsTab {
public static CreativeTabs TAB = new CreativeTabs(StageLights.MODID) {
@Override
public Item getTabIconItem() {
return Item.getItemFromBlock(Blocks.REDSTONE_LAMP);
}
};
}
| UTF-8 | Java | 495 | java | StageLightsTab.java | Java | [
{
"context": "shmead.stagelights.StageLights;\n\n/**\n * Created by Rushmead for StageLights.\n */\npublic class StageLightsTab ",
"end": 225,
"score": 0.9582209587097168,
"start": 217,
"tag": "USERNAME",
"value": "Rushmead"
}
] | null | [] | package xyz.rushmead.stagelights.util;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import xyz.rushmead.stagelights.StageLights;
/**
* Created by Rushmead for StageLights.
*/
public class StageLightsTab {
public static CreativeTabs TAB = new CreativeTabs(StageLights.MODID) {
@Override
public Item getTabIconItem() {
return Item.getItemFromBlock(Blocks.REDSTONE_LAMP);
}
};
}
| 495 | 0.721212 | 0.721212 | 21 | 22.571428 | 22.385309 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 3 |
303efbeb0d9c702e995e0aac1f1d971b3de54651 | 28,132,035,806,165 | b56e8b90663318ddebcee41ced89fd14418444c9 | /app/src/main/java/cn/weli/svideo/module/task/model/bean/CoinOpenStatusBean.java | bcc25c6e7650f9ed1d7d38c1da98ee82d5df745f | [] | no_license | Grekit-Sun-Coder/svideo | https://github.com/Grekit-Sun-Coder/svideo | 19ce81e26258de63eb98b402520b1a6eae2b110a | 8879a0f0b2ad47c704eebdd20f6244ea834ecfd8 | refs/heads/master | 2021-02-21T06:10:09.337000 | 2020-03-06T07:11:21 | 2020-03-06T07:11:21 | 245,351,989 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.weli.svideo.module.task.model.bean;
/**
* Function description
*
* @author Lei Jiang
* @version [1.0.0]
* @date 2019-12-25
* @see [class/method]
* @since [1.0.0]
*/
public class CoinOpenStatusBean {
public long seconds;
}
| UTF-8 | Java | 247 | java | CoinOpenStatusBean.java | Java | [
{
"context": "l.bean;\n\n/**\n * Function description\n *\n * @author Lei Jiang\n * @version [1.0.0]\n * @date 2019-12-25\n * @see [",
"end": 99,
"score": 0.9998283386230469,
"start": 90,
"tag": "NAME",
"value": "Lei Jiang"
}
] | null | [] | package cn.weli.svideo.module.task.model.bean;
/**
* Function description
*
* @author <NAME>
* @version [1.0.0]
* @date 2019-12-25
* @see [class/method]
* @since [1.0.0]
*/
public class CoinOpenStatusBean {
public long seconds;
}
| 244 | 0.651822 | 0.595142 | 15 | 15.466666 | 13.265829 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.133333 | false | false | 3 |
d8070a522fd59ead04915ddf421f7ca72e4b4f9b | 16,363,825,440,582 | 1a84c91c1b888820ca236b56c2a4cb01b2ecb52d | /app/src/main/java/id/thony/android/quranlite/data/source/preferences/DayNightPreferencesSource.java | 1d9a34770e7810810b0ec1bcf6018fcda0ae5f4f | [
"MIT"
] | permissive | fathonyfath/quran-lite-android | https://github.com/fathonyfath/quran-lite-android | 4a541a1b6be2256a43ac84cb03e86e10cc68c94a | 9f4948623b5500c923cb2818e7ab2797ca8760d9 | refs/heads/main | 2022-08-26T18:04:50.465000 | 2022-08-21T12:04:05 | 2022-08-21T12:04:05 | 164,826,906 | 6 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package id.thony.android.quranlite.data.source.preferences;
import android.annotation.SuppressLint;
import android.content.SharedPreferences;
public class DayNightPreferencesSource {
private static final String DAY_NIGHT_PREFERENCE_KEY = "DAY_NIGHT_PREFERENCE_KEY";
private final SharedPreferences sharedPreferences;
public DayNightPreferencesSource(SharedPreferences sharedPreferences) {
this.sharedPreferences = sharedPreferences;
}
@SuppressLint("ApplySharedPref")
public void putValue(String preference) {
this.sharedPreferences.edit()
.putString(DAY_NIGHT_PREFERENCE_KEY, preference)
.commit();
}
public String getValue() {
return this.sharedPreferences.getString(DAY_NIGHT_PREFERENCE_KEY, "");
}
}
| UTF-8 | Java | 802 | java | DayNightPreferencesSource.java | Java | [] | null | [] | package id.thony.android.quranlite.data.source.preferences;
import android.annotation.SuppressLint;
import android.content.SharedPreferences;
public class DayNightPreferencesSource {
private static final String DAY_NIGHT_PREFERENCE_KEY = "DAY_NIGHT_PREFERENCE_KEY";
private final SharedPreferences sharedPreferences;
public DayNightPreferencesSource(SharedPreferences sharedPreferences) {
this.sharedPreferences = sharedPreferences;
}
@SuppressLint("ApplySharedPref")
public void putValue(String preference) {
this.sharedPreferences.edit()
.putString(DAY_NIGHT_PREFERENCE_KEY, preference)
.commit();
}
public String getValue() {
return this.sharedPreferences.getString(DAY_NIGHT_PREFERENCE_KEY, "");
}
}
| 802 | 0.726933 | 0.726933 | 25 | 31.08 | 27.708366 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 3 |
761f56586f67f2637c693bbc3e848ba6472e1b81 | 25,005,299,623,549 | 4d70947af36d1f4f50432b27b08b29d86aec81c7 | /ResManagment/src/com/ts/web/reviewServlet.java | a4969ad4b6f829b469e38b91cbdd81e1d86c2493 | [] | no_license | navya-dan/Online-Restaurant-Guide | https://github.com/navya-dan/Online-Restaurant-Guide | cc894acca0492ece92fd4d808ccde8a02d7fe388 | 8e4add785aeae571261868ecf108c4096be2e4c0 | refs/heads/master | 2021-06-26T13:06:55.983000 | 2021-01-12T02:53:21 | 2021-01-12T02:53:21 | 185,922,908 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ts.web;
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.ts.dao.ReviewDAO;
import com.ts.dto.Manager;
import com.ts.dto.Reviews;
import com.ts.dto.User;
@WebServlet("/reviewServlet")
public class reviewServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public reviewServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(true);
String comment=request.getParameter("comment");
int rating=Integer.parseInt(request.getParameter("rating"));
User user=(User)session.getAttribute("user");
Manager manager = (Manager)session.getAttribute("manager");
Reviews reviews=new Reviews(comment,rating,manager,user);
ReviewDAO reviewDao= new ReviewDAO();
reviewDao.register(reviews);
List<Reviews> reviewsData=ReviewDAO.getAllReviews(manager.getBranchId());
session.setAttribute("reviewsData",reviewsData);
RequestDispatcher rd = request.getRequestDispatcher("DisplayRecipe.jsp");
rd.include(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
| UTF-8 | Java | 1,844 | java | reviewServlet.java | Java | [] | null | [] | package com.ts.web;
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.ts.dao.ReviewDAO;
import com.ts.dto.Manager;
import com.ts.dto.Reviews;
import com.ts.dto.User;
@WebServlet("/reviewServlet")
public class reviewServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public reviewServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(true);
String comment=request.getParameter("comment");
int rating=Integer.parseInt(request.getParameter("rating"));
User user=(User)session.getAttribute("user");
Manager manager = (Manager)session.getAttribute("manager");
Reviews reviews=new Reviews(comment,rating,manager,user);
ReviewDAO reviewDao= new ReviewDAO();
reviewDao.register(reviews);
List<Reviews> reviewsData=ReviewDAO.getAllReviews(manager.getBranchId());
session.setAttribute("reviewsData",reviewsData);
RequestDispatcher rd = request.getRequestDispatcher("DisplayRecipe.jsp");
rd.include(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
| 1,844 | 0.748373 | 0.747831 | 56 | 30.928572 | 28.394451 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.428571 | false | false | 3 |
17e638801731fed728bbfd0161e6ab94f43e8b7b | 25,512,105,738,869 | 060130510a75e480ff55ad555d1508a2aa1f7e92 | /Laboratorio de computacion II - Trabajos practicos/src/TP7/ExcepcionesPropias.java | 907293a0e1cf9493f87d3231066d370a6ef9e58a | [] | no_license | jeremiasalvarez/lab-comp-2 | https://github.com/jeremiasalvarez/lab-comp-2 | 9c4ef1b4b350155656aafa47c9831143c8efea5e | 868badd1c73c7144df35f64b719fde650509c191 | refs/heads/master | 2020-07-01T22:28:05.384000 | 2019-11-29T15:43:31 | 2019-11-29T15:43:31 | 201,323,078 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package TP7;
import java.util.Scanner;
public class ExcepcionesPropias {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int numero;
System.out.println("Ingresar un numero del 1 al 100");
numero = scan.nextInt();
validar(numero);
}
static void validar (int num) throws FueraDeRango {
if (num < 1 || num > 100) {
FueraDeRango eN = new FueraDeRango("El numero esta fuera de rango");
throw eN;
}
}
}
| UTF-8 | Java | 566 | java | ExcepcionesPropias.java | Java | [] | null | [] | package TP7;
import java.util.Scanner;
public class ExcepcionesPropias {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int numero;
System.out.println("Ingresar un numero del 1 al 100");
numero = scan.nextInt();
validar(numero);
}
static void validar (int num) throws FueraDeRango {
if (num < 1 || num > 100) {
FueraDeRango eN = new FueraDeRango("El numero esta fuera de rango");
throw eN;
}
}
}
| 566 | 0.551237 | 0.535336 | 29 | 17.517241 | 22.002541 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.37931 | false | false | 3 |
54c1ce8210a738b21ba982ece1dde65883eb758e | 16,209,206,618,622 | 22838a58b5ff355e3db546739f1b1dc39e6fc89c | /DoubleDispatch/TeclaInvalidaException.java | 798f2ce7e837aea9315d66b362e5a65d38726a91 | [] | no_license | gigietelman/disenio_sistemas | https://github.com/gigietelman/disenio_sistemas | a3dc0f0ca24e6c9effcafa27bc60d9e01452eff6 | 44f818b7c004f48bba1b42ee69c9a37f68779a8c | refs/heads/master | 2023-01-06T19:23:17.840000 | 2020-10-28T00:46:11 | 2020-10-28T00:46:11 | 297,176,787 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package DoubleDispatch;
public class TeclaInvalidaException extends Exception {
}
| UTF-8 | Java | 84 | java | TeclaInvalidaException.java | Java | [] | null | [] | package DoubleDispatch;
public class TeclaInvalidaException extends Exception {
}
| 84 | 0.833333 | 0.833333 | 5 | 15.8 | 21.479292 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false | 3 |
d337c88d4418c51122ef91cc4dacda628f84e0ae | 16,209,206,620,952 | a5e433478a6ab9931581bbc23b803726fc0a9109 | /transaction/src/main/java/tk/zhangh/springboot/transaction/lazy/StudentService.java | 484cfcbc65cc02339c08aae9bf13ad5227f2fbc3 | [] | no_license | zhanghTK/spring-boot | https://github.com/zhanghTK/spring-boot | a777c74b20499d7eec40617877d8c1159b44ca1c | de6ac666fd126e5a41748177815349245c5fc601 | refs/heads/master | 2021-06-23T14:59:50.714000 | 2017-07-15T04:37:08 | 2017-07-15T04:37:08 | 93,913,877 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package tk.zhangh.springboot.transaction.lazy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
/**
* Created by ZhangHao on 2017/7/15.
*/
@Component
public class StudentService {
@Autowired
private StudentDao studentDao;
public void getOne() {
// EntityManagerFactory entityManagerFactory = ApplicationContextProvider.getApplicationContext().getBean(EntityManagerFactory.class);
// EntityManager entityManager = entityManagerFactory.createEntityManager();
// EntityManagerHolder entityManagerHolder = new EntityManagerHolder(entityManager);
// TransactionSynchronizationManager.bindResource(entityManagerFactory, entityManagerHolder);
System.out.println(studentDao.getOne(1).getName());
// TransactionSynchronizationManager.unbindResource(entityManagerFactory);
// EntityManagerFactoryUtils.closeEntityManager(entityManager);
}
@Transactional
public void testNormalGetOneWithTrans() {
System.out.println(studentDao.getOne(1).getName());
}
public void findOne() {
System.out.println(studentDao.findOne(1).getName());
}
}
| UTF-8 | Java | 1,258 | java | StudentService.java | Java | [
{
"context": "ction.annotation.Transactional;\n\n/**\n * Created by ZhangHao on 2017/7/15.\n */\n@Component\npublic class Student",
"end": 252,
"score": 0.9997243881225586,
"start": 244,
"tag": "NAME",
"value": "ZhangHao"
}
] | null | [] | package tk.zhangh.springboot.transaction.lazy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
/**
* Created by ZhangHao on 2017/7/15.
*/
@Component
public class StudentService {
@Autowired
private StudentDao studentDao;
public void getOne() {
// EntityManagerFactory entityManagerFactory = ApplicationContextProvider.getApplicationContext().getBean(EntityManagerFactory.class);
// EntityManager entityManager = entityManagerFactory.createEntityManager();
// EntityManagerHolder entityManagerHolder = new EntityManagerHolder(entityManager);
// TransactionSynchronizationManager.bindResource(entityManagerFactory, entityManagerHolder);
System.out.println(studentDao.getOne(1).getName());
// TransactionSynchronizationManager.unbindResource(entityManagerFactory);
// EntityManagerFactoryUtils.closeEntityManager(entityManager);
}
@Transactional
public void testNormalGetOneWithTrans() {
System.out.println(studentDao.getOne(1).getName());
}
public void findOne() {
System.out.println(studentDao.findOne(1).getName());
}
}
| 1,258 | 0.761526 | 0.753577 | 33 | 37.121212 | 35.418499 | 141 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false | 3 |
d71cc30317a7f847e26d8d3c0288cd4cc895f93d | 7,627,861,935,578 | 3c7502cc9da3b1827b0a7529985a4e62fa1ade61 | /redbeams-api/src/test/java/com/sequenceiq/redbeams/api/endpoint/v4/stacks/azure/AzureNetworkV4ParametersTest.java | 8b0ff34a026b08ae1ef289421a0a80bce6012515 | [
"LicenseRef-scancode-warranty-disclaimer",
"ANTLR-PD",
"CDDL-1.0",
"bzip2-1.0.6",
"Zlib",
"BSD-3-Clause",
"MIT",
"EPL-1.0",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-jdbm-1.00",
"Apache-2.0"
] | permissive | jdesjean/cloudbreak | https://github.com/jdesjean/cloudbreak | d77d630dab058df4aaa6cf609cb97f542c4cdf8c | d533f24162c043bd5345d07adef0e4074e938027 | refs/heads/master | 2020-07-06T05:06:10.822000 | 2019-08-13T19:55:33 | 2019-08-16T19:58:23 | 202,900,069 | 0 | 0 | Apache-2.0 | true | 2019-08-17T15:42:47 | 2019-08-17T15:42:46 | 2019-08-17T05:40:36 | 2019-08-17T15:35:46 | 69,727 | 0 | 0 | 0 | null | false | false | package com.sequenceiq.redbeams.api.endpoint.v4.stacks.azure;
import static org.assertj.core.api.Assertions.assertThat;
import com.sequenceiq.cloudbreak.common.mappable.CloudPlatform;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
public class AzureNetworkV4ParametersTest {
private AzureNetworkV4Parameters underTest;
@Before
public void setUp() {
underTest = new AzureNetworkV4Parameters();
}
@Test
public void testGettersAndSetters() {
underTest.setVirtualNetwork("someVirtualNetwork");
assertThat(underTest.getVirtualNetwork()).isEqualTo("someVirtualNetwork");
}
@Test
public void testAsMap() {
underTest.setVirtualNetwork("someVirtualNetwork");
assertThat(underTest.asMap()).containsOnly(Map.entry("virtualNetwork", "someVirtualNetwork"),
Map.entry("cloudPlatform", "AZURE"));
}
@Test
public void testGetCloudPlatform() {
assertThat(underTest.getCloudPlatform()).isEqualTo(CloudPlatform.AZURE);
}
@Test
public void testParse() {
Map<String, Object> parameters = Map.of("virtualNetwork", "someVirtualNetwork");
underTest.parse(parameters);
assertThat(underTest.getVirtualNetwork()).isEqualTo("someVirtualNetwork");
}
}
| UTF-8 | Java | 1,313 | java | AzureNetworkV4ParametersTest.java | Java | [] | null | [] | package com.sequenceiq.redbeams.api.endpoint.v4.stacks.azure;
import static org.assertj.core.api.Assertions.assertThat;
import com.sequenceiq.cloudbreak.common.mappable.CloudPlatform;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
public class AzureNetworkV4ParametersTest {
private AzureNetworkV4Parameters underTest;
@Before
public void setUp() {
underTest = new AzureNetworkV4Parameters();
}
@Test
public void testGettersAndSetters() {
underTest.setVirtualNetwork("someVirtualNetwork");
assertThat(underTest.getVirtualNetwork()).isEqualTo("someVirtualNetwork");
}
@Test
public void testAsMap() {
underTest.setVirtualNetwork("someVirtualNetwork");
assertThat(underTest.asMap()).containsOnly(Map.entry("virtualNetwork", "someVirtualNetwork"),
Map.entry("cloudPlatform", "AZURE"));
}
@Test
public void testGetCloudPlatform() {
assertThat(underTest.getCloudPlatform()).isEqualTo(CloudPlatform.AZURE);
}
@Test
public void testParse() {
Map<String, Object> parameters = Map.of("virtualNetwork", "someVirtualNetwork");
underTest.parse(parameters);
assertThat(underTest.getVirtualNetwork()).isEqualTo("someVirtualNetwork");
}
}
| 1,313 | 0.706017 | 0.70297 | 49 | 25.795918 | 29.024254 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 3 |
dcc195ad442976102322073f947a5f6795674acf | 29,197,187,696,433 | c516dc3adb2e8cf0b3e59d7b7bcf31dd1284a021 | /src/com/estore/utils/FillDataBean.java | 2065cce459edc42cd77d06a4f8197c9da337175a | [] | no_license | 794213535/webstore | https://github.com/794213535/webstore | ff7db3cfe969626cf563d8502151f37d27ad2ba5 | b83d712a3af3566ff11ecf81c2a3d92c89a8d64e | refs/heads/master | 2020-03-22T12:42:56.701000 | 2018-07-07T05:52:51 | 2018-07-07T05:52:51 | 140,056,681 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.estore.utils;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.beanutils.BeanUtils;
public class FillDataBean {
public static <T> T fillData(Class<T> clazz,HttpServletRequest request){
Map<String, String[]> map = request.getParameterMap();
T bean = null;
try {
bean = clazz.newInstance();
BeanUtils.populate(bean, map);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return bean;
}
}
| UTF-8 | Java | 674 | java | FillDataBean.java | Java | [] | null | [] | package com.estore.utils;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.beanutils.BeanUtils;
public class FillDataBean {
public static <T> T fillData(Class<T> clazz,HttpServletRequest request){
Map<String, String[]> map = request.getParameterMap();
T bean = null;
try {
bean = clazz.newInstance();
BeanUtils.populate(bean, map);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return bean;
}
}
| 674 | 0.721068 | 0.721068 | 31 | 20.741936 | 19.949884 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.806452 | false | false | 3 |
71cc925ed3c844a21654a15b3b7802e418510baa | 13,099,650,277,128 | a986d7f747d7648de33b2e775ae5e63206a95477 | /online-manage-console/src/main/java/com/wfj/search/online/management/console/service/HotWordService.java | 341295b173c127bb547069085f849f58e536027c | [] | no_license | suevip/wangfujing-online-searching | https://github.com/suevip/wangfujing-online-searching | e8c8c2413cfcf843bb39ada66cc1204a5632eee8 | 573206523ec0c8aafabc64134da570f52e0d1d51 | refs/heads/develop | 2018-03-07T07:18:59.805000 | 2016-05-25T03:26:13 | 2016-05-25T03:26:13 | 64,294,875 | 0 | 1 | null | true | 2016-07-27T09:19:23 | 2016-07-27T09:19:23 | 2016-05-31T05:44:40 | 2016-05-31T05:50:07 | 4,289 | 0 | 0 | 0 | null | null | null | package com.wfj.search.online.management.console.service;
import com.wfj.search.online.common.pojo.HotWordPojo;
import java.util.List;
/**
* <br/>create at 15-12-15
*
* @author liuxh
* @since 1.0.0
*/
public interface HotWordService {
/**
* 分页展示热词列表
*
* @param start 开始
* @param limit 条数
* @return 热词列表
*/
List<HotWordPojo> list(String site, String channel, int start, int limit);
/**
* 热词总数
*
* @return 热词总数
*/
int count(String site, String channel);
/**
* 根据热词id获取热词数据
*
* @param hotWordId 热词id
* @return 热词数据
*/
HotWordPojo get(String hotWordId);
/**
* 添加热词
*
* @param pojo 热词实体
* @param modifier 修改人
* @return 状态,-1数据错误
*/
int add(HotWordPojo pojo, String modifier);
/**
* 修改热词
*
* @param pojo 热词实体
* @param modifier 修改人
* @return 状态,-1数据错误,-2不存在数据,-3存在数据为有效数据
*/
int mod(HotWordPojo pojo, String modifier);
/**
* 删除热词数据
*
* @param sid 热词编号
* @param modifier 修改人
* @return 状态,-1数据错误,-2不存在数据,-3存在数据为有效数据
*/
int del(String sid, String modifier);
/**
* 使热词生效
*
* @param sid 热词编号
* @param modifier 修改人
* @return 状态,-1数据错误,-2不存在数据
*/
int enabled(String sid, String modifier);
/**
* 使热词失效
*
* @param sid 热词编号
* @param modifier 修改人
* @return 状态,-1数据错误,-2不存在数据
*/
int disabled(String sid, String modifier);
}
| UTF-8 | Java | 1,888 | java | HotWordService.java | Java | [
{
"context": "ist;\n\n/**\n * <br/>create at 15-12-15\n *\n * @author liuxh\n * @since 1.0.0\n */\npublic interface HotWordServi",
"end": 188,
"score": 0.9996816515922546,
"start": 183,
"tag": "USERNAME",
"value": "liuxh"
}
] | null | [] | package com.wfj.search.online.management.console.service;
import com.wfj.search.online.common.pojo.HotWordPojo;
import java.util.List;
/**
* <br/>create at 15-12-15
*
* @author liuxh
* @since 1.0.0
*/
public interface HotWordService {
/**
* 分页展示热词列表
*
* @param start 开始
* @param limit 条数
* @return 热词列表
*/
List<HotWordPojo> list(String site, String channel, int start, int limit);
/**
* 热词总数
*
* @return 热词总数
*/
int count(String site, String channel);
/**
* 根据热词id获取热词数据
*
* @param hotWordId 热词id
* @return 热词数据
*/
HotWordPojo get(String hotWordId);
/**
* 添加热词
*
* @param pojo 热词实体
* @param modifier 修改人
* @return 状态,-1数据错误
*/
int add(HotWordPojo pojo, String modifier);
/**
* 修改热词
*
* @param pojo 热词实体
* @param modifier 修改人
* @return 状态,-1数据错误,-2不存在数据,-3存在数据为有效数据
*/
int mod(HotWordPojo pojo, String modifier);
/**
* 删除热词数据
*
* @param sid 热词编号
* @param modifier 修改人
* @return 状态,-1数据错误,-2不存在数据,-3存在数据为有效数据
*/
int del(String sid, String modifier);
/**
* 使热词生效
*
* @param sid 热词编号
* @param modifier 修改人
* @return 状态,-1数据错误,-2不存在数据
*/
int enabled(String sid, String modifier);
/**
* 使热词失效
*
* @param sid 热词编号
* @param modifier 修改人
* @return 状态,-1数据错误,-2不存在数据
*/
int disabled(String sid, String modifier);
}
| 1,888 | 0.542428 | 0.529373 | 82 | 17.682926 | 16.238226 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.243902 | false | false | 3 |
9aee9672585ac450836ea5206c8d485f8c3c39ac | 7,730,941,183,599 | 5d75cf39da084d67eb1f8a7e2d3095c376455008 | /other/src/com/joymeng/slg/union/task/AlliDailyTask.java | 0bdecd4a29aba8695ead6485053d101691f66b83 | [] | no_license | keyking-coin/code | https://github.com/keyking-coin/code | 1413a32a9901725228004cd971f6efac4a4e5121 | bdba6b9d8a7bb8a4ac682d7ff5f12d3e37c27bdb | refs/heads/master | 2020-04-04T05:46:34.108000 | 2016-09-30T07:09:46 | 2016-09-30T07:09:46 | 52,215,473 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.joymeng.slg.union.task;
import com.joymeng.common.util.TimeUtils;
public class AlliDailyTask extends AlliTask {
//进度
int schedule;
//开启时间
long openTime;
//完成持续时间
long continued = 0;
@Override
protected int updateProgress(int count) {
if(count > 0)
schedule += count;
return schedule;
}
@Override
protected boolean isOpen() {
return TimeUtils.nowLong() >= openTime;
}
@Override
protected boolean isRefresh() {
//日常任务每天刷新
return false;
}
@Override
protected boolean isFinish() {
return TimeUtils.nowLong() >= openTime + continued;
}
}
| UTF-8 | Java | 626 | java | AlliDailyTask.java | Java | [] | null | [] | package com.joymeng.slg.union.task;
import com.joymeng.common.util.TimeUtils;
public class AlliDailyTask extends AlliTask {
//进度
int schedule;
//开启时间
long openTime;
//完成持续时间
long continued = 0;
@Override
protected int updateProgress(int count) {
if(count > 0)
schedule += count;
return schedule;
}
@Override
protected boolean isOpen() {
return TimeUtils.nowLong() >= openTime;
}
@Override
protected boolean isRefresh() {
//日常任务每天刷新
return false;
}
@Override
protected boolean isFinish() {
return TimeUtils.nowLong() >= openTime + continued;
}
}
| 626 | 0.703072 | 0.699659 | 36 | 15.277778 | 15.239953 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.222222 | false | false | 3 |
82350bfa26a632d4803cd414e015aa5abd9b63b6 | 8,108,898,296,088 | fc5193b59b7453fca18a403adac03ac0c2104b91 | /src/main/java/jtm/tasks/fundamentals/DiceHistogram.java | fa0ca5609b25a22b175065a26e2a05b6c8edf3db | [] | no_license | ibelecka/java2020 | https://github.com/ibelecka/java2020 | b6086d33e4e9e005d889eeb6de9ea3aa4a5466d8 | f97ab6517b24ea41564211fc243c20409cf0ffb7 | refs/heads/master | 2022-01-19T20:14:29.469000 | 2020-02-26T10:57:59 | 2020-02-26T10:57:59 | 234,135,878 | 0 | 0 | null | false | 2022-01-07T00:20:46 | 2020-01-15T17:32:56 | 2020-02-26T10:58:02 | 2022-01-07T00:20:45 | 3,748 | 0 | 0 | 3 | Java | false | false | package jtm.tasks.fundamentals;
public class DiceHistogram {
/*
* TODO A 6-sided die is rolled a number of times and the results are plotted as
* a character-based histogram.
*
* You will be passed the dice value frequencies, and your task is to write the
* code to return a string representing a histogram, so that when it is printed
* it has the same format as the example.
*
*
* There are no trailing spaces on the lines All lines (including the last) end
* with a newline \n A count is displayed beside each bar except where the count
* is 0 The number of rolls may vary but there are never more than 100
*
* Example: [7,3,10,1,0,5] =>
*
* 6|##### 5 5| 4|# 1 3|########## 10 2|### 3 1|####### 7
*/
public static String histogram(final int results[]) {
String histogram = "";
for (int i = results.length - 1; i >= 0; i--) {
histogram += "" + (i + 1) + "|";
for (int j = 1; j <= results[i]; j++) {
histogram += "#";
}
if (results[i] != 0) {
histogram += " " + results[i];
}
histogram += "\n";
}
return histogram;
}
}
| UTF-8 | Java | 1,096 | java | DiceHistogram.java | Java | [] | null | [] | package jtm.tasks.fundamentals;
public class DiceHistogram {
/*
* TODO A 6-sided die is rolled a number of times and the results are plotted as
* a character-based histogram.
*
* You will be passed the dice value frequencies, and your task is to write the
* code to return a string representing a histogram, so that when it is printed
* it has the same format as the example.
*
*
* There are no trailing spaces on the lines All lines (including the last) end
* with a newline \n A count is displayed beside each bar except where the count
* is 0 The number of rolls may vary but there are never more than 100
*
* Example: [7,3,10,1,0,5] =>
*
* 6|##### 5 5| 4|# 1 3|########## 10 2|### 3 1|####### 7
*/
public static String histogram(final int results[]) {
String histogram = "";
for (int i = results.length - 1; i >= 0; i--) {
histogram += "" + (i + 1) + "|";
for (int j = 1; j <= results[i]; j++) {
histogram += "#";
}
if (results[i] != 0) {
histogram += " " + results[i];
}
histogram += "\n";
}
return histogram;
}
}
| 1,096 | 0.604927 | 0.578467 | 37 | 28.621622 | 27.463343 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.108108 | false | false | 3 |
2724fa23502bf994ed6cafb11bfb54d21323ba0b | 27,625,229,661,281 | 04b460198f5fbf3368443c2105f979421b630aa2 | /domino-ui/src/main/java/org/dominokit/domino/ui/Typography/Strong.java | 9f497117e6f56e3f86e0e73c21cc0c7bdcade523 | [
"Apache-2.0"
] | permissive | RaulPampliegaMayoral/domino-ui | https://github.com/RaulPampliegaMayoral/domino-ui | 7a357b8847bf15421c5b388db15b73f744fad0b0 | 4a67b72a6448537310fe63ec4df6ce31be5ff03f | refs/heads/master | 2021-07-16T13:02:00.806000 | 2020-10-17T15:12:15 | 2020-10-17T15:12:15 | 171,243,344 | 0 | 0 | Apache-2.0 | true | 2019-07-03T09:35:54 | 2019-02-18T08:24:17 | 2019-02-18T08:24:20 | 2019-07-03T09:35:54 | 26,657 | 0 | 0 | 0 | Java | false | false | package org.dominokit.domino.ui.Typography;
import elemental2.dom.HTMLElement;
import org.dominokit.domino.ui.utils.BaseDominoElement;
import static org.jboss.elemento.Elements.strong;
public class Strong extends BaseDominoElement<HTMLElement, Strong> {
private HTMLElement element = strong().element();
public Strong(String text){
element.textContent = text;
init(this);
}
public static Strong of(String text){
return new Strong(text);
}
@Override
public HTMLElement element() {
return element;
}
}
| UTF-8 | Java | 571 | java | Strong.java | Java | [] | null | [] | package org.dominokit.domino.ui.Typography;
import elemental2.dom.HTMLElement;
import org.dominokit.domino.ui.utils.BaseDominoElement;
import static org.jboss.elemento.Elements.strong;
public class Strong extends BaseDominoElement<HTMLElement, Strong> {
private HTMLElement element = strong().element();
public Strong(String text){
element.textContent = text;
init(this);
}
public static Strong of(String text){
return new Strong(text);
}
@Override
public HTMLElement element() {
return element;
}
}
| 571 | 0.698774 | 0.697023 | 25 | 21.84 | 21.091572 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 3 |
c04be3902157dc32d028862ad2235599b9b54296 | 18,090,402,321,301 | 4ad676ceede02a1f5b89623db3cba1a79755c77b | /RemoveCharacters.java | 0b2857bb694fb66dd0b49662b8a739f9ff504350 | [] | no_license | timstoddard/Code-Eval-Solutions | https://github.com/timstoddard/Code-Eval-Solutions | d320f7d5d4ba1ecac058172b7ee114c6122aef96 | dd975c6d0adf26106aa9fd90b7759d0cc0cea5be | refs/heads/master | 2021-01-10T02:37:30.778000 | 2016-01-10T00:46:54 | 2016-01-10T00:46:54 | 49,347,753 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.io.*;
public class RemoveCharacters {
public static void main (String[] args) throws IOException {
File file = new File(/*args[0]*/"/Users/timstoddard/Dropbox/school/homestead/Comp Sci Ap/ava/workspace/CodeEval/RemoveCharacters.txt");
BufferedReader buffer = new BufferedReader(new FileReader(file));
String line;
while ((line = buffer.readLine()) != null) {
line = line.trim();
String[] s = line.split(",");
char[] c = s[1].trim().toCharArray();
String scrubbed = "";
for (int i = 0; i < s[0].length(); i++) {
for (int j = 0; j < c.length; j++) {
if (s[0].charAt(i) == c[j]) {break;}
else if (j == c.length - 1) {scrubbed += s[0].charAt(i); break;}
}
}
System.out.println(scrubbed);
}
buffer.close();
}
} | UTF-8 | Java | 911 | java | RemoveCharacters.java | Java | [
{
"context": "{\n File file = new File(/*args[0]*/\"/Users/timstoddard/Dropbox/school/homestead/Comp Sci Ap/ava/workspac",
"end": 174,
"score": 0.9995071291923523,
"start": 163,
"tag": "USERNAME",
"value": "timstoddard"
}
] | null | [] | import java.io.*;
public class RemoveCharacters {
public static void main (String[] args) throws IOException {
File file = new File(/*args[0]*/"/Users/timstoddard/Dropbox/school/homestead/Comp Sci Ap/ava/workspace/CodeEval/RemoveCharacters.txt");
BufferedReader buffer = new BufferedReader(new FileReader(file));
String line;
while ((line = buffer.readLine()) != null) {
line = line.trim();
String[] s = line.split(",");
char[] c = s[1].trim().toCharArray();
String scrubbed = "";
for (int i = 0; i < s[0].length(); i++) {
for (int j = 0; j < c.length; j++) {
if (s[0].charAt(i) == c[j]) {break;}
else if (j == c.length - 1) {scrubbed += s[0].charAt(i); break;}
}
}
System.out.println(scrubbed);
}
buffer.close();
}
} | 911 | 0.518112 | 0.50933 | 22 | 40.454544 | 30.771484 | 143 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.090909 | false | false | 3 |
2630622b6e3313c25f04b97c88d03fb5cbd90357 | 11,974,368,835,881 | 1aba10a7db729854194eb02ab59b23273e47259f | /calimocho-tab/src/test/java/org/hupo/psi/calimocho/tab/io/DefaultRowReaderTest.java | b72ddca4d942895d6f92bf8d19c8dc151920e836 | [
"CC-BY-4.0"
] | permissive | MICommunity/psimi | https://github.com/MICommunity/psimi | 442b8ca2adac0e2cfb589ca983a898050ec59742 | 9baca51cd699a69b3a61533093919ccd614b42b4 | refs/heads/master | 2023-04-08T04:42:09.071000 | 2018-08-22T15:38:10 | 2018-08-22T15:38:10 | 34,381,736 | 6 | 4 | CC-BY-4.0 | false | 2023-03-15T12:20:58 | 2015-04-22T09:35:33 | 2023-01-11T17:08:55 | 2023-03-15T12:20:57 | 333,620 | 4 | 3 | 15 | Java | false | false | package org.hupo.psi.calimocho.tab.io;
import junit.framework.Assert;
import org.hupo.psi.calimocho.io.IllegalFieldException;
import org.hupo.psi.calimocho.io.IllegalRowException;
import org.hupo.psi.calimocho.key.CalimochoKeys;
import org.hupo.psi.calimocho.tab.AbstractCalimochoTabTest;
import org.hupo.psi.calimocho.model.*;
import org.hupo.psi.calimocho.tab.io.formatter.KeyValueFieldFormatter;
import org.hupo.psi.calimocho.tab.io.formatter.LiteralFieldFormatter;
import org.hupo.psi.calimocho.tab.io.formatter.XrefFieldFormatter;
import org.hupo.psi.calimocho.tab.io.parser.KeyValueFieldParser;
import org.hupo.psi.calimocho.tab.io.parser.LiteralFieldParser;
import org.hupo.psi.calimocho.tab.io.parser.XrefFieldParser;
import org.hupo.psi.calimocho.tab.model.ColumnBasedDocumentDefinition;
import org.hupo.psi.calimocho.tab.model.ColumnBasedDocumentDefinitionBuilder;
import org.hupo.psi.calimocho.tab.model.ColumnDefinition;
import org.hupo.psi.calimocho.tab.model.ColumnDefinitionBuilder;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Collection;
import java.util.List;
/**
* @author Bruno Aranda (baranda@ebi.ac.uk)
* @version $Id$
* @since 1.0
*/
public class DefaultRowReaderTest extends AbstractCalimochoTabTest {
private static String mitab26Line;
private static String mitab27Line;
private static String mitab28Line;
@BeforeClass
public static void setUp() {
mitab26Line = "uniprotkb:Q9Y5J7|intact:EBI-123456\tuniprotkb:Q9Y584\tuniprotkb:TIMM9(gene name)\tuniprotkb:TIMM22(gene name)\t" +
"uniprotkb:TIM9\tuniprotkb:TEX4\t" +
"psi-mi:\"MI:0006\"(anti bait coip)\tPeter et al (2010)\tpubmed:14726512\ttaxid:9606(human)\ttaxid:9606(human)\t" +
"psi-mi:\"MI:0218\"(physical interaction)\tpsi-mi:\"MI:0469\"(intact)\tintact:EBI-1200556\t-\t" +
"psi-mi:\"MI:xxxx\"(spoke)\tpsi-mi:\"MI:0499\"(unspecified role)\tpsi-mi:\"MI:0499\"(unspecified role)\t" +
"psi-mi:\"MI:0497\"(bait)\tpsi-mi:\"MI:0498\"(prey)\tpsi-mi:\"MI:0326\"(protein)\tpsi-mi:\"MI:0326\"(protein)\t" +
"interpro:IPR004046(GST_C)\t" +
"go:\"GO:0004709\"(\"F:MAP kinase kinase kinase act\")\tgo:\"GO:xxxxx\"\t" +
"caution:AnnotA\tcaution:AnnotB\tdataset:Test\ttaxid:9606(human-293t)\tkd:2\t2009/03/09\t2010/03/30\t" +
"seguid:checksumA\tseguid:checksumB\tseguid:checksumI\tfalse";
mitab27Line = mitab26Line + "\ttag:?-?\t-\t-\t-\tpsi-mi:\"MI:0102\"(sequence tag identification)\tpsi-mi:\"MI:0102\"(sequence tag identification)";
mitab28Line = mitab27Line + "\t-\t-\tpsi-mi:\"MI:2247\"(transcriptional regulation)\tpsi-mi:\"MI:2236\"(up-regulates activity)";
}
@Test
public void readMitab26Line() throws Exception {
ColumnDefinition idColDefinition = new ColumnDefinitionBuilder()
.setKey( "idA" )
.setPosition( 0 )
.setFieldSeparator( "|" )
.setFieldParser( new KeyValueFieldParser( ":" ) )
.setFieldFormatter( new KeyValueFieldFormatter( ":" ) )
.build();
ColumnDefinition authColDefinition = new ColumnDefinitionBuilder()
.extendColumnDefinition( idColDefinition )
.setKey( "pubauth" )
.setPosition( 7 )
.setFieldParser( new LiteralFieldParser() )
.setFieldFormatter( new LiteralFieldFormatter() )
.build();
ColumnBasedDocumentDefinition docDefinition = new ColumnBasedDocumentDefinitionBuilder()
.addColumnDefinition( idColDefinition )
.addColumnDefinition( authColDefinition )
.setColumnSeparator( "\t" )
.setCommentPrefix( "#" )
.build();
RowReader rowReader = new DefaultRowReader( docDefinition );
Row row = rowReader.readLine(mitab26Line);
Assert.assertNotNull( row );
Collection<Field> idFields = row.getFields( idColDefinition.getKey() );
Assert.assertEquals( 2, idFields.size() );
for (Field idField : idFields) {
final String db = idField.get( CalimochoKeys.KEY );
final String value = idField.get( CalimochoKeys.VALUE );
if ("intact".equals(db)) {
Assert.assertEquals("intact", db);
Assert.assertEquals( "EBI-123456", value );
} else {
Assert.assertEquals("uniprotkb", db);
Assert.assertEquals( "Q9Y5J7", value );
}
}
Collection<Field> authorFields = row.getFields( authColDefinition.getKey() );
Assert.assertEquals( 1, authorFields.size() );
Field authField = authorFields.iterator().next();
Assert.assertEquals( "Peter et al (2010)", authField.get( CalimochoKeys.VALUE ) );
}
@Test
public void readMitab27Line() throws Exception {
XrefFieldParser xrefParser = new XrefFieldParser();
XrefFieldFormatter xrefFormatter = new XrefFieldFormatter();
ColumnDefinition featuresInteractorADefinition = new ColumnDefinitionBuilder()
.setKey( "ftypeA" )
.setPosition( 36 )
.setFieldSeparator("|")
.setEmptyValue("-")
.setFieldDelimiter("")
.setIsAllowsEmpty(true)
.setFieldFormatter(xrefFormatter)
.setFieldParser(xrefParser)
.build();
ColumnDefinition partDetectionMethodADefinition = new ColumnDefinitionBuilder()
.extendColumnDefinition( featuresInteractorADefinition )
.setKey( "pmethodA" )
.setPosition( 40 )
.build();
ColumnBasedDocumentDefinition docDefinition = new ColumnBasedDocumentDefinitionBuilder()
.addColumnDefinition( featuresInteractorADefinition )
.addColumnDefinition( partDetectionMethodADefinition )
.setColumnSeparator( "\t" )
.setCommentPrefix( "#" )
.build();
RowReader rowReader = new DefaultRowReader( docDefinition );
Row row = rowReader.readLine(mitab27Line);
Assert.assertNotNull( row );
Collection<Field> fTypeAFields = row.getFields( featuresInteractorADefinition.getKey() );
Assert.assertEquals( 1, fTypeAFields.size() );
Field fTypeAField = fTypeAFields.iterator().next();
final String fTypeA_key = fTypeAField.get( CalimochoKeys.KEY );
final String fTypeA_value = fTypeAField.get( CalimochoKeys.VALUE );
Assert.assertEquals("tag", fTypeA_key);
Assert.assertEquals("?-?", fTypeA_value);
Collection<Field> partDetMethodAFields = row.getFields( partDetectionMethodADefinition.getKey() );
Assert.assertEquals(1, partDetMethodAFields.size());
Field partDetMethodAField = partDetMethodAFields.iterator().next();
final String partDetMethodA_key = partDetMethodAField.get( CalimochoKeys.KEY );
final String partDetMethodA_value = partDetMethodAField.get( CalimochoKeys.VALUE );
final String partDetMethodA_text = partDetMethodAField.get( CalimochoKeys.TEXT );
Assert.assertEquals("psi-mi", partDetMethodA_key);
Assert.assertEquals("MI:0102", partDetMethodA_value);
Assert.assertEquals("sequence tag identification", partDetMethodA_text);
}
@Test
public void readMitab28Line() throws Exception {
XrefFieldParser xrefParser = new XrefFieldParser();
XrefFieldFormatter xrefFormatter = new XrefFieldFormatter();
ColumnDefinition biologicalEffectADefinition = new ColumnDefinitionBuilder()
.setKey( "bioEffectA" )
.setPosition( 42 )
.setFieldSeparator("|")
.setEmptyValue("-")
.setFieldDelimiter("")
.setIsAllowsEmpty(true)
.setFieldFormatter(xrefFormatter)
.setFieldParser(xrefParser)
.build();
ColumnDefinition causalRegMechanismDefinition = new ColumnDefinitionBuilder()
.extendColumnDefinition( biologicalEffectADefinition )
.setKey( "causalmechanism" )
.setPosition( 44 )
.build();
ColumnBasedDocumentDefinition docDefinition = new ColumnBasedDocumentDefinitionBuilder()
.addColumnDefinition( biologicalEffectADefinition )
.addColumnDefinition( causalRegMechanismDefinition )
.setColumnSeparator( "\t" )
.setCommentPrefix( "#" )
.build();
RowReader rowReader = new DefaultRowReader( docDefinition );
Row row = rowReader.readLine(mitab28Line);
Assert.assertNotNull( row );
Collection<Field> bioEffectAFields = row.getFields( biologicalEffectADefinition.getKey() );
Assert.assertEquals( 0, bioEffectAFields.size() );
Collection<Field> causalRegMechanismFields = row.getFields( causalRegMechanismDefinition.getKey() );
Assert.assertEquals(1, causalRegMechanismFields.size());
Field causalRegMechanismField = causalRegMechanismFields.iterator().next();
final String key = causalRegMechanismField.get( CalimochoKeys.KEY );
final String value = causalRegMechanismField.get( CalimochoKeys.VALUE );
final String text = causalRegMechanismField.get( CalimochoKeys.TEXT );
Assert.assertEquals("psi-mi", key);
Assert.assertEquals("MI:2247", value);
Assert.assertEquals("transcriptional regulation", text);
}
@Test
public void readMitab26Stream() throws Exception {
InputStream is = DefaultRowReaderTest.class.getResourceAsStream( "/META-INF/mitab26/14726512.txt" );
ColumnDefinition columnDefinition = new ColumnDefinitionBuilder()
.setKey( "id" )
.setPosition( 0 )
.setFieldSeparator( "|" )
.setFieldParser( new KeyValueFieldParser( ":" ) )
.setFieldFormatter( new KeyValueFieldFormatter( ":" ) )
.build();
ColumnBasedDocumentDefinition docDefinition = new ColumnBasedDocumentDefinitionBuilder()
.addColumnDefinition( columnDefinition )
.setColumnSeparator( "\t" )
.setCommentPrefix( "#" )
.build();
RowReader reader = new DefaultRowReader(docDefinition);
List<Row> rows = reader.read(is);
Assert.assertEquals( 1, rows.size() );
Row row = rows.get( 0 );
Collection<Field> fields = row.getFields( columnDefinition.getKey() );
Assert.assertEquals( 1, fields.size() );
Field field = fields.iterator().next();
final String key = field.get( CalimochoKeys.KEY );
final String value = field.get( CalimochoKeys.VALUE );
final String text = field.get( CalimochoKeys.TEXT );
Assert.assertEquals("uniprotkb", key);
Assert.assertEquals("Q9Y5J7", value);
Assert.assertNull( text );
}
@Test
public void readMitab27Stream() throws Exception {
InputStream is = DefaultRowReaderTest.class.getResourceAsStream( "/META-INF/mitab27/mitab27_example.txt" );
XrefFieldParser xrefParser = new XrefFieldParser();
XrefFieldFormatter xrefFormatter = new XrefFieldFormatter();
ColumnDefinition hostOrganismDefinition = new ColumnDefinitionBuilder()
.setKey("taxidHost")
.setFieldSeparator("|")
.setEmptyValue("-")
.setFieldDelimiter("")
.setIsAllowsEmpty(true)
.setPosition(28)
.setFieldFormatter(xrefFormatter)
.setFieldParser(xrefParser)
.build();
ColumnDefinition partDetectionMethodBDefinition = new ColumnDefinitionBuilder()
.extendColumnDefinition(hostOrganismDefinition)
.setKey("pmethodB")
.setPosition(41)
.build();
ColumnBasedDocumentDefinition docDefinition = new ColumnBasedDocumentDefinitionBuilder()
.addColumnDefinition(hostOrganismDefinition)
.addColumnDefinition(partDetectionMethodBDefinition)
.setColumnSeparator( "\t" )
.setCommentPrefix( "#" )
.build();
RowReader reader = new DefaultRowReader(docDefinition);
List<Row> rows = reader.read(is);
Assert.assertEquals( 1, rows.size() );
Row row = rows.get( 0 );
Collection<Field> hostOrganismFields = row.getFields( hostOrganismDefinition.getKey() );
Assert.assertEquals( 2, hostOrganismFields.size() );
for (Field hostOrganismField : hostOrganismFields) {
final String key = hostOrganismField.get( CalimochoKeys.KEY );
final String value = hostOrganismField.get( CalimochoKeys.VALUE );
final String text = hostOrganismField.get( CalimochoKeys.TEXT );
Assert.assertEquals("taxid", key);
Assert.assertEquals("7227", value);
Assert.assertTrue(text.equalsIgnoreCase("drome-embryo") || text.equalsIgnoreCase("drosophilla melanogaster embryo"));
}
Collection<Field> pmethodBFields = row.getFields( partDetectionMethodBDefinition.getKey() );
Assert.assertEquals( 1, pmethodBFields.size() );
Field pmethodBField = pmethodBFields.iterator().next();
final String key = pmethodBField.get( CalimochoKeys.KEY );
final String value = pmethodBField.get( CalimochoKeys.VALUE );
final String text = pmethodBField.get( CalimochoKeys.TEXT );
Assert.assertEquals("psi-mi", key);
Assert.assertEquals("MI:0102", value);
Assert.assertEquals("sequence tag identification", text);
}
@Test
public void readMitab28Stream() throws Exception {
InputStream is = DefaultRowReaderTest.class.getResourceAsStream( "/META-INF/mitab28/mitab28_example.txt" );
XrefFieldParser xrefParser = new XrefFieldParser();
XrefFieldFormatter xrefFormatter = new XrefFieldFormatter();
ColumnDefinition biologicalEffectBDefinition = new ColumnDefinitionBuilder()
.setKey( "bioEffectB" )
.setPosition( 43 )
.setFieldSeparator("|")
.setEmptyValue("-")
.setFieldDelimiter("")
.setIsAllowsEmpty(true)
.setFieldFormatter(xrefFormatter)
.setFieldParser(xrefParser)
.build();
ColumnDefinition causalStatementDefinition = new ColumnDefinitionBuilder()
.extendColumnDefinition( biologicalEffectBDefinition)
.setKey( "causalstatement" )
.setPosition( 45 )
.build();
ColumnBasedDocumentDefinition docDefinition = new ColumnBasedDocumentDefinitionBuilder()
.addColumnDefinition(biologicalEffectBDefinition)
.addColumnDefinition(causalStatementDefinition)
.setColumnSeparator( "\t" )
.setCommentPrefix( "#" )
.build();
RowReader reader = new DefaultRowReader(docDefinition);
List<Row> rows = reader.read(is);
Assert.assertEquals( 1, rows.size() );
Row row = rows.get( 0 );
Collection<Field> bioEffectBFields = row.getFields( biologicalEffectBDefinition.getKey() );
Assert.assertEquals(1, bioEffectBFields.size());
Field bioEffectBField = bioEffectBFields.iterator().next();
final String bioEffectBField_key = bioEffectBField.get( CalimochoKeys.KEY );
final String bioEffectBField_value = bioEffectBField.get( CalimochoKeys.VALUE );
final String bioEffectBField_text = bioEffectBField.get( CalimochoKeys.TEXT );
Assert.assertEquals("go", bioEffectBField_key);
Assert.assertEquals("GO:0016301", bioEffectBField_value);
Assert.assertEquals("kinase activity", bioEffectBField_text);
Collection<Field> causalStatementFields = row.getFields( causalStatementDefinition.getKey() );
Assert.assertEquals(1, causalStatementFields.size());
Field causalStatementField = causalStatementFields.iterator().next();
final String causalStatementField_key = causalStatementField.get( CalimochoKeys.KEY );
final String causalStatementField_value = causalStatementField.get( CalimochoKeys.VALUE );
final String causalStatementField_text = causalStatementField.get( CalimochoKeys.TEXT );
Assert.assertEquals("psi-mi", causalStatementField_key);
Assert.assertEquals("MI:2240", causalStatementField_value);
Assert.assertEquals("down regulates", causalStatementField_text);
}
@Test()
@Ignore
// we don't want this test anymore. If the number of columns is bigger/lower that the one expected in column definitions, we just ignore the supplementary columns.
// this would help with parsing MITAB 2.5 files using 2.7 parser and 2.7 files using 2.5 parser
public void invalidInputFile_columnCount() throws Exception {
ColumnBasedDocumentDefinition dd = new ColumnBasedDocumentDefinitionBuilder().addColumnDefinition( new ColumnDefinitionBuilder()
.setKey( "gene" )
.setPosition( 1 )
.setEmptyValue( "" )
.setIsAllowsEmpty( false )
.setFieldSeparator( "," )
.setFieldDelimiter( "" )
.setFieldParser( new LiteralFieldParser() )
.setFieldFormatter( new LiteralFieldFormatter() )
.build() )
.addColumnDefinition( new ColumnDefinitionBuilder()
.setKey( "taxid" )
.setPosition( 2 )
.setEmptyValue( "" )
.setIsAllowsEmpty( false )
.setFieldSeparator( "," )
.setFieldDelimiter( "" )
.setFieldParser( new LiteralFieldParser() )
.setFieldFormatter( new LiteralFieldFormatter() )
.build() )
.setColumnSeparator( "|" )
.build();
String aLine = "LSM7|9606";
RowReader reader = new DefaultRowReader( dd );
try {
reader.readLine( aLine );
Assert.fail("Expected IllegalRowException to be thrown");
} catch ( IllegalRowException e ) {
// expected here !
Assert.assertEquals( aLine, e.getLine() );
} catch ( IllegalColumnException e ) {
Assert.fail();
} catch ( IllegalFieldException e ) {
Assert.fail();
}
}
@Test
public void read_fieldKeyValue() throws Exception {
final String aLine = "LSM7|9606\n";
final ColumnBasedDocumentDefinition documentDefinition = buildGeneListDefinition();
RowReader reader = new DefaultRowReader( documentDefinition );
final List<Row> rows = reader.read( new ByteArrayInputStream( aLine.getBytes() ) );
org.junit.Assert.assertNotNull( rows );
org.junit.Assert.assertEquals( 1, rows.size() );
Row row = rows.get( 0 );
final Collection<Field> geneFields = row.getFields( "gene" );
Assert.assertNotNull( geneFields );
Assert.assertEquals(1, geneFields.size());
final Field geneField = geneFields.iterator().next();
final String gene = geneField.get( CalimochoKeys.VALUE );
Assert.assertNotNull( gene );
Assert.assertEquals("LSM7", gene);
final Collection<Field> taxidFields = row.getFields( "taxid" );
Assert.assertNotNull( taxidFields );
Assert.assertEquals(1, taxidFields.size());
final Field taxidField = taxidFields.iterator().next();
final String taxid = taxidField.get( CalimochoKeys.VALUE );
Assert.assertNotNull( taxid );
Assert.assertEquals("9606", taxid);
}
}
| UTF-8 | Java | 21,276 | java | DefaultRowReaderTest.java | Java | [
{
"context": "ection;\r\nimport java.util.List;\r\n\r\n/**\r\n * @author Bruno Aranda (baranda@ebi.ac.uk)\r\n * @version $Id$\r\n * @since ",
"end": 1251,
"score": 0.9998844265937805,
"start": 1239,
"tag": "NAME",
"value": "Bruno Aranda"
},
{
"context": " java.util.List;\r\n\r\n/**\r... | null | [] | package org.hupo.psi.calimocho.tab.io;
import junit.framework.Assert;
import org.hupo.psi.calimocho.io.IllegalFieldException;
import org.hupo.psi.calimocho.io.IllegalRowException;
import org.hupo.psi.calimocho.key.CalimochoKeys;
import org.hupo.psi.calimocho.tab.AbstractCalimochoTabTest;
import org.hupo.psi.calimocho.model.*;
import org.hupo.psi.calimocho.tab.io.formatter.KeyValueFieldFormatter;
import org.hupo.psi.calimocho.tab.io.formatter.LiteralFieldFormatter;
import org.hupo.psi.calimocho.tab.io.formatter.XrefFieldFormatter;
import org.hupo.psi.calimocho.tab.io.parser.KeyValueFieldParser;
import org.hupo.psi.calimocho.tab.io.parser.LiteralFieldParser;
import org.hupo.psi.calimocho.tab.io.parser.XrefFieldParser;
import org.hupo.psi.calimocho.tab.model.ColumnBasedDocumentDefinition;
import org.hupo.psi.calimocho.tab.model.ColumnBasedDocumentDefinitionBuilder;
import org.hupo.psi.calimocho.tab.model.ColumnDefinition;
import org.hupo.psi.calimocho.tab.model.ColumnDefinitionBuilder;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Collection;
import java.util.List;
/**
* @author <NAME> (<EMAIL>)
* @version $Id$
* @since 1.0
*/
public class DefaultRowReaderTest extends AbstractCalimochoTabTest {
private static String mitab26Line;
private static String mitab27Line;
private static String mitab28Line;
@BeforeClass
public static void setUp() {
mitab26Line = "uniprotkb:Q9Y5J7|intact:EBI-123456\tuniprotkb:Q9Y584\tuniprotkb:TIMM9(gene name)\tuniprotkb:TIMM22(gene name)\t" +
"uniprotkb:TIM9\tuniprotkb:TEX4\t" +
"psi-mi:\"MI:0006\"(anti bait coip)\tPeter et al (2010)\tpubmed:14726512\ttaxid:9606(human)\ttaxid:9606(human)\t" +
"psi-mi:\"MI:0218\"(physical interaction)\tpsi-mi:\"MI:0469\"(intact)\tintact:EBI-1200556\t-\t" +
"psi-mi:\"MI:xxxx\"(spoke)\tpsi-mi:\"MI:0499\"(unspecified role)\tpsi-mi:\"MI:0499\"(unspecified role)\t" +
"psi-mi:\"MI:0497\"(bait)\tpsi-mi:\"MI:0498\"(prey)\tpsi-mi:\"MI:0326\"(protein)\tpsi-mi:\"MI:0326\"(protein)\t" +
"interpro:IPR004046(GST_C)\t" +
"go:\"GO:0004709\"(\"F:MAP kinase kinase kinase act\")\tgo:\"GO:xxxxx\"\t" +
"caution:AnnotA\tcaution:AnnotB\tdataset:Test\ttaxid:9606(human-293t)\tkd:2\t2009/03/09\t2010/03/30\t" +
"seguid:checksumA\tseguid:checksumB\tseguid:checksumI\tfalse";
mitab27Line = mitab26Line + "\ttag:?-?\t-\t-\t-\tpsi-mi:\"MI:0102\"(sequence tag identification)\tpsi-mi:\"MI:0102\"(sequence tag identification)";
mitab28Line = mitab27Line + "\t-\t-\tpsi-mi:\"MI:2247\"(transcriptional regulation)\tpsi-mi:\"MI:2236\"(up-regulates activity)";
}
@Test
public void readMitab26Line() throws Exception {
ColumnDefinition idColDefinition = new ColumnDefinitionBuilder()
.setKey( "idA" )
.setPosition( 0 )
.setFieldSeparator( "|" )
.setFieldParser( new KeyValueFieldParser( ":" ) )
.setFieldFormatter( new KeyValueFieldFormatter( ":" ) )
.build();
ColumnDefinition authColDefinition = new ColumnDefinitionBuilder()
.extendColumnDefinition( idColDefinition )
.setKey( "pubauth" )
.setPosition( 7 )
.setFieldParser( new LiteralFieldParser() )
.setFieldFormatter( new LiteralFieldFormatter() )
.build();
ColumnBasedDocumentDefinition docDefinition = new ColumnBasedDocumentDefinitionBuilder()
.addColumnDefinition( idColDefinition )
.addColumnDefinition( authColDefinition )
.setColumnSeparator( "\t" )
.setCommentPrefix( "#" )
.build();
RowReader rowReader = new DefaultRowReader( docDefinition );
Row row = rowReader.readLine(mitab26Line);
Assert.assertNotNull( row );
Collection<Field> idFields = row.getFields( idColDefinition.getKey() );
Assert.assertEquals( 2, idFields.size() );
for (Field idField : idFields) {
final String db = idField.get( CalimochoKeys.KEY );
final String value = idField.get( CalimochoKeys.VALUE );
if ("intact".equals(db)) {
Assert.assertEquals("intact", db);
Assert.assertEquals( "EBI-123456", value );
} else {
Assert.assertEquals("uniprotkb", db);
Assert.assertEquals( "Q9Y5J7", value );
}
}
Collection<Field> authorFields = row.getFields( authColDefinition.getKey() );
Assert.assertEquals( 1, authorFields.size() );
Field authField = authorFields.iterator().next();
Assert.assertEquals( "Peter et al (2010)", authField.get( CalimochoKeys.VALUE ) );
}
@Test
public void readMitab27Line() throws Exception {
XrefFieldParser xrefParser = new XrefFieldParser();
XrefFieldFormatter xrefFormatter = new XrefFieldFormatter();
ColumnDefinition featuresInteractorADefinition = new ColumnDefinitionBuilder()
.setKey( "ftypeA" )
.setPosition( 36 )
.setFieldSeparator("|")
.setEmptyValue("-")
.setFieldDelimiter("")
.setIsAllowsEmpty(true)
.setFieldFormatter(xrefFormatter)
.setFieldParser(xrefParser)
.build();
ColumnDefinition partDetectionMethodADefinition = new ColumnDefinitionBuilder()
.extendColumnDefinition( featuresInteractorADefinition )
.setKey( "pmethodA" )
.setPosition( 40 )
.build();
ColumnBasedDocumentDefinition docDefinition = new ColumnBasedDocumentDefinitionBuilder()
.addColumnDefinition( featuresInteractorADefinition )
.addColumnDefinition( partDetectionMethodADefinition )
.setColumnSeparator( "\t" )
.setCommentPrefix( "#" )
.build();
RowReader rowReader = new DefaultRowReader( docDefinition );
Row row = rowReader.readLine(mitab27Line);
Assert.assertNotNull( row );
Collection<Field> fTypeAFields = row.getFields( featuresInteractorADefinition.getKey() );
Assert.assertEquals( 1, fTypeAFields.size() );
Field fTypeAField = fTypeAFields.iterator().next();
final String fTypeA_key = fTypeAField.get( CalimochoKeys.KEY );
final String fTypeA_value = fTypeAField.get( CalimochoKeys.VALUE );
Assert.assertEquals("tag", fTypeA_key);
Assert.assertEquals("?-?", fTypeA_value);
Collection<Field> partDetMethodAFields = row.getFields( partDetectionMethodADefinition.getKey() );
Assert.assertEquals(1, partDetMethodAFields.size());
Field partDetMethodAField = partDetMethodAFields.iterator().next();
final String partDetMethodA_key = partDetMethodAField.get( CalimochoKeys.KEY );
final String partDetMethodA_value = partDetMethodAField.get( CalimochoKeys.VALUE );
final String partDetMethodA_text = partDetMethodAField.get( CalimochoKeys.TEXT );
Assert.assertEquals("psi-mi", partDetMethodA_key);
Assert.assertEquals("MI:0102", partDetMethodA_value);
Assert.assertEquals("sequence tag identification", partDetMethodA_text);
}
@Test
public void readMitab28Line() throws Exception {
XrefFieldParser xrefParser = new XrefFieldParser();
XrefFieldFormatter xrefFormatter = new XrefFieldFormatter();
ColumnDefinition biologicalEffectADefinition = new ColumnDefinitionBuilder()
.setKey( "bioEffectA" )
.setPosition( 42 )
.setFieldSeparator("|")
.setEmptyValue("-")
.setFieldDelimiter("")
.setIsAllowsEmpty(true)
.setFieldFormatter(xrefFormatter)
.setFieldParser(xrefParser)
.build();
ColumnDefinition causalRegMechanismDefinition = new ColumnDefinitionBuilder()
.extendColumnDefinition( biologicalEffectADefinition )
.setKey( "causalmechanism" )
.setPosition( 44 )
.build();
ColumnBasedDocumentDefinition docDefinition = new ColumnBasedDocumentDefinitionBuilder()
.addColumnDefinition( biologicalEffectADefinition )
.addColumnDefinition( causalRegMechanismDefinition )
.setColumnSeparator( "\t" )
.setCommentPrefix( "#" )
.build();
RowReader rowReader = new DefaultRowReader( docDefinition );
Row row = rowReader.readLine(mitab28Line);
Assert.assertNotNull( row );
Collection<Field> bioEffectAFields = row.getFields( biologicalEffectADefinition.getKey() );
Assert.assertEquals( 0, bioEffectAFields.size() );
Collection<Field> causalRegMechanismFields = row.getFields( causalRegMechanismDefinition.getKey() );
Assert.assertEquals(1, causalRegMechanismFields.size());
Field causalRegMechanismField = causalRegMechanismFields.iterator().next();
final String key = causalRegMechanismField.get( CalimochoKeys.KEY );
final String value = causalRegMechanismField.get( CalimochoKeys.VALUE );
final String text = causalRegMechanismField.get( CalimochoKeys.TEXT );
Assert.assertEquals("psi-mi", key);
Assert.assertEquals("MI:2247", value);
Assert.assertEquals("transcriptional regulation", text);
}
@Test
public void readMitab26Stream() throws Exception {
InputStream is = DefaultRowReaderTest.class.getResourceAsStream( "/META-INF/mitab26/14726512.txt" );
ColumnDefinition columnDefinition = new ColumnDefinitionBuilder()
.setKey( "id" )
.setPosition( 0 )
.setFieldSeparator( "|" )
.setFieldParser( new KeyValueFieldParser( ":" ) )
.setFieldFormatter( new KeyValueFieldFormatter( ":" ) )
.build();
ColumnBasedDocumentDefinition docDefinition = new ColumnBasedDocumentDefinitionBuilder()
.addColumnDefinition( columnDefinition )
.setColumnSeparator( "\t" )
.setCommentPrefix( "#" )
.build();
RowReader reader = new DefaultRowReader(docDefinition);
List<Row> rows = reader.read(is);
Assert.assertEquals( 1, rows.size() );
Row row = rows.get( 0 );
Collection<Field> fields = row.getFields( columnDefinition.getKey() );
Assert.assertEquals( 1, fields.size() );
Field field = fields.iterator().next();
final String key = field.get( CalimochoKeys.KEY );
final String value = field.get( CalimochoKeys.VALUE );
final String text = field.get( CalimochoKeys.TEXT );
Assert.assertEquals("uniprotkb", key);
Assert.assertEquals("Q9Y5J7", value);
Assert.assertNull( text );
}
@Test
public void readMitab27Stream() throws Exception {
InputStream is = DefaultRowReaderTest.class.getResourceAsStream( "/META-INF/mitab27/mitab27_example.txt" );
XrefFieldParser xrefParser = new XrefFieldParser();
XrefFieldFormatter xrefFormatter = new XrefFieldFormatter();
ColumnDefinition hostOrganismDefinition = new ColumnDefinitionBuilder()
.setKey("taxidHost")
.setFieldSeparator("|")
.setEmptyValue("-")
.setFieldDelimiter("")
.setIsAllowsEmpty(true)
.setPosition(28)
.setFieldFormatter(xrefFormatter)
.setFieldParser(xrefParser)
.build();
ColumnDefinition partDetectionMethodBDefinition = new ColumnDefinitionBuilder()
.extendColumnDefinition(hostOrganismDefinition)
.setKey("pmethodB")
.setPosition(41)
.build();
ColumnBasedDocumentDefinition docDefinition = new ColumnBasedDocumentDefinitionBuilder()
.addColumnDefinition(hostOrganismDefinition)
.addColumnDefinition(partDetectionMethodBDefinition)
.setColumnSeparator( "\t" )
.setCommentPrefix( "#" )
.build();
RowReader reader = new DefaultRowReader(docDefinition);
List<Row> rows = reader.read(is);
Assert.assertEquals( 1, rows.size() );
Row row = rows.get( 0 );
Collection<Field> hostOrganismFields = row.getFields( hostOrganismDefinition.getKey() );
Assert.assertEquals( 2, hostOrganismFields.size() );
for (Field hostOrganismField : hostOrganismFields) {
final String key = hostOrganismField.get( CalimochoKeys.KEY );
final String value = hostOrganismField.get( CalimochoKeys.VALUE );
final String text = hostOrganismField.get( CalimochoKeys.TEXT );
Assert.assertEquals("taxid", key);
Assert.assertEquals("7227", value);
Assert.assertTrue(text.equalsIgnoreCase("drome-embryo") || text.equalsIgnoreCase("drosophilla melanogaster embryo"));
}
Collection<Field> pmethodBFields = row.getFields( partDetectionMethodBDefinition.getKey() );
Assert.assertEquals( 1, pmethodBFields.size() );
Field pmethodBField = pmethodBFields.iterator().next();
final String key = pmethodBField.get( CalimochoKeys.KEY );
final String value = pmethodBField.get( CalimochoKeys.VALUE );
final String text = pmethodBField.get( CalimochoKeys.TEXT );
Assert.assertEquals("psi-mi", key);
Assert.assertEquals("MI:0102", value);
Assert.assertEquals("sequence tag identification", text);
}
@Test
public void readMitab28Stream() throws Exception {
InputStream is = DefaultRowReaderTest.class.getResourceAsStream( "/META-INF/mitab28/mitab28_example.txt" );
XrefFieldParser xrefParser = new XrefFieldParser();
XrefFieldFormatter xrefFormatter = new XrefFieldFormatter();
ColumnDefinition biologicalEffectBDefinition = new ColumnDefinitionBuilder()
.setKey( "bioEffectB" )
.setPosition( 43 )
.setFieldSeparator("|")
.setEmptyValue("-")
.setFieldDelimiter("")
.setIsAllowsEmpty(true)
.setFieldFormatter(xrefFormatter)
.setFieldParser(xrefParser)
.build();
ColumnDefinition causalStatementDefinition = new ColumnDefinitionBuilder()
.extendColumnDefinition( biologicalEffectBDefinition)
.setKey( "causalstatement" )
.setPosition( 45 )
.build();
ColumnBasedDocumentDefinition docDefinition = new ColumnBasedDocumentDefinitionBuilder()
.addColumnDefinition(biologicalEffectBDefinition)
.addColumnDefinition(causalStatementDefinition)
.setColumnSeparator( "\t" )
.setCommentPrefix( "#" )
.build();
RowReader reader = new DefaultRowReader(docDefinition);
List<Row> rows = reader.read(is);
Assert.assertEquals( 1, rows.size() );
Row row = rows.get( 0 );
Collection<Field> bioEffectBFields = row.getFields( biologicalEffectBDefinition.getKey() );
Assert.assertEquals(1, bioEffectBFields.size());
Field bioEffectBField = bioEffectBFields.iterator().next();
final String bioEffectBField_key = bioEffectBField.get( CalimochoKeys.KEY );
final String bioEffectBField_value = bioEffectBField.get( CalimochoKeys.VALUE );
final String bioEffectBField_text = bioEffectBField.get( CalimochoKeys.TEXT );
Assert.assertEquals("go", bioEffectBField_key);
Assert.assertEquals("GO:0016301", bioEffectBField_value);
Assert.assertEquals("kinase activity", bioEffectBField_text);
Collection<Field> causalStatementFields = row.getFields( causalStatementDefinition.getKey() );
Assert.assertEquals(1, causalStatementFields.size());
Field causalStatementField = causalStatementFields.iterator().next();
final String causalStatementField_key = causalStatementField.get( CalimochoKeys.KEY );
final String causalStatementField_value = causalStatementField.get( CalimochoKeys.VALUE );
final String causalStatementField_text = causalStatementField.get( CalimochoKeys.TEXT );
Assert.assertEquals("psi-mi", causalStatementField_key);
Assert.assertEquals("MI:2240", causalStatementField_value);
Assert.assertEquals("down regulates", causalStatementField_text);
}
@Test()
@Ignore
// we don't want this test anymore. If the number of columns is bigger/lower that the one expected in column definitions, we just ignore the supplementary columns.
// this would help with parsing MITAB 2.5 files using 2.7 parser and 2.7 files using 2.5 parser
public void invalidInputFile_columnCount() throws Exception {
ColumnBasedDocumentDefinition dd = new ColumnBasedDocumentDefinitionBuilder().addColumnDefinition( new ColumnDefinitionBuilder()
.setKey( "gene" )
.setPosition( 1 )
.setEmptyValue( "" )
.setIsAllowsEmpty( false )
.setFieldSeparator( "," )
.setFieldDelimiter( "" )
.setFieldParser( new LiteralFieldParser() )
.setFieldFormatter( new LiteralFieldFormatter() )
.build() )
.addColumnDefinition( new ColumnDefinitionBuilder()
.setKey( "taxid" )
.setPosition( 2 )
.setEmptyValue( "" )
.setIsAllowsEmpty( false )
.setFieldSeparator( "," )
.setFieldDelimiter( "" )
.setFieldParser( new LiteralFieldParser() )
.setFieldFormatter( new LiteralFieldFormatter() )
.build() )
.setColumnSeparator( "|" )
.build();
String aLine = "LSM7|9606";
RowReader reader = new DefaultRowReader( dd );
try {
reader.readLine( aLine );
Assert.fail("Expected IllegalRowException to be thrown");
} catch ( IllegalRowException e ) {
// expected here !
Assert.assertEquals( aLine, e.getLine() );
} catch ( IllegalColumnException e ) {
Assert.fail();
} catch ( IllegalFieldException e ) {
Assert.fail();
}
}
@Test
public void read_fieldKeyValue() throws Exception {
final String aLine = "LSM7|9606\n";
final ColumnBasedDocumentDefinition documentDefinition = buildGeneListDefinition();
RowReader reader = new DefaultRowReader( documentDefinition );
final List<Row> rows = reader.read( new ByteArrayInputStream( aLine.getBytes() ) );
org.junit.Assert.assertNotNull( rows );
org.junit.Assert.assertEquals( 1, rows.size() );
Row row = rows.get( 0 );
final Collection<Field> geneFields = row.getFields( "gene" );
Assert.assertNotNull( geneFields );
Assert.assertEquals(1, geneFields.size());
final Field geneField = geneFields.iterator().next();
final String gene = geneField.get( CalimochoKeys.VALUE );
Assert.assertNotNull( gene );
Assert.assertEquals("LSM7", gene);
final Collection<Field> taxidFields = row.getFields( "taxid" );
Assert.assertNotNull( taxidFields );
Assert.assertEquals(1, taxidFields.size());
final Field taxidField = taxidFields.iterator().next();
final String taxid = taxidField.get( CalimochoKeys.VALUE );
Assert.assertNotNull( taxid );
Assert.assertEquals("9606", taxid);
}
}
| 21,260 | 0.608996 | 0.595084 | 477 | 42.603775 | 33.311253 | 167 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.528302 | false | false | 3 |
1740a1e9c989af04abb7695d733e162712f32fad | 10,033,043,651,816 | d881ff6c893792e3027346100c2b839beaedc246 | /app/src/main/java/mobi/medbook/android/events/notifications/EventLoadNofications.java | f78d4296ee270b13939b0d0f8e46d5da30a62244 | [] | no_license | IhorSpivak/MedBook | https://github.com/IhorSpivak/MedBook | a9dffa304b203bcddf0205358a419c38ed879128 | 97d0048495a7c613fe4f5779c16956270cee1dee | refs/heads/master | 2022-02-17T17:34:26.672000 | 2019-09-29T22:37:17 | 2019-09-29T22:37:17 | 198,087,930 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package mobi.medbook.android.events.notifications;
import mobi.medbook.android.events.core.Event;
public class EventLoadNofications extends Event {
public EventLoadNofications(boolean success, String message) {
super(EVENT_LOAD_NOTIFICATIONS);
}
}
| UTF-8 | Java | 266 | java | EventLoadNofications.java | Java | [] | null | [] | package mobi.medbook.android.events.notifications;
import mobi.medbook.android.events.core.Event;
public class EventLoadNofications extends Event {
public EventLoadNofications(boolean success, String message) {
super(EVENT_LOAD_NOTIFICATIONS);
}
}
| 266 | 0.774436 | 0.774436 | 9 | 28.555555 | 25.07815 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false | 3 |
46994933350d2f5b97fe78edd5c21ea0cccd5808 | 17,033,840,303,277 | a3c531fc2ddb7451ec3ff0f6115b0ab341b324a5 | /app/src/main/java/org/ahmadhelmiyahya775/MathForFun/KalkulatorTabung.java | 84183c38cbc9b7df1100240d8e1241c9d09b859d | [] | no_license | ahmadhelmi775/ProjectUTS | https://github.com/ahmadhelmi775/ProjectUTS | 67e01a73081779b7e5b2f366124d1a2118c08f6d | 8792dba4d453fa561e7b91c4c127654b702619ea | refs/heads/master | 2021-05-20T14:39:42.221000 | 2020-04-02T02:02:39 | 2020-04-02T02:02:39 | 252,336,207 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.ahmadhelmiyahya775.MathForFun;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
public class KalkulatorTabung extends AppCompatActivity {
EditText editJariTabung, editTinggiTabung;
TextView textLuasTabung, textVolumeTabung;
Double jari,tinggi, volume, luas;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kalkulator_tabung);
editJariTabung = (EditText) findViewById(R.id.editJariTabung);
editTinggiTabung = (EditText) findViewById(R.id.editTinggiTabung);
textVolumeTabung = (TextView) findViewById(R.id.text_volume_tabung);
textLuasTabung = (TextView) findViewById(R.id.text_luas_tabung);
Intent intent = getIntent();
final String namaBangunRuang = intent.getExtras().getString("namaBangunRuang");
final String descBangunRuang = intent.getExtras().getString("descBangunRuang");
final int whiteThumbBangunRuang = intent.getExtras().getInt("whiteThumbBangunRuang");
final String luasBangunRuang = intent.getExtras().getString("luasBangunRuang");
final String volumeBangunRuang = intent.getExtras().getString("volumeBangunRuang");
final int rumusBangunRuang = intent.getExtras().getInt("rumusBangunRuang");
FloatingActionButton fab = findViewById(R.id.fabBack);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), MateriBangunRuang.class);
intent.putExtra("namaBangunRuang", namaBangunRuang);
intent.putExtra("descBangunRuang", descBangunRuang);
intent.putExtra("whiteThumbBangunRuang", whiteThumbBangunRuang);
intent.putExtra("luasBangunRuang", luasBangunRuang);
intent.putExtra("volumeBangunRuang", volumeBangunRuang);
intent.putExtra("rumusBangunRuang", rumusBangunRuang);
startActivity(intent);
}
});
}
public void HitungVolumeTabung(View view){
jari = Double.parseDouble(editJariTabung.getText().toString());
tinggi = Double.parseDouble(editTinggiTabung.getText().toString());
volume = 3.14*jari*jari*tinggi;
textVolumeTabung.setText(String.valueOf(volume));
}
public void HitungLuasTabung(View view){
jari = Double.parseDouble(editJariTabung.getText().toString());
tinggi = Double.parseDouble(editTinggiTabung.getText().toString());
luas = 2*(3.14*jari*jari)+(2*3.14*jari)*tinggi;
textLuasTabung.setText(String.valueOf(luas));
}
}
| UTF-8 | Java | 2,962 | java | KalkulatorTabung.java | Java | [
{
"context": "package org.ahmadhelmiyahya775.MathForFun;\n\nimport android.content.Intent;\nimpor",
"end": 30,
"score": 0.7431163787841797,
"start": 20,
"tag": "USERNAME",
"value": "miyahya775"
}
] | null | [] | package org.ahmadhelmiyahya775.MathForFun;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
public class KalkulatorTabung extends AppCompatActivity {
EditText editJariTabung, editTinggiTabung;
TextView textLuasTabung, textVolumeTabung;
Double jari,tinggi, volume, luas;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kalkulator_tabung);
editJariTabung = (EditText) findViewById(R.id.editJariTabung);
editTinggiTabung = (EditText) findViewById(R.id.editTinggiTabung);
textVolumeTabung = (TextView) findViewById(R.id.text_volume_tabung);
textLuasTabung = (TextView) findViewById(R.id.text_luas_tabung);
Intent intent = getIntent();
final String namaBangunRuang = intent.getExtras().getString("namaBangunRuang");
final String descBangunRuang = intent.getExtras().getString("descBangunRuang");
final int whiteThumbBangunRuang = intent.getExtras().getInt("whiteThumbBangunRuang");
final String luasBangunRuang = intent.getExtras().getString("luasBangunRuang");
final String volumeBangunRuang = intent.getExtras().getString("volumeBangunRuang");
final int rumusBangunRuang = intent.getExtras().getInt("rumusBangunRuang");
FloatingActionButton fab = findViewById(R.id.fabBack);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), MateriBangunRuang.class);
intent.putExtra("namaBangunRuang", namaBangunRuang);
intent.putExtra("descBangunRuang", descBangunRuang);
intent.putExtra("whiteThumbBangunRuang", whiteThumbBangunRuang);
intent.putExtra("luasBangunRuang", luasBangunRuang);
intent.putExtra("volumeBangunRuang", volumeBangunRuang);
intent.putExtra("rumusBangunRuang", rumusBangunRuang);
startActivity(intent);
}
});
}
public void HitungVolumeTabung(View view){
jari = Double.parseDouble(editJariTabung.getText().toString());
tinggi = Double.parseDouble(editTinggiTabung.getText().toString());
volume = 3.14*jari*jari*tinggi;
textVolumeTabung.setText(String.valueOf(volume));
}
public void HitungLuasTabung(View view){
jari = Double.parseDouble(editJariTabung.getText().toString());
tinggi = Double.parseDouble(editTinggiTabung.getText().toString());
luas = 2*(3.14*jari*jari)+(2*3.14*jari)*tinggi;
textLuasTabung.setText(String.valueOf(luas));
}
}
| 2,962 | 0.702566 | 0.697839 | 69 | 41.913044 | 30.956604 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.782609 | false | false | 1 |
3caef39ef8231d25c10525145becb96e28e93137 | 17,059,610,162,759 | d3c40c09f50229b6f7b75866b1e75655dc2ed100 | /gwa/src/main/java/com/tks/gwa/entity/Tradepost.java | 023fc984edda3aceae23ae2bdc0e8be792691560 | [] | no_license | hoangngominhtung212192/capstone | https://github.com/hoangngominhtung212192/capstone | 21466a39c41937ca0d68ad9b685091f4cc483599 | 09c5df4954f7be42787017300e3947e4891857c1 | refs/heads/master | 2020-03-30T11:10:45.902000 | 2019-02-11T07:43:41 | 2019-02-11T07:43:41 | 151,157,362 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tks.gwa.entity;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Table(name = "tradepost")
public class Tradepost implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "approvalstatus")
private String approvalStatus;
@Column(name = "brand")
private String brand;
@Column(name = "`condition`")
private int condition;
@Lob
@Column(name = "`description`")
private String description;
@Column(name = "lastmodified")
private String lastModified;
@Column(name = "location")
private String location;
@Column(name = "latlng")
private String latlng;
@Column(name = "model")
private String model;
@Column(name = "posteddate")
private String postedDate;
@Column(name = "price")
private double price;
@Column(name = "pricenegotiable")
private int priceNegotiable;
@Column(name = "quantity")
private int quantity;
@Column(name = "rejectreason")
private String rejectReason;
@Column(name = "title")
private String title;
@Column(name = "tradetype")
private int tradeType;
@Column(name = "numberofrater")
private int numberOfRater;
@Column(name = "numberofstar")
private int numberOfStar;
//bi-directional many-to-one association to Account
@ManyToOne
@JoinColumn(name="ownerid")
private Account account;
public Tradepost(){}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getApprovalStatus() {
return approvalStatus;
}
public void setApprovalStatus(String approvalStatus) {
this.approvalStatus = approvalStatus;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public int getCondition() {
return condition;
}
public void setCondition(int condition) {
this.condition = condition;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getLastModified() {
return lastModified;
}
public void setLastModified(String lastModified) {
this.lastModified = lastModified;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getPostedDate() {
return postedDate;
}
public void setPostedDate(String postedDate) {
this.postedDate = postedDate;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getPriceNegotiable() {
return priceNegotiable;
}
public void setPriceNegotiable(int priceNegotiable) {
this.priceNegotiable = priceNegotiable;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String getRejectReason() {
return rejectReason;
}
public void setRejectReason(String rejectReason) {
this.rejectReason = rejectReason;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getTradeType() {
return tradeType;
}
public void setTradeType(int tradeType) {
this.tradeType = tradeType;
}
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
public int getNumberOfRater() {
return numberOfRater;
}
public void setNumberOfRater(int numberOfRater) {
this.numberOfRater = numberOfRater;
}
public int getNumberOfStar() {
return numberOfStar;
}
public void setNumberOfStar(int numberOfStar) {
this.numberOfStar = numberOfStar;
}
public String getLatlng() {
return latlng;
}
public void setLatlng(String latlng) {
this.latlng = latlng;
}
}
| UTF-8 | Java | 4,500 | java | Tradepost.java | Java | [] | null | [] | package com.tks.gwa.entity;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Table(name = "tradepost")
public class Tradepost implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "approvalstatus")
private String approvalStatus;
@Column(name = "brand")
private String brand;
@Column(name = "`condition`")
private int condition;
@Lob
@Column(name = "`description`")
private String description;
@Column(name = "lastmodified")
private String lastModified;
@Column(name = "location")
private String location;
@Column(name = "latlng")
private String latlng;
@Column(name = "model")
private String model;
@Column(name = "posteddate")
private String postedDate;
@Column(name = "price")
private double price;
@Column(name = "pricenegotiable")
private int priceNegotiable;
@Column(name = "quantity")
private int quantity;
@Column(name = "rejectreason")
private String rejectReason;
@Column(name = "title")
private String title;
@Column(name = "tradetype")
private int tradeType;
@Column(name = "numberofrater")
private int numberOfRater;
@Column(name = "numberofstar")
private int numberOfStar;
//bi-directional many-to-one association to Account
@ManyToOne
@JoinColumn(name="ownerid")
private Account account;
public Tradepost(){}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getApprovalStatus() {
return approvalStatus;
}
public void setApprovalStatus(String approvalStatus) {
this.approvalStatus = approvalStatus;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public int getCondition() {
return condition;
}
public void setCondition(int condition) {
this.condition = condition;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getLastModified() {
return lastModified;
}
public void setLastModified(String lastModified) {
this.lastModified = lastModified;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getPostedDate() {
return postedDate;
}
public void setPostedDate(String postedDate) {
this.postedDate = postedDate;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getPriceNegotiable() {
return priceNegotiable;
}
public void setPriceNegotiable(int priceNegotiable) {
this.priceNegotiable = priceNegotiable;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String getRejectReason() {
return rejectReason;
}
public void setRejectReason(String rejectReason) {
this.rejectReason = rejectReason;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getTradeType() {
return tradeType;
}
public void setTradeType(int tradeType) {
this.tradeType = tradeType;
}
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
public int getNumberOfRater() {
return numberOfRater;
}
public void setNumberOfRater(int numberOfRater) {
this.numberOfRater = numberOfRater;
}
public int getNumberOfStar() {
return numberOfStar;
}
public void setNumberOfStar(int numberOfStar) {
this.numberOfStar = numberOfStar;
}
public String getLatlng() {
return latlng;
}
public void setLatlng(String latlng) {
this.latlng = latlng;
}
}
| 4,500 | 0.624444 | 0.624444 | 225 | 19 | 16.862581 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.266667 | false | false | 1 |
6a8c61aafef92e55c25bbd4a18abd545becfdec6 | 8,753,143,393,339 | 6a418002abe7bfefd6c2d8d3e86162671d0ba124 | /intro_comp_sci/assign6/src/Board.java | 3b5ad9664bdb8ac917d23f064d72ffeab75d0c5f | [] | no_license | p8858xp/portfolio | https://github.com/p8858xp/portfolio | 25cee70533535fe990b5f22adeffd240d045c048 | 15f4290c7107e306a8f8ca92cd363dbf209814ff | refs/heads/master | 2022-12-09T07:05:38.820000 | 2019-07-26T17:38:56 | 2019-07-26T17:38:56 | 152,906,351 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | //HW6(Board)
//pp1445
//
//Paul Park
//1 hour
//*************************
public class Board {
int [][] board;
public Board(){
board = new int[3][3];
}
//create a method called container
public int container(int x, int y){
return board[x][y];
}
//create a method called put that will take in a string and two ints as parameters
public void put(String letter, int x, int y){
if (letter.equals("X")){
board[x][y]=1;
}
else {
board[x][y]=2;
}
}
//create a method to check if there is indeed a winner at every turn
public int checkWinner(){
int counter = 0;
for (int x = 0;x<board.length;x++){
for(int y = 0;y<board[x].length;y++){
if (board[x][y]!=0){
counter+=1;
}
}
}
if (counter == 9){
return -1;
}
//horizontals
if (board[0][0] == board[0][1] && board[0][1] == board[0][2] && board[0][0]!=0) {
return board[0][0];
}
if (board[1][0] == board[1][1] && board[1][1] == board[1][2] && board[1][0]!=0){
return board[1][0];
}
if (board[2][0] == board[2][1] && board[2][1] == board[2][2] && board[2][0]!=0){
return board[2][0];
}
//verticals
if (board[0][0] == board[1][0] && board[1][0] == board[2][0] && board[0][0]!=0){
return board[0][0];
}
if (board[0][1] == board[1][1] && board[1][1] == board[2][1] && board[0][1]!=0){
return board[0][1];
}
if (board[0][2] == board[1][2] && board[1][2] == board[2][2] && board[0][2]!=0){
return board[0][2];
}
//diagonals
if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[0][0]!=0){
return board[0][0];
}
if (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[0][2]!=0){
return board[0][2];
}
return 0;
}
}
| UTF-8 | Java | 1,710 | java | Board.java | Java | [
{
"context": "//HW6(Board)\n//pp1445\n//\n//Paul Park\n//1 hour\n//*************************\npublic class",
"end": 36,
"score": 0.999700129032135,
"start": 27,
"tag": "NAME",
"value": "Paul Park"
}
] | null | [] | //HW6(Board)
//pp1445
//
//<NAME>
//1 hour
//*************************
public class Board {
int [][] board;
public Board(){
board = new int[3][3];
}
//create a method called container
public int container(int x, int y){
return board[x][y];
}
//create a method called put that will take in a string and two ints as parameters
public void put(String letter, int x, int y){
if (letter.equals("X")){
board[x][y]=1;
}
else {
board[x][y]=2;
}
}
//create a method to check if there is indeed a winner at every turn
public int checkWinner(){
int counter = 0;
for (int x = 0;x<board.length;x++){
for(int y = 0;y<board[x].length;y++){
if (board[x][y]!=0){
counter+=1;
}
}
}
if (counter == 9){
return -1;
}
//horizontals
if (board[0][0] == board[0][1] && board[0][1] == board[0][2] && board[0][0]!=0) {
return board[0][0];
}
if (board[1][0] == board[1][1] && board[1][1] == board[1][2] && board[1][0]!=0){
return board[1][0];
}
if (board[2][0] == board[2][1] && board[2][1] == board[2][2] && board[2][0]!=0){
return board[2][0];
}
//verticals
if (board[0][0] == board[1][0] && board[1][0] == board[2][0] && board[0][0]!=0){
return board[0][0];
}
if (board[0][1] == board[1][1] && board[1][1] == board[2][1] && board[0][1]!=0){
return board[0][1];
}
if (board[0][2] == board[1][2] && board[1][2] == board[2][2] && board[0][2]!=0){
return board[0][2];
}
//diagonals
if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[0][0]!=0){
return board[0][0];
}
if (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[0][2]!=0){
return board[0][2];
}
return 0;
}
}
| 1,707 | 0.515205 | 0.44386 | 69 | 23.782608 | 25.755184 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.246377 | false | false | 1 |
fdf868c554bde73fdf2956ddff643412ca3752a1 | 30,150,670,428,959 | 6cde52773994ab16570e3479c6e68dd49bc86fc2 | /2/CPM/FinalModule/src/logic/TravelAgency.java | 298393d61e1d3e4cbcdd5ff779260b128f15fbb1 | [] | no_license | themrcesi/Computer-Software-Engineering | https://github.com/themrcesi/Computer-Software-Engineering | 8053b4e7d566bc543d99f638e49c65faa6a140e5 | 87c1601a816edeaab247763cc108d740164b78f9 | refs/heads/master | 2019-12-15T03:27:22.541000 | 2018-12-30T11:09:12 | 2018-12-30T11:09:12 | 86,713,998 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package logic;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.FilterWriter;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
import exceptions.InvalidFormatException;
import exceptions.ItemAlreadyAddedException;
import logic.comparators.AccommodationComparatorByCategory;
import logic.comparators.AccommodationComparatorByName;
import logic.comparators.AccommodationComparatorByPrice;
import logic.comparators.PackageComparatorByAdultPrice;
import logic.comparators.PackageComparatorByChildrenPrice;
import logic.comparators.PackageComparatorByName;
import logic.comparators.ThemeParkComparatorByAdultPrice;
import logic.comparators.ThemeParkComparatorByChildrenPrice;
import logic.comparators.ThemeParkComparatorByName;
import logic.elements.Accommodation;
import logic.elements.Hotel;
import logic.elements.Package;
import logic.elements.ThemePark;
import logic.elements.Ticket;
import logic.order.AccommodationR;
import logic.order.PackageR;
import logic.order.Pedido;
import logic.order.ThemeParkR;
import logic.parser.AccommodationReader;
import logic.parser.PackageReader;
import logic.parser.ThemeParkReader;
import logic.parser.TicketReader;
public class TravelAgency {
public final static String acFile="files/alojamientos.dat";
public final static String parkFile="files/tematicos.dat";
public final static String ticketFile="files/entradas.dat";
public final static String packageFile="files/paquetes.dat";
public final static int NUM_PARKS=7;
private List<ThemePark> parks=new ArrayList<ThemePark>();
private List<Accommodation> accommodations=new ArrayList<Accommodation>();
private List<Ticket> tickets=new ArrayList<Ticket>();
private List<Package> packages=new ArrayList<Package>();
private Pedido pedido=new Pedido();
private AccommodationReader acReader;
private TicketReader ticketReader;
private ThemeParkReader parkReader;
private PackageReader packageReader;
private int random=0;
public TravelAgency() throws FileNotFoundException, IOException
{
acReader=new AccommodationReader(this);
ticketReader=new TicketReader(this);
parkReader=new ThemeParkReader(this);
packageReader=new PackageReader(this);
loadData(random);
}
public List<ThemePark> getParks()
{
return parks;
}
public List<Accommodation> getAccommodations()
{
return accommodations;
}
public List<Ticket> getTickets()
{
return tickets;
}
public List<Package> getPackages()
{
return packages;
}
private void loadData(int random) throws FileNotFoundException, IOException
{
random=new Random().nextInt(NUM_PARKS);
ticketReader.loadFromFile(ticketFile);
parkReader.loadFromFile(parkFile,random);
acReader.loadFromFile(acFile);
packageReader.loadFromFile(packageFile);
}
public void addThemePark(ThemePark park) throws InvalidFormatException
{
try {
if(park!=null)
{
if(parks.contains(park))
{
throw new ItemAlreadyAddedException("Park already added");
}
parks.add(park);
}
} catch(ItemAlreadyAddedException e){
System.err.println("Park already added");
throw new InvalidFormatException("e");
}
}
public void addPackage(Package pac) throws InvalidFormatException
{
try {
if(pac!=null)
{
if(packages.contains(pac))
{
throw new ItemAlreadyAddedException("Package already added");
}
packages.add(pac);
}
} catch(ItemAlreadyAddedException e){
System.err.println("Package already added");
throw new InvalidFormatException("e");
}
}
public void addAccommodation(Accommodation ac) throws InvalidFormatException
{
try {
if(ac!=null)
{
if(accommodations.contains(ac))
{
throw new ItemAlreadyAddedException("Accommodation already added");
}
accommodations.add(ac);
}
} catch(ItemAlreadyAddedException e){
System.err.println("Accommodation already added");
throw new InvalidFormatException("e");
}
}
public void addTicket(Ticket ticket) throws InvalidFormatException
{
try {
if(ticket!=null)
{
if(tickets.contains(ticket))
{
throw new ItemAlreadyAddedException("Ticket already added");
}
tickets.add(ticket);
}
} catch(ItemAlreadyAddedException e){
System.err.println("Ticket already added");
throw new InvalidFormatException("e");
}
}
public ThemePark searchPark(String parkCode)
{
for(ThemePark p:parks)
{
if(p.getCode().equals(parkCode))
return p;
}
return null;
}
public Accommodation searchAccommodation(String acCode)
{
for(Accommodation ac:accommodations)
{
if(ac.getCode().equals(acCode))
{
return ac;
}
}
return null;
}
public Ticket searchTicket(String parkCode)
{
String ticket=parkCode.substring(2);
for(Ticket t:tickets)
{
if(t.getCode().equals("EN"+ticket))
return t;
}
return null;
}
public double getMaxPricePackA()
{
double max=0;
for(Package p:packages)
{
if(p.getAdultPrice()>max)
{
max=p.getAdultPrice();
}
}
return max;
}
public double getMaxPricePackC()
{
double max=0;
for(Package p:packages)
{
if(p.getChildrenPrice()>max)
{
max=p.getChildrenPrice();
}
}
return max;
}
public int getMinPricePackA()
{
double min=10000;
for(Package p:packages)
{
if(p.getAdultPrice()<min)
{
min=p.getAdultPrice();
}
}
return (int) min;
}
public double getMinPricePackC()
{
double min=10000;
for(Package p:packages)
{
if(p.getChildrenPrice()<min)
{
min=p.getChildrenPrice();
}
}
return min;
}
public int getMaxLengthPack()
{
int max=0;
for(Package p:packages)
{
if(p.getDays()>max)
{
max=p.getDays();
}
}
return max;
}
public double getMaxPriceParkA()
{
double max=0;
for(ThemePark p:parks)
{
if(p.getTicket().getAdultPrice()>max)
{
max=p.getTicket().getAdultPrice();
}
}
return max;
}
public double getMaxPriceParkC()
{
double max=0;
for(ThemePark p:parks)
{
if(p.getTicket().getChildrenPrice()>max)
{
max=p.getTicket().getChildrenPrice();
}
}
return max;
}
public ArrayList<Integer> getCategoriesSorted()
{
ArrayList<Integer> list=new ArrayList<Integer>();
for(int i=0;i<getAccommodations().size();i++)
{
if(!(list.contains(getAccommodations().get(i).getCategory())))
list.add(getAccommodations().get(i).getCategory());
}
ArrayList<Integer> aux=new ArrayList<Integer>();
for(int i=0;i<list.size();i++)
{
addSorted(list.get(i),aux);
}
for(int i=0;i<aux.size();i++)
{
list.set(i, aux.get(i));
}
return list;
}
private void addSorted(Integer integer, ArrayList<Integer> aux)
{
for(int i=0;i<aux.size();i++)
{
if(integer<aux.get(i))
{
aux.add(i,integer);
return ;
}
}
aux.add(integer);
}
public double getMaxPriceAc()
{
double max=0;
for(Accommodation a:getAccommodations())
{
if(a.getPrice()>max)
{
max=a.getPrice();
}
}
return max;
}
public ArrayList<Package> getPackagesRequested(String park, String acType, int maxPriceA, int minPriceA,
int maxPriceC, int minPriceC, int length)
{
ArrayList<Package> returned=new ArrayList<Package>();
for(Package p:packages)
{
int count=0;
if(park!=null)
{
if(p.getPark().getName().equals(park))
{
count++;
}
}
else
{
count++;
}
if(acType!=null)
{
if(p.getAc().getType().equals(acType))
{
count++;
}
}
else
{
count++;
}
if(p.getAdultPrice()<=maxPriceA && p.getAdultPrice()>=minPriceA)
{
count++;
}
if(p.getChildrenPrice()<=maxPriceC && p.getChildrenPrice()>=minPriceC)
{
count++;
}
if(p.getDays()>=length)
{
count++;
}
if(count==5)
{
returned.add(p);
}
}
return returned;
}
public void addPackageToPedido(PackageR p)
{
pedido.addPackage(p);
}
public void addThemeParkToPedido(ThemeParkR p)
{
pedido.addThemePark(p);
}
public void addAccommodationToPedido(AccommodationR a)
{
pedido.addAccommodation(a);
}
public void removePackageOfPedido(PackageR p)
{
pedido.removePackage(p);
}
public void removeThemeParkOfPedido(ThemeParkR p)
{
pedido.removeThemePark(p);
}
public void removeAccommodationOfPedido(AccommodationR a)
{
pedido.removeAccommodation(a);
}
public ArrayList<ThemePark> getThemeParksRequested(int minPriceA, int maxPriceA, int minPriceC, int maxPriceC)
{
ArrayList<ThemePark> returned=new ArrayList<ThemePark>();
for(ThemePark p:parks)
{
if(p.getTicket().getAdultPrice()>=minPriceA && p.getTicket().getAdultPrice()<=maxPriceA)
{
if(p.getTicket().getChildrenPrice()>=minPriceC && p.getTicket().getChildrenPrice()<=maxPriceC)
{
returned.add(p);
}
}
}
return returned;
}
public ArrayList<Accommodation> getAccommodationsRequested(String type, Integer category, boolean breakfast, int minPrice, int maxPrice)
{
ArrayList<Accommodation> ac=new ArrayList<Accommodation>();
int count=0;
for(Accommodation a:accommodations)
{
count=0;
if(type!=null)
{
if(a.getType().equals(type))
{
count++;
}
}
else
{
count++;
}
if(category!=null)
{
if(a.getCategory()==category)
{
count++;
}
}
else
{
count++;
}
if(a.getPrice()>=minPrice && a.getPrice()<=maxPrice)
{
count++;
}
if(breakfast)
{
if(a instanceof Hotel)
{
count++;
}
}
else
{
count++;
}
if(count==4)
{
ac.add(a);
}
}
return ac;
}
public Pedido getPedido()
{
return pedido;
}
public void clearPedido()
{
getPedido().getPackages().clear();
getPedido().getParks().clear();
getPedido().getAc().clear();
}
public void grabarPedido(String name, String surname, String id) throws IOException
{
String fileName=id.concat("_"+DateTimeFormatter.ofPattern("dd/MM/yyyy").format(LocalDate.now()))+".txt";
fileName=fileName.replace("/", "-");
String string=getPedido().getInfo(name, surname, id);
BufferedWriter w=new BufferedWriter(new FileWriter(fileName));
w.write(string);
w.close();
}
public ThemePark getParkDiscounted()
{
ThemePark t=null;
for(ThemePark p:parks)
{
if(p.isDiscount())
t=p;
}
return t;
}
public List<Package> getPackagesSortedByAdultPrice(ArrayList<Package> arrayList)
{
List<Package> list=arrayList;
List<Package> aux=new ArrayList<Package>();
Comparator c=new PackageComparatorByAdultPrice();
for(int i=0;i<list.size();i++)
{
addPackageSorted(list.get(i),aux,c);
}
for(int i=0;i<list.size();i++)
{
list.set(i, aux.get(i));
}
return list;
}
private void addPackageSorted(Package pack, List<Package> aux, Comparator<Package> c)
{
for(int i=0;i<aux.size();i++)
{
if(c.compare(pack, aux.get(i))>0)
{
aux.add(i,pack);
return ;
}
}
aux.add(pack);
}
public List<Package> getPackagesSortedByChildrenPrice(ArrayList<Package> arrayList)
{
List<Package> list=arrayList;
List<Package> aux=new ArrayList<Package>();
Comparator c=new PackageComparatorByChildrenPrice();
for(int i=0;i<list.size();i++)
{
addPackageSorted(list.get(i),aux,c);
}
for(int i=0;i<list.size();i++)
{
list.set(i, aux.get(i));
}
return list;
}
public List<Package> getPackagesSortedByName(ArrayList<Package> arrayList)
{
List<Package> list=arrayList;
List<Package> aux=new ArrayList<Package>();
Comparator c=new PackageComparatorByName();
for(int i=0;i<list.size();i++)
{
addPackageSorted(list.get(i),aux,c);
}
for(int i=0;i<list.size();i++)
{
list.set(i, aux.get(i));
}
return list;
}
public List<ThemePark> getParksSortedByAdultPrice(ArrayList<ThemePark> arrayList)
{
List<ThemePark> list=arrayList;
List<ThemePark> aux=new ArrayList<ThemePark>();
Comparator c=new ThemeParkComparatorByAdultPrice();
for(int i=0;i<list.size();i++)
{
addThemeParkSorted(list.get(i),aux,c);
}
for(int i=0;i<list.size();i++)
{
list.set(i, aux.get(i));
}
return list;
}
public List<ThemePark> getParksSortedByChildrenPrice(ArrayList<ThemePark> arrayList)
{
List<ThemePark> list=arrayList;
List<ThemePark> aux=new ArrayList<ThemePark>();
Comparator c=new ThemeParkComparatorByChildrenPrice();
for(int i=0;i<list.size();i++)
{
addThemeParkSorted(list.get(i),aux,c);
}
for(int i=0;i<list.size();i++)
{
list.set(i, aux.get(i));
}
return list;
}
private void addThemeParkSorted(ThemePark themePark, List<ThemePark> aux, Comparator c)
{
for(int i=0;i<aux.size();i++)
{
if(c.compare(themePark, aux.get(i))>0)
{
aux.add(i,themePark);
return ;
}
}
aux.add(themePark);
}
public List<ThemePark> getParksSortedByName(ArrayList<ThemePark> arrayList)
{
List<ThemePark> list=arrayList;
List<ThemePark> aux=new ArrayList<ThemePark>();
Comparator c=new ThemeParkComparatorByName();
for(int i=0;i<list.size();i++)
{
addThemeParkSorted(list.get(i),aux,c);
}
for(int i=0;i<list.size();i++)
{
list.set(i, aux.get(i));
}
return list;
}
public List<Accommodation> getAccommodationsSortedByName(ArrayList<Accommodation> arrayList)
{
List<Accommodation> list=arrayList;
List<Accommodation> aux=new ArrayList<Accommodation>();
Comparator c=new AccommodationComparatorByName();
for(int i=0;i<list.size();i++)
{
addAccommodationSorted(list.get(i),aux,c);
}
for(int i=0;i<list.size();i++)
{
list.set(i, aux.get(i));
}
return list;
}
private void addAccommodationSorted(Accommodation accommodation, List<Accommodation> aux, Comparator c)
{
for(int i=0;i<aux.size();i++)
{
if(c.compare(accommodation, aux.get(i))>0)
{
aux.add(i,accommodation);
return ;
}
}
aux.add(accommodation);
}
public List<Accommodation> getAccommodationsSortedByPrice(ArrayList<Accommodation> arrayList)
{
List<Accommodation> list=arrayList;
List<Accommodation> aux=new ArrayList<Accommodation>();
Comparator c=new AccommodationComparatorByPrice();
for(int i=0;i<list.size();i++)
{
addAccommodationSorted(list.get(i),aux,c);
}
for(int i=0;i<list.size();i++)
{
list.set(i, aux.get(i));
}
return list;
}
public List<Accommodation> getAccommodationsSortedByCategory(ArrayList<Accommodation> arrayList)
{
List<Accommodation> list=arrayList;
List<Accommodation> aux=new ArrayList<Accommodation>();
Comparator c=new AccommodationComparatorByCategory();
for(int i=0;i<list.size();i++)
{
addAccommodationSorted(list.get(i),aux,c);
}
for(int i=0;i<list.size();i++)
{
list.set(i, aux.get(i));
}
return list;
}
}
| UTF-8 | Java | 14,942 | java | TravelAgency.java | Java | [] | null | [] | package logic;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.FilterWriter;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
import exceptions.InvalidFormatException;
import exceptions.ItemAlreadyAddedException;
import logic.comparators.AccommodationComparatorByCategory;
import logic.comparators.AccommodationComparatorByName;
import logic.comparators.AccommodationComparatorByPrice;
import logic.comparators.PackageComparatorByAdultPrice;
import logic.comparators.PackageComparatorByChildrenPrice;
import logic.comparators.PackageComparatorByName;
import logic.comparators.ThemeParkComparatorByAdultPrice;
import logic.comparators.ThemeParkComparatorByChildrenPrice;
import logic.comparators.ThemeParkComparatorByName;
import logic.elements.Accommodation;
import logic.elements.Hotel;
import logic.elements.Package;
import logic.elements.ThemePark;
import logic.elements.Ticket;
import logic.order.AccommodationR;
import logic.order.PackageR;
import logic.order.Pedido;
import logic.order.ThemeParkR;
import logic.parser.AccommodationReader;
import logic.parser.PackageReader;
import logic.parser.ThemeParkReader;
import logic.parser.TicketReader;
public class TravelAgency {
public final static String acFile="files/alojamientos.dat";
public final static String parkFile="files/tematicos.dat";
public final static String ticketFile="files/entradas.dat";
public final static String packageFile="files/paquetes.dat";
public final static int NUM_PARKS=7;
private List<ThemePark> parks=new ArrayList<ThemePark>();
private List<Accommodation> accommodations=new ArrayList<Accommodation>();
private List<Ticket> tickets=new ArrayList<Ticket>();
private List<Package> packages=new ArrayList<Package>();
private Pedido pedido=new Pedido();
private AccommodationReader acReader;
private TicketReader ticketReader;
private ThemeParkReader parkReader;
private PackageReader packageReader;
private int random=0;
public TravelAgency() throws FileNotFoundException, IOException
{
acReader=new AccommodationReader(this);
ticketReader=new TicketReader(this);
parkReader=new ThemeParkReader(this);
packageReader=new PackageReader(this);
loadData(random);
}
public List<ThemePark> getParks()
{
return parks;
}
public List<Accommodation> getAccommodations()
{
return accommodations;
}
public List<Ticket> getTickets()
{
return tickets;
}
public List<Package> getPackages()
{
return packages;
}
private void loadData(int random) throws FileNotFoundException, IOException
{
random=new Random().nextInt(NUM_PARKS);
ticketReader.loadFromFile(ticketFile);
parkReader.loadFromFile(parkFile,random);
acReader.loadFromFile(acFile);
packageReader.loadFromFile(packageFile);
}
public void addThemePark(ThemePark park) throws InvalidFormatException
{
try {
if(park!=null)
{
if(parks.contains(park))
{
throw new ItemAlreadyAddedException("Park already added");
}
parks.add(park);
}
} catch(ItemAlreadyAddedException e){
System.err.println("Park already added");
throw new InvalidFormatException("e");
}
}
public void addPackage(Package pac) throws InvalidFormatException
{
try {
if(pac!=null)
{
if(packages.contains(pac))
{
throw new ItemAlreadyAddedException("Package already added");
}
packages.add(pac);
}
} catch(ItemAlreadyAddedException e){
System.err.println("Package already added");
throw new InvalidFormatException("e");
}
}
public void addAccommodation(Accommodation ac) throws InvalidFormatException
{
try {
if(ac!=null)
{
if(accommodations.contains(ac))
{
throw new ItemAlreadyAddedException("Accommodation already added");
}
accommodations.add(ac);
}
} catch(ItemAlreadyAddedException e){
System.err.println("Accommodation already added");
throw new InvalidFormatException("e");
}
}
public void addTicket(Ticket ticket) throws InvalidFormatException
{
try {
if(ticket!=null)
{
if(tickets.contains(ticket))
{
throw new ItemAlreadyAddedException("Ticket already added");
}
tickets.add(ticket);
}
} catch(ItemAlreadyAddedException e){
System.err.println("Ticket already added");
throw new InvalidFormatException("e");
}
}
public ThemePark searchPark(String parkCode)
{
for(ThemePark p:parks)
{
if(p.getCode().equals(parkCode))
return p;
}
return null;
}
public Accommodation searchAccommodation(String acCode)
{
for(Accommodation ac:accommodations)
{
if(ac.getCode().equals(acCode))
{
return ac;
}
}
return null;
}
public Ticket searchTicket(String parkCode)
{
String ticket=parkCode.substring(2);
for(Ticket t:tickets)
{
if(t.getCode().equals("EN"+ticket))
return t;
}
return null;
}
public double getMaxPricePackA()
{
double max=0;
for(Package p:packages)
{
if(p.getAdultPrice()>max)
{
max=p.getAdultPrice();
}
}
return max;
}
public double getMaxPricePackC()
{
double max=0;
for(Package p:packages)
{
if(p.getChildrenPrice()>max)
{
max=p.getChildrenPrice();
}
}
return max;
}
public int getMinPricePackA()
{
double min=10000;
for(Package p:packages)
{
if(p.getAdultPrice()<min)
{
min=p.getAdultPrice();
}
}
return (int) min;
}
public double getMinPricePackC()
{
double min=10000;
for(Package p:packages)
{
if(p.getChildrenPrice()<min)
{
min=p.getChildrenPrice();
}
}
return min;
}
public int getMaxLengthPack()
{
int max=0;
for(Package p:packages)
{
if(p.getDays()>max)
{
max=p.getDays();
}
}
return max;
}
public double getMaxPriceParkA()
{
double max=0;
for(ThemePark p:parks)
{
if(p.getTicket().getAdultPrice()>max)
{
max=p.getTicket().getAdultPrice();
}
}
return max;
}
public double getMaxPriceParkC()
{
double max=0;
for(ThemePark p:parks)
{
if(p.getTicket().getChildrenPrice()>max)
{
max=p.getTicket().getChildrenPrice();
}
}
return max;
}
public ArrayList<Integer> getCategoriesSorted()
{
ArrayList<Integer> list=new ArrayList<Integer>();
for(int i=0;i<getAccommodations().size();i++)
{
if(!(list.contains(getAccommodations().get(i).getCategory())))
list.add(getAccommodations().get(i).getCategory());
}
ArrayList<Integer> aux=new ArrayList<Integer>();
for(int i=0;i<list.size();i++)
{
addSorted(list.get(i),aux);
}
for(int i=0;i<aux.size();i++)
{
list.set(i, aux.get(i));
}
return list;
}
private void addSorted(Integer integer, ArrayList<Integer> aux)
{
for(int i=0;i<aux.size();i++)
{
if(integer<aux.get(i))
{
aux.add(i,integer);
return ;
}
}
aux.add(integer);
}
public double getMaxPriceAc()
{
double max=0;
for(Accommodation a:getAccommodations())
{
if(a.getPrice()>max)
{
max=a.getPrice();
}
}
return max;
}
public ArrayList<Package> getPackagesRequested(String park, String acType, int maxPriceA, int minPriceA,
int maxPriceC, int minPriceC, int length)
{
ArrayList<Package> returned=new ArrayList<Package>();
for(Package p:packages)
{
int count=0;
if(park!=null)
{
if(p.getPark().getName().equals(park))
{
count++;
}
}
else
{
count++;
}
if(acType!=null)
{
if(p.getAc().getType().equals(acType))
{
count++;
}
}
else
{
count++;
}
if(p.getAdultPrice()<=maxPriceA && p.getAdultPrice()>=minPriceA)
{
count++;
}
if(p.getChildrenPrice()<=maxPriceC && p.getChildrenPrice()>=minPriceC)
{
count++;
}
if(p.getDays()>=length)
{
count++;
}
if(count==5)
{
returned.add(p);
}
}
return returned;
}
public void addPackageToPedido(PackageR p)
{
pedido.addPackage(p);
}
public void addThemeParkToPedido(ThemeParkR p)
{
pedido.addThemePark(p);
}
public void addAccommodationToPedido(AccommodationR a)
{
pedido.addAccommodation(a);
}
public void removePackageOfPedido(PackageR p)
{
pedido.removePackage(p);
}
public void removeThemeParkOfPedido(ThemeParkR p)
{
pedido.removeThemePark(p);
}
public void removeAccommodationOfPedido(AccommodationR a)
{
pedido.removeAccommodation(a);
}
public ArrayList<ThemePark> getThemeParksRequested(int minPriceA, int maxPriceA, int minPriceC, int maxPriceC)
{
ArrayList<ThemePark> returned=new ArrayList<ThemePark>();
for(ThemePark p:parks)
{
if(p.getTicket().getAdultPrice()>=minPriceA && p.getTicket().getAdultPrice()<=maxPriceA)
{
if(p.getTicket().getChildrenPrice()>=minPriceC && p.getTicket().getChildrenPrice()<=maxPriceC)
{
returned.add(p);
}
}
}
return returned;
}
public ArrayList<Accommodation> getAccommodationsRequested(String type, Integer category, boolean breakfast, int minPrice, int maxPrice)
{
ArrayList<Accommodation> ac=new ArrayList<Accommodation>();
int count=0;
for(Accommodation a:accommodations)
{
count=0;
if(type!=null)
{
if(a.getType().equals(type))
{
count++;
}
}
else
{
count++;
}
if(category!=null)
{
if(a.getCategory()==category)
{
count++;
}
}
else
{
count++;
}
if(a.getPrice()>=minPrice && a.getPrice()<=maxPrice)
{
count++;
}
if(breakfast)
{
if(a instanceof Hotel)
{
count++;
}
}
else
{
count++;
}
if(count==4)
{
ac.add(a);
}
}
return ac;
}
public Pedido getPedido()
{
return pedido;
}
public void clearPedido()
{
getPedido().getPackages().clear();
getPedido().getParks().clear();
getPedido().getAc().clear();
}
public void grabarPedido(String name, String surname, String id) throws IOException
{
String fileName=id.concat("_"+DateTimeFormatter.ofPattern("dd/MM/yyyy").format(LocalDate.now()))+".txt";
fileName=fileName.replace("/", "-");
String string=getPedido().getInfo(name, surname, id);
BufferedWriter w=new BufferedWriter(new FileWriter(fileName));
w.write(string);
w.close();
}
public ThemePark getParkDiscounted()
{
ThemePark t=null;
for(ThemePark p:parks)
{
if(p.isDiscount())
t=p;
}
return t;
}
public List<Package> getPackagesSortedByAdultPrice(ArrayList<Package> arrayList)
{
List<Package> list=arrayList;
List<Package> aux=new ArrayList<Package>();
Comparator c=new PackageComparatorByAdultPrice();
for(int i=0;i<list.size();i++)
{
addPackageSorted(list.get(i),aux,c);
}
for(int i=0;i<list.size();i++)
{
list.set(i, aux.get(i));
}
return list;
}
private void addPackageSorted(Package pack, List<Package> aux, Comparator<Package> c)
{
for(int i=0;i<aux.size();i++)
{
if(c.compare(pack, aux.get(i))>0)
{
aux.add(i,pack);
return ;
}
}
aux.add(pack);
}
public List<Package> getPackagesSortedByChildrenPrice(ArrayList<Package> arrayList)
{
List<Package> list=arrayList;
List<Package> aux=new ArrayList<Package>();
Comparator c=new PackageComparatorByChildrenPrice();
for(int i=0;i<list.size();i++)
{
addPackageSorted(list.get(i),aux,c);
}
for(int i=0;i<list.size();i++)
{
list.set(i, aux.get(i));
}
return list;
}
public List<Package> getPackagesSortedByName(ArrayList<Package> arrayList)
{
List<Package> list=arrayList;
List<Package> aux=new ArrayList<Package>();
Comparator c=new PackageComparatorByName();
for(int i=0;i<list.size();i++)
{
addPackageSorted(list.get(i),aux,c);
}
for(int i=0;i<list.size();i++)
{
list.set(i, aux.get(i));
}
return list;
}
public List<ThemePark> getParksSortedByAdultPrice(ArrayList<ThemePark> arrayList)
{
List<ThemePark> list=arrayList;
List<ThemePark> aux=new ArrayList<ThemePark>();
Comparator c=new ThemeParkComparatorByAdultPrice();
for(int i=0;i<list.size();i++)
{
addThemeParkSorted(list.get(i),aux,c);
}
for(int i=0;i<list.size();i++)
{
list.set(i, aux.get(i));
}
return list;
}
public List<ThemePark> getParksSortedByChildrenPrice(ArrayList<ThemePark> arrayList)
{
List<ThemePark> list=arrayList;
List<ThemePark> aux=new ArrayList<ThemePark>();
Comparator c=new ThemeParkComparatorByChildrenPrice();
for(int i=0;i<list.size();i++)
{
addThemeParkSorted(list.get(i),aux,c);
}
for(int i=0;i<list.size();i++)
{
list.set(i, aux.get(i));
}
return list;
}
private void addThemeParkSorted(ThemePark themePark, List<ThemePark> aux, Comparator c)
{
for(int i=0;i<aux.size();i++)
{
if(c.compare(themePark, aux.get(i))>0)
{
aux.add(i,themePark);
return ;
}
}
aux.add(themePark);
}
public List<ThemePark> getParksSortedByName(ArrayList<ThemePark> arrayList)
{
List<ThemePark> list=arrayList;
List<ThemePark> aux=new ArrayList<ThemePark>();
Comparator c=new ThemeParkComparatorByName();
for(int i=0;i<list.size();i++)
{
addThemeParkSorted(list.get(i),aux,c);
}
for(int i=0;i<list.size();i++)
{
list.set(i, aux.get(i));
}
return list;
}
public List<Accommodation> getAccommodationsSortedByName(ArrayList<Accommodation> arrayList)
{
List<Accommodation> list=arrayList;
List<Accommodation> aux=new ArrayList<Accommodation>();
Comparator c=new AccommodationComparatorByName();
for(int i=0;i<list.size();i++)
{
addAccommodationSorted(list.get(i),aux,c);
}
for(int i=0;i<list.size();i++)
{
list.set(i, aux.get(i));
}
return list;
}
private void addAccommodationSorted(Accommodation accommodation, List<Accommodation> aux, Comparator c)
{
for(int i=0;i<aux.size();i++)
{
if(c.compare(accommodation, aux.get(i))>0)
{
aux.add(i,accommodation);
return ;
}
}
aux.add(accommodation);
}
public List<Accommodation> getAccommodationsSortedByPrice(ArrayList<Accommodation> arrayList)
{
List<Accommodation> list=arrayList;
List<Accommodation> aux=new ArrayList<Accommodation>();
Comparator c=new AccommodationComparatorByPrice();
for(int i=0;i<list.size();i++)
{
addAccommodationSorted(list.get(i),aux,c);
}
for(int i=0;i<list.size();i++)
{
list.set(i, aux.get(i));
}
return list;
}
public List<Accommodation> getAccommodationsSortedByCategory(ArrayList<Accommodation> arrayList)
{
List<Accommodation> list=arrayList;
List<Accommodation> aux=new ArrayList<Accommodation>();
Comparator c=new AccommodationComparatorByCategory();
for(int i=0;i<list.size();i++)
{
addAccommodationSorted(list.get(i),aux,c);
}
for(int i=0;i<list.size();i++)
{
list.set(i, aux.get(i));
}
return list;
}
}
| 14,942 | 0.679494 | 0.676014 | 740 | 19.191893 | 22.159336 | 138 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.372973 | false | false | 1 |
ec849b5d7abaf02fa3d3a9e9e1df322db35c8116 | 858,993,509,222 | 26be270a249ff5f89f0ab1f1c53a0d0eb69d6dc2 | /egakat-core-services/src/main/java/com/egakat/core/services/crud/api/QueryByCodigoService.java | 780422003500c9d8987d244fbef1257ef938c1fe | [] | no_license | github-ek/egakat-core | https://github.com/github-ek/egakat-core | b02c84f12e9161e91487571a89d79e91fc8d1871 | a4fee2aef7e0bde39c18562ea337c3953ba1d24f | refs/heads/master | 2020-03-19T10:23:11.514000 | 2019-09-23T03:59:59 | 2019-09-23T03:59:59 | 136,365,642 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.egakat.core.services.crud.api;
import java.util.Optional;
import org.springframework.transaction.annotation.Transactional;
import com.egakat.core.domain.ObjectWithCode;
public interface QueryByCodigoService<M extends ObjectWithCode<ID>, ID> {
@Transactional(readOnly = true)
Optional<M> findByCodigo(String codigo);
} | UTF-8 | Java | 337 | java | QueryByCodigoService.java | Java | [] | null | [] | package com.egakat.core.services.crud.api;
import java.util.Optional;
import org.springframework.transaction.annotation.Transactional;
import com.egakat.core.domain.ObjectWithCode;
public interface QueryByCodigoService<M extends ObjectWithCode<ID>, ID> {
@Transactional(readOnly = true)
Optional<M> findByCodigo(String codigo);
} | 337 | 0.810089 | 0.810089 | 14 | 23.142857 | 25.491896 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 1 |
19c2c7e024010680097d6c25bf32a0e3883ff6bc | 23,192,823,404,284 | f649bf9d05fd0f7d44aa4c383e3321d4338caf46 | /src/main/java/com/crime/model/bean/CriminalInfo.java | d1c69174cbb6d6f90f0381d8297c691cf18ccbff | [] | no_license | syt123450/america-crime-backend | https://github.com/syt123450/america-crime-backend | 48e17e55874081f4c2caa2f20b31c3cb9428465d | 434f9e2fc7005f12b4d5a7f96e5733e7340b734f | refs/heads/master | 2020-03-17T03:01:42.897000 | 2018-05-21T07:21:17 | 2018-05-21T07:21:17 | 133,216,623 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.crime.model.bean;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Created by ss on 2018/5/12.
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CriminalInfo {
private int suspect;
private int arrested;
private int victim;
}
| UTF-8 | Java | 310 | java | CriminalInfo.java | Java | [
{
"context": "mport lombok.NoArgsConstructor;\n\n/**\n * Created by ss on 2018/5/12.\n */\n\n@Data\n@NoArgsConstructor\n@AllA",
"end": 139,
"score": 0.9975581765174866,
"start": 137,
"tag": "USERNAME",
"value": "ss"
}
] | null | [] | package com.crime.model.bean;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Created by ss on 2018/5/12.
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CriminalInfo {
private int suspect;
private int arrested;
private int victim;
}
| 310 | 0.748387 | 0.725806 | 19 | 15.315789 | 12.452235 | 33 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.368421 | false | false | 1 |
9620d2c7eedcb9f286596d1e7e6f1ad854e412d7 | 7,206,955,183,105 | fd402ae283b78e7e07c2e22f0e96fe8f53bf9a99 | /BetsJSF2-Hibernate/src/modelo/bean/MenuBean.java | f85e2073dfcd2b7b917d4d2056d2627f28a6b773 | [] | no_license | Itusil/BetsJSF-Hibernate | https://github.com/Itusil/BetsJSF-Hibernate | 288b2d40ab1d87ec4c172573710ec14fe74c5e88 | 0c17cca5b0f167ad5003016a0bbf4a9b37a26f21 | refs/heads/master | 2023-02-02T17:30:57.184000 | 2020-12-16T10:18:50 | 2020-12-16T10:18:50 | 320,537,413 | 0 | 0 | null | false | 2020-12-16T10:04:34 | 2020-12-11T10:12:26 | 2020-12-15T09:55:21 | 2020-12-16T10:04:34 | 13,349 | 0 | 0 | 0 | Java | false | false | package modelo.bean;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import org.primefaces.event.SelectEvent;
import businessLogic.BLFacade;
import businessLogic.BLFacadeImplementation;
import domain.Event;
import domain.Question;
import exceptions.EventFinished;
import exceptions.QuestionAlreadyExist;
public class MenuBean {
private Date fecha;
private Integer idEvento;
private Event evento;
private String preg;
private String minbet;
private BLFacade bl= new BLFacadeImplementation();
private List<Event> eventos=new ArrayList<Event>();
private List<Question> preguntas = new ArrayList<Question>();
public String getPreg() {
return preg;
}
public void setPreg(String preg) {
this.preg = preg;
}
public String getMinbet() {
return minbet;
}
public void setMinbet(String minbet) {
this.minbet = minbet;
}
public Event getEvento() {
return evento;
}
public void setEvento(Event evento) {
this.evento = evento;
}
public MenuBean() {
}
public List<Question> getPreguntas(){
return preguntas;
}
public List<Event> getEventos(){
return eventos;
}
public Date getFecha() {
return fecha;
}
public void setFecha(Date fecha) {
this.fecha = fecha;
}
public Integer getIdEvento() {
return idEvento;
}
public void setIdEvento(Integer idEvento) {
this.idEvento = idEvento;
}
public void onDateSelectMostrar(SelectEvent event) {
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage("Fecha escogida:"+this.getFecha().toString()));//event.getObject().toString())
}
public void onDateSelect(SelectEvent event) {
eventos=new ArrayList<Event>();
List<Event> j = bl.getEvents(getFecha());
Iterator<Event> jit = j.iterator();
while (jit.hasNext()) {
eventos.add(jit.next());
}
}
public void printPreguntas () {
int id_ = getIdEvento();
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage("Id:"+id_));//event.getObject().toString())
}
public void obtenerEventosFecha() {
this.eventos = bl.getEvents(fecha);
}
public void verPreguntas() {
Integer id_ = getIdEvento();
System.out.println("id: "+ id_);
List<Event> etos = getEventos();
Event e2 = null;
for(Event e: etos) {
if(e.getEventNumber()== id_) {
e2 = e;
}
}
try {
preguntas = e2.getQuestions();
}catch(NullPointerException e) {
e.printStackTrace();
}
}
public void anadirPregunta() {
float minimo = Float.parseFloat(getMinbet());
try {
bl.createQuestion(evento, preg, minimo);
this.refrescarEventos();
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage("Pregunta aņadida correctamente"));
} catch (EventFinished e) {
e.printStackTrace();
FacesContext.getCurrentInstance().addMessage("ok",
new FacesMessage("ERROR: El evento ya ha finalizado"));
} catch (QuestionAlreadyExist e) {
// TODO Auto-generated catch block
e.printStackTrace();
FacesContext.getCurrentInstance().addMessage("error",new FacesMessage("ERROR: Existe una pregunta con la misma descripcion"));
}
}
public void refrescarEventos() {
eventos=new ArrayList<Event>();
List<Event> j = bl.getEvents(getFecha());
Iterator<Event> jit = j.iterator();
while (jit.hasNext()) {
eventos.add(jit.next());
}
}
}
| ISO-8859-10 | Java | 3,463 | java | MenuBean.java | Java | [] | null | [] | package modelo.bean;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import org.primefaces.event.SelectEvent;
import businessLogic.BLFacade;
import businessLogic.BLFacadeImplementation;
import domain.Event;
import domain.Question;
import exceptions.EventFinished;
import exceptions.QuestionAlreadyExist;
public class MenuBean {
private Date fecha;
private Integer idEvento;
private Event evento;
private String preg;
private String minbet;
private BLFacade bl= new BLFacadeImplementation();
private List<Event> eventos=new ArrayList<Event>();
private List<Question> preguntas = new ArrayList<Question>();
public String getPreg() {
return preg;
}
public void setPreg(String preg) {
this.preg = preg;
}
public String getMinbet() {
return minbet;
}
public void setMinbet(String minbet) {
this.minbet = minbet;
}
public Event getEvento() {
return evento;
}
public void setEvento(Event evento) {
this.evento = evento;
}
public MenuBean() {
}
public List<Question> getPreguntas(){
return preguntas;
}
public List<Event> getEventos(){
return eventos;
}
public Date getFecha() {
return fecha;
}
public void setFecha(Date fecha) {
this.fecha = fecha;
}
public Integer getIdEvento() {
return idEvento;
}
public void setIdEvento(Integer idEvento) {
this.idEvento = idEvento;
}
public void onDateSelectMostrar(SelectEvent event) {
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage("Fecha escogida:"+this.getFecha().toString()));//event.getObject().toString())
}
public void onDateSelect(SelectEvent event) {
eventos=new ArrayList<Event>();
List<Event> j = bl.getEvents(getFecha());
Iterator<Event> jit = j.iterator();
while (jit.hasNext()) {
eventos.add(jit.next());
}
}
public void printPreguntas () {
int id_ = getIdEvento();
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage("Id:"+id_));//event.getObject().toString())
}
public void obtenerEventosFecha() {
this.eventos = bl.getEvents(fecha);
}
public void verPreguntas() {
Integer id_ = getIdEvento();
System.out.println("id: "+ id_);
List<Event> etos = getEventos();
Event e2 = null;
for(Event e: etos) {
if(e.getEventNumber()== id_) {
e2 = e;
}
}
try {
preguntas = e2.getQuestions();
}catch(NullPointerException e) {
e.printStackTrace();
}
}
public void anadirPregunta() {
float minimo = Float.parseFloat(getMinbet());
try {
bl.createQuestion(evento, preg, minimo);
this.refrescarEventos();
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage("Pregunta aņadida correctamente"));
} catch (EventFinished e) {
e.printStackTrace();
FacesContext.getCurrentInstance().addMessage("ok",
new FacesMessage("ERROR: El evento ya ha finalizado"));
} catch (QuestionAlreadyExist e) {
// TODO Auto-generated catch block
e.printStackTrace();
FacesContext.getCurrentInstance().addMessage("error",new FacesMessage("ERROR: Existe una pregunta con la misma descripcion"));
}
}
public void refrescarEventos() {
eventos=new ArrayList<Event>();
List<Event> j = bl.getEvents(getFecha());
Iterator<Event> jit = j.iterator();
while (jit.hasNext()) {
eventos.add(jit.next());
}
}
}
| 3,463 | 0.709705 | 0.708839 | 150 | 22.08 | 20.41683 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.8 | false | false | 1 |
0290734217dbab345dfaf5a84549c01d5b86e289 | 18,253,611,011,134 | 0581dd75bbaaaa90a42fd62c352170b2ca6d9ae6 | /src/java/mx/org/kaana/kajool/enums/EEncabezadosCargaAlumno.java | 9b28f58144669db8648abbff136b2d3c4941b84f | [] | no_license | TeamDeveloper2016/jom | https://github.com/TeamDeveloper2016/jom | a6cebf86f5ece8b72becdd11204b3a2affbb8e5c | a1131a741255689cd82c4ef4c40d15b675062e0c | refs/heads/master | 2020-10-02T05:50:06.105000 | 2020-07-22T20:24:13 | 2020-07-22T20:24:13 | 227,715,196 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package mx.org.kaana.kajool.enums;
/**
*@company KAANA
*@project KAJOOL (Control system polls)
*@date 10/04/2015
*@time 11:19:02 AM
*@author Team Developer 2016 <team.developer@kaana.org.mx>
*/
public enum EEncabezadosCargaAlumno {
CLAVE_PLANTEL ("Clave del plantel"),
MATRICULA ("Matrícula"),
NOMBRES ("Nombre completo"),
PRIMER_APELLIDO ("Primer apellido"),
SEGUNDO_APELLIDO ("Segundo apellido"),
CURP ("CURP"),
SEXO ("Sexo"),
FECHA_NACIMIENTO ("Fecha de nacimiento"),
LUGAR_NACIMIENTO ("Lugar de nacimiento"),
ENTIDAD ("Entidad"),
MUNICICPIO ("Municipio"),
C_P ("C.P."),
CORREO_ELECTRONICO ("Correo electrónico"),
NUMERO_TELEFONICO ("Número de teléfono"),
LENGUA_INDIGENA ("Lengua indígena"),
DISCAPACIDAD ("Tipo de discapacidad"),
PLAN_DE_ESTUDIOS ("Plan de estudios al que está inscrito"),
MES_INSCRIPCION ("Mes"),
ANIO_INSCRIPCION ("Año de ingreso"),
MATERIAS ("Materias"),
ESTATUS_ASIGNATURAS ("Estatus de las asignaturas"),
CALIFICACION ("Calificaciones"),
BECA ("Recibe beca")
;
String encabezado;
private EEncabezadosCargaAlumno(String encabezado) {
this.encabezado=encabezado;
}
public String getEncabezado() {
return encabezado;
}
}
| ISO-8859-1 | Java | 1,408 | java | EEncabezadosCargaAlumno.java | Java | [
{
"context": " *@date 10/04/2015\r\n *@time 11:19:02 AM\r\n *@author Team Developer 2016 <team.developer@kaana.org.mx>\r\n */\r\npublic e",
"end": 168,
"score": 0.9808188676834106,
"start": 154,
"tag": "NAME",
"value": "Team Developer"
},
{
"context": "@time 11:19:02 AM\r\n *@author ... | null | [] | package mx.org.kaana.kajool.enums;
/**
*@company KAANA
*@project KAJOOL (Control system polls)
*@date 10/04/2015
*@time 11:19:02 AM
*@author <NAME> 2016 <<EMAIL>>
*/
public enum EEncabezadosCargaAlumno {
CLAVE_PLANTEL ("Clave del plantel"),
MATRICULA ("Matrícula"),
NOMBRES ("Nombre completo"),
PRIMER_APELLIDO ("Primer apellido"),
SEGUNDO_APELLIDO ("Segundo apellido"),
CURP ("CURP"),
SEXO ("Sexo"),
FECHA_NACIMIENTO ("Fecha de nacimiento"),
LUGAR_NACIMIENTO ("Lugar de nacimiento"),
ENTIDAD ("Entidad"),
MUNICICPIO ("Municipio"),
C_P ("C.P."),
CORREO_ELECTRONICO ("Correo electrónico"),
NUMERO_TELEFONICO ("Número de teléfono"),
LENGUA_INDIGENA ("Lengua indígena"),
DISCAPACIDAD ("Tipo de discapacidad"),
PLAN_DE_ESTUDIOS ("Plan de estudios al que está inscrito"),
MES_INSCRIPCION ("Mes"),
ANIO_INSCRIPCION ("Año de ingreso"),
MATERIAS ("Materias"),
ESTATUS_ASIGNATURAS ("Estatus de las asignaturas"),
CALIFICACION ("Calificaciones"),
BECA ("Recibe beca")
;
String encabezado;
private EEncabezadosCargaAlumno(String encabezado) {
this.encabezado=encabezado;
}
public String getEncabezado() {
return encabezado;
}
}
| 1,380 | 0.608137 | 0.595289 | 45 | 29.133333 | 17.681881 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.311111 | false | false | 1 |
e0393b27b5973137ce640fbcf1bb3cd873a81f2d | 22,170,621,248,578 | 098bf0dca92c59c70809b095013957efb9e5aaf4 | /bookstore-feignclient-service/src/main/java/com/learning/bookstore/web/CreatePaymentRequest.java | a0b0c425dafbbab2854a0616e268b68b9c8552bc | [] | no_license | liuzhenxin/bookstore-app | https://github.com/liuzhenxin/bookstore-app | 2c8a8bffaf59c02523de90d9da5e071dff1ff6d0 | 0e4e4627ca19a68c5f6aa5fb7185aa148285e9a9 | refs/heads/main | 2023-07-15T18:03:28.843000 | 2021-08-23T04:23:53 | 2021-08-23T04:23:53 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.learning.bookstore.web;
import lombok.Builder;
import lombok.Getter;
@Getter
@Builder
public class CreatePaymentRequest {
private int amount;
private String currency;
private String paymentMethodId;
}
| UTF-8 | Java | 227 | java | CreatePaymentRequest.java | Java | [] | null | [] | package com.learning.bookstore.web;
import lombok.Builder;
import lombok.Getter;
@Getter
@Builder
public class CreatePaymentRequest {
private int amount;
private String currency;
private String paymentMethodId;
}
| 227 | 0.77533 | 0.77533 | 12 | 17.916666 | 13.462654 | 35 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 1 |
2b0264e00d0043974f306b9259fb766d0163038c | 11,613,591,597,121 | 7d4fb7bc2c8ba95b1bb20740bae2b956aec551ab | /app/src/main/java/com/example/bookmytable/DisplayRestaurants.java | 068b45fe055cb158fb9807f78b73821e078a7e2b | [] | no_license | dvenkatesalu/BookMyTable | https://github.com/dvenkatesalu/BookMyTable | 50fdfb18364167c021b9471d31de49938a9fc728 | 561247451aabac19e9715e7f2e0deb738dc74051 | refs/heads/master | 2022-01-13T02:51:05.114000 | 2019-05-14T07:19:43 | 2019-05-14T07:19:43 | 183,526,808 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.bookmytable;
import android.content.Intent;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
public class DisplayRestaurants extends AppCompatActivity {
private ListView mListView;
private static final String API_KEY = "AIzaSyDi1OagTMGaVbLZb5UW8rHpKTWkmgaMZK4";
private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place";
private static final String TYPE_AUTOCOMPLETE = "/autocomplete";
private static final String TYPE_DETAILS = "/details";
private static final String TYPE_SEARCH = "/nearbysearch";
private static final String OUT_JSON = "/json?";
private static final String LOG_TAG = "ListRest";
private static String[] restname = new String[]{};
private static String[] restLocation = new String[]{};
private static Integer[] restRating = new Integer[]{};
ArrayList<RestaurantBO> restaurantBO;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_restaurant);
Intent intent = getIntent();
String longitude = intent.getStringExtra("long");
String latitude = intent.getStringExtra("lat");
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Double lng = Double.parseDouble(longitude);
Double lat = Double.parseDouble(latitude);
int radius = 1000;
ArrayList<RestaurantBO> list = search(lat, lng, radius);
if (list != null)
{
mListView = (ListView) findViewById(R.id.listView);
CustomAdapter adapter = new CustomAdapter(this,list);
mListView.setAdapter(adapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
LinearLayout ll = (LinearLayout) view;
TextView tv = (TextView) ll.findViewById(R.id.tv);
TextView tv1 = (TextView) ll.findViewById(R.id.tv1);
RatingBar rate = (RatingBar)ll.findViewById(R.id.listitemrating);
final String text = tv.getText().toString();
final String location = tv1.getText().toString();
final Float ratingOfRestaurant = rate.getRating();
setRestaurantToOwner(text,location,ratingOfRestaurant);
Toast.makeText(getApplicationContext(), "Restaurant added to Database!", Toast.LENGTH_SHORT).show();
startActivity(new Intent(DisplayRestaurants.this,MainActivity.class));
}
});
}
}
public void setRestaurantToOwner( String resName, String loc, Float ratings ){
Toast.makeText(DisplayRestaurants.this, "Inside add resName to db.",
Toast.LENGTH_SHORT).show();
FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseDatabase database = FirebaseDatabase.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
String key = user.getDisplayName() + "_" + user.getUid();
String resId = resName + key;
DatabaseReference keyRef =
database.getReference("restaurants");//.child(resId);
keyRef.child("name").setValue(resName);
keyRef.child("address").setValue(loc);
keyRef.child("rating").setValue(ratings);
keyRef.child("ownerId").setValue(key);
keyRef.child("reference").setValue("");
keyRef.child("resId").setValue(resId);
}
public static ArrayList<RestaurantBO> search(double lat, double lng, int radius) {
ArrayList<RestaurantBO> resultList = null;
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
StringBuilder sb = new StringBuilder(PLACES_API_BASE);
sb.append(TYPE_SEARCH);
sb.append(OUT_JSON);
sb.append("location=" + String.valueOf(lat) + "," + String.valueOf(lng));
sb.append("&radius=" + String.valueOf(radius));
sb.append("&type=restaurant");
sb.append("&key=" + API_KEY);
URL url = new URL(sb.toString());
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error processing Places API URL", e);
return resultList;
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to Places API", e);
return resultList;
} finally {
if (conn != null) {
conn.disconnect();
}
}
try {
// Create a JSON object hierarchy from the results
JSONObject jsonObj = new JSONObject(jsonResults.toString());
JSONArray predsJsonArray = jsonObj.getJSONArray("results");
// Extract the descriptions from the results
resultList = new ArrayList<RestaurantBO>(predsJsonArray.length());
for (int i = 0; i < predsJsonArray.length(); i++) {
RestaurantBO place = new RestaurantBO();
place.reference = predsJsonArray.getJSONObject(i).getString("reference");
place.name = predsJsonArray.getJSONObject(i).getString("name");
place.rating = predsJsonArray.getJSONObject(i).getInt("rating");
place.address = predsJsonArray.getJSONObject(i).getString("vicinity");
resultList.add(place);
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Error processing JSON results", e);
}
return resultList;
}
} | UTF-8 | Java | 6,891 | java | DisplayRestaurants.java | Java | [
{
"context": "tView;\n private static final String API_KEY = \"AIzaSyDi1OagTMGaVbLZb5UW8rHpKTWkmgaMZK4\";\n\n private static final String PLACES_API_BAS",
"end": 1068,
"score": 0.9996805787086487,
"start": 1029,
"tag": "KEY",
"value": "AIzaSyDi1OagTMGaVbLZb5UW8rHpKTWkmgaMZK4"
}
] | null | [] | package com.example.bookmytable;
import android.content.Intent;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
public class DisplayRestaurants extends AppCompatActivity {
private ListView mListView;
private static final String API_KEY = "<KEY>";
private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place";
private static final String TYPE_AUTOCOMPLETE = "/autocomplete";
private static final String TYPE_DETAILS = "/details";
private static final String TYPE_SEARCH = "/nearbysearch";
private static final String OUT_JSON = "/json?";
private static final String LOG_TAG = "ListRest";
private static String[] restname = new String[]{};
private static String[] restLocation = new String[]{};
private static Integer[] restRating = new Integer[]{};
ArrayList<RestaurantBO> restaurantBO;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_restaurant);
Intent intent = getIntent();
String longitude = intent.getStringExtra("long");
String latitude = intent.getStringExtra("lat");
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Double lng = Double.parseDouble(longitude);
Double lat = Double.parseDouble(latitude);
int radius = 1000;
ArrayList<RestaurantBO> list = search(lat, lng, radius);
if (list != null)
{
mListView = (ListView) findViewById(R.id.listView);
CustomAdapter adapter = new CustomAdapter(this,list);
mListView.setAdapter(adapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
LinearLayout ll = (LinearLayout) view;
TextView tv = (TextView) ll.findViewById(R.id.tv);
TextView tv1 = (TextView) ll.findViewById(R.id.tv1);
RatingBar rate = (RatingBar)ll.findViewById(R.id.listitemrating);
final String text = tv.getText().toString();
final String location = tv1.getText().toString();
final Float ratingOfRestaurant = rate.getRating();
setRestaurantToOwner(text,location,ratingOfRestaurant);
Toast.makeText(getApplicationContext(), "Restaurant added to Database!", Toast.LENGTH_SHORT).show();
startActivity(new Intent(DisplayRestaurants.this,MainActivity.class));
}
});
}
}
public void setRestaurantToOwner( String resName, String loc, Float ratings ){
Toast.makeText(DisplayRestaurants.this, "Inside add resName to db.",
Toast.LENGTH_SHORT).show();
FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseDatabase database = FirebaseDatabase.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
String key = user.getDisplayName() + "_" + user.getUid();
String resId = resName + key;
DatabaseReference keyRef =
database.getReference("restaurants");//.child(resId);
keyRef.child("name").setValue(resName);
keyRef.child("address").setValue(loc);
keyRef.child("rating").setValue(ratings);
keyRef.child("ownerId").setValue(key);
keyRef.child("reference").setValue("");
keyRef.child("resId").setValue(resId);
}
public static ArrayList<RestaurantBO> search(double lat, double lng, int radius) {
ArrayList<RestaurantBO> resultList = null;
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
StringBuilder sb = new StringBuilder(PLACES_API_BASE);
sb.append(TYPE_SEARCH);
sb.append(OUT_JSON);
sb.append("location=" + String.valueOf(lat) + "," + String.valueOf(lng));
sb.append("&radius=" + String.valueOf(radius));
sb.append("&type=restaurant");
sb.append("&key=" + API_KEY);
URL url = new URL(sb.toString());
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error processing Places API URL", e);
return resultList;
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to Places API", e);
return resultList;
} finally {
if (conn != null) {
conn.disconnect();
}
}
try {
// Create a JSON object hierarchy from the results
JSONObject jsonObj = new JSONObject(jsonResults.toString());
JSONArray predsJsonArray = jsonObj.getJSONArray("results");
// Extract the descriptions from the results
resultList = new ArrayList<RestaurantBO>(predsJsonArray.length());
for (int i = 0; i < predsJsonArray.length(); i++) {
RestaurantBO place = new RestaurantBO();
place.reference = predsJsonArray.getJSONObject(i).getString("reference");
place.name = predsJsonArray.getJSONObject(i).getString("name");
place.rating = predsJsonArray.getJSONObject(i).getInt("rating");
place.address = predsJsonArray.getJSONObject(i).getString("vicinity");
resultList.add(place);
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Error processing JSON results", e);
}
return resultList;
}
} | 6,857 | 0.636192 | 0.633435 | 174 | 38.609196 | 27.69014 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.787356 | false | false | 1 |
0ec65bb5d0815208c1f939daeeeebbad73a02459 | 25,048,249,273,983 | d0f42c649f6cce87de7dd622e7d3b001e59fba65 | /src/main/java/dminter/utils/Xutils.java | fbe5a6c87f179741fc11ae95a1950947ab18de2e | [] | no_license | Dminter/QiqiGo | https://github.com/Dminter/QiqiGo | c8e54addcfb8e831f57d8db9fbb252c66385d752 | d06c48337d74161d2fa75cfaea7d5249edbf3bcb | refs/heads/master | 2021-01-19T17:05:50.912000 | 2017-08-22T09:50:28 | 2017-08-22T09:50:28 | 101,047,915 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dminter.utils;
public class Xutils {
public static void debug(Object obj){
System.out.println(obj);
}
}
| UTF-8 | Java | 130 | java | Xutils.java | Java | [] | null | [] | package dminter.utils;
public class Xutils {
public static void debug(Object obj){
System.out.println(obj);
}
}
| 130 | 0.653846 | 0.653846 | 7 | 17.571428 | 14.927033 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 1 |
813374eda91425bdfb0b1803e9b4cf24f1c2b0a2 | 3,332,894,675,763 | 611ee05cae29428f2bbbdb37fc0f323f79880a20 | /algorithms/src/main/java/org/tcse/algorithms/LRUCache.java | 7bf21ad3377af7c24922ff2d505c3519fc156b8f | [] | no_license | coderfengyun/learn | https://github.com/coderfengyun/learn | fefd5df397eedea72cd1b721ec653e9c3420cbce | 915491968164a3afc2ed7dafda6f6228eb57dde8 | refs/heads/main | 2022-05-02T19:31:23.497000 | 2021-12-24T08:49:40 | 2021-12-24T08:49:40 | 25,959,800 | 1 | 0 | null | false | 2021-12-24T08:49:41 | 2014-10-30T07:36:18 | 2021-12-15T04:02:36 | 2021-12-24T08:49:40 | 190 | 0 | 0 | 0 | Java | false | false | package org.tcse.algorithms;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.Map;
import org.junit.Test;
public class LRUCache{
@Test
public void test() {
Solution1 cache = new Solution1(2);
cache.set(2, 1);
cache.set(1, 1);
cache.get(2);
cache.set(4, 1);
cache.get(1);
cache.get(2);
}
}
class Solution1 {
private Map<Integer, ListIterator<Integer>> keyToIterator;
private Map<Integer, Integer> valToKey;
private LinkedList<Integer> list;
private int capacity;
public Solution1(int capacity) {
this.capacity = capacity;
list = new LinkedList<Integer>();
this.keyToIterator = new HashMap<Integer, ListIterator<Integer>>();
this.valToKey = new HashMap<Integer, Integer>(capacity);
}
public synchronized int get(int key) {
if (!keyToIterator.containsKey(key)) {
return -1;
}
ListIterator<Integer> valIterator = keyToIterator.get(key);
int result = valIterator.next();
valIterator.remove();
this.list.addFirst(result);
keyToIterator.put(key, this.list.listIterator(0));
return result;
}
public synchronized void set(int key, int value) {
if (keyToIterator.containsKey(key)) {
ListIterator<Integer> itr = keyToIterator.get(key);
this.valToKey.remove(itr.next());
itr.remove();
} else if (this.list.size() == this.capacity) {
int tailKey = this.valToKey.get(this.list.removeLast());
this.keyToIterator.remove(tailKey);
}
this.list.addFirst(value);
this.keyToIterator.put(key, this.list.listIterator(0));
this.valToKey.put(value, key);
}
}
| UTF-8 | Java | 1,579 | java | LRUCache.java | Java | [] | null | [] | package org.tcse.algorithms;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.Map;
import org.junit.Test;
public class LRUCache{
@Test
public void test() {
Solution1 cache = new Solution1(2);
cache.set(2, 1);
cache.set(1, 1);
cache.get(2);
cache.set(4, 1);
cache.get(1);
cache.get(2);
}
}
class Solution1 {
private Map<Integer, ListIterator<Integer>> keyToIterator;
private Map<Integer, Integer> valToKey;
private LinkedList<Integer> list;
private int capacity;
public Solution1(int capacity) {
this.capacity = capacity;
list = new LinkedList<Integer>();
this.keyToIterator = new HashMap<Integer, ListIterator<Integer>>();
this.valToKey = new HashMap<Integer, Integer>(capacity);
}
public synchronized int get(int key) {
if (!keyToIterator.containsKey(key)) {
return -1;
}
ListIterator<Integer> valIterator = keyToIterator.get(key);
int result = valIterator.next();
valIterator.remove();
this.list.addFirst(result);
keyToIterator.put(key, this.list.listIterator(0));
return result;
}
public synchronized void set(int key, int value) {
if (keyToIterator.containsKey(key)) {
ListIterator<Integer> itr = keyToIterator.get(key);
this.valToKey.remove(itr.next());
itr.remove();
} else if (this.list.size() == this.capacity) {
int tailKey = this.valToKey.get(this.list.removeLast());
this.keyToIterator.remove(tailKey);
}
this.list.addFirst(value);
this.keyToIterator.put(key, this.list.listIterator(0));
this.valToKey.put(value, key);
}
}
| 1,579 | 0.71121 | 0.700443 | 63 | 24.063492 | 19.18984 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.047619 | false | false | 1 |
995bbaa5db8bcae1c7f61cbf8c69c18756f1015f | 3,951,369,930,724 | b0b4335c8cf37c63e587e73711291eed57db6706 | /ProgramA.java | cf2a8a31ff965130b5308a7997934bb4feafaf5c | [] | no_license | ddpuga/DAGGS_pr3ej2 | https://github.com/ddpuga/DAGGS_pr3ej2 | b2e50c2f98d6181a94f996549b14b722d4629491 | ea9c77e77748a687e484cd7fa75e80c9cef69a5c | refs/heads/master | 2020-09-03T21:42:04.459000 | 2019-11-04T19:35:11 | 2019-11-04T19:35:11 | 219,578,922 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class ProgramA extends Program{
boolean end = false;
public void concreteRun(){
try{
System.out.println("[START] Program A");
Thread.sleep(10);
System.out.println("[END] Program A");
}catch(InterruptedException e){ throw new RuntimeException(e);}
}
} | UTF-8 | Java | 311 | java | ProgramA.java | Java | [] | null | [] |
public class ProgramA extends Program{
boolean end = false;
public void concreteRun(){
try{
System.out.println("[START] Program A");
Thread.sleep(10);
System.out.println("[END] Program A");
}catch(InterruptedException e){ throw new RuntimeException(e);}
}
} | 311 | 0.617363 | 0.610932 | 12 | 23.916666 | 21.092884 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 1 |
ec27fac798e5b2f008dbb52bc4c3370c8f74f34c | 27,857,157,952,382 | aeb68fa06f4e0689876643cbde67198eb30a86be | /src/main/java/Controllers/ActivitiesController.java | 9a977c9942b7aa0bc32cf27ea909d2e51916f035 | [] | no_license | ashb02/Coursework | https://github.com/ashb02/Coursework | e32de2de237651c9b3a3f714f71bfa6352112274 | 2320fb12d9960d52ccc175d67c270c51b34ceefa | refs/heads/master | 2022-07-29T08:08:11.170000 | 2020-01-27T10:27:40 | 2020-01-27T10:27:40 | 191,759,164 | 0 | 0 | null | false | 2022-07-07T22:11:32 | 2019-06-13T12:30:55 | 2020-01-27T10:27:58 | 2022-07-07T22:11:30 | 79 | 0 | 0 | 3 | Java | false | false | package Controllers;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import static Server.Main.db;
public class ActivitiesController
{
//Outputs the items in the Actvities table
public static void listActivities()
{
try
{
PreparedStatement ps = db.prepareStatement("SELECT ActivityID, LocationID, ActivityName, Description, Cost, Address, Website");
ResultSet results = ps.executeQuery();
while (results.next()) //returns the next record until there are no more values in the column
{
int ActivityID = results.getInt(1);
int LocationID = results.getInt(2);
String ActivityName = results.getString(3);
String Description = results.getString(4);
String Cost = results.getString(5);
String Address = results.getString(6);
String Website = results.getString(7);
System.out.println(ActivityID + " " + LocationID + " " + ActivityName + " " + Description + " " + Cost + " " + Address + " " + Website);
}
}
catch (Exception exception) //if an error occurs returns an error message
{
System.out.println("Database error: " + exception.getMessage());
}
}
//Adds a record to the Activities table
public static void insertActivities(int ActivityID, int LocationID, String ActivityName, String Description, String Cost, String Address, String Website)
{
try
{
PreparedStatement ps = db.prepareStatement("INSERT INTO Activities (ActivityID, LocationID, ActivityName, Description, Cost, Address, Website) VALUES (?, ?, ?, ?, ?, ?, ?");
//contain the values to be added through the SQL statement in place of the ?s
ps.setInt(1, ActivityID);
ps.setInt(2, LocationID);
ps.setString(3, ActivityName);
ps.setString(4, Description);
ps.setString(5, Cost);
ps.setString(6, Address);
ps.setString(7, Website);
ps.executeUpdate(); //executes the SQL statement in the PreparedStatement
System.out.println("Record added to Activities");
}
catch (Exception exception) //if an error occurs returns an error message
{
System.out.println("Database error: " + exception.getMessage());
}
}
//Changes a record within the Activities table
public static void updateActivities(int ActivityID, int LocationID, String ActivityName, String Description, String Cost, String Address, String Website)
{
try
{
PreparedStatement ps = db.prepareStatement("UPDATE Activities SET ActivityID = ?, LocationID = ?, ActivityName = ?, Description = ?, Cost = ?, Address = ?, Website = ?");
//contain the values to be changed through the SQL statement in place of the ?s
ps.setInt(1, ActivityID);
ps.setInt(2, LocationID);
ps.setString(3, ActivityName);
ps.setString(4, Description);
ps.setString(5, Cost);
ps.setString(6, Address);
ps.setString(7, Website);
ps.executeUpdate(); //executes the SQL statement in the PreparedStatement
}
catch(Exception exception) //if an error occurs returns an error message
{
System.out.println("Database error: " + exception.getMessage());
}
}
//Deletes a record from the Activities table
public static void deleteActivity(int ActivityID)
{
try
{
PreparedStatement ps = db.prepareStatement("DELETE FROM Activities SET ActivityID = ?");
ps.setInt(1, ActivityID);
ps.executeUpdate();
}
catch(Exception exception)
{
System.out.println("Database error: " + exception.getMessage());
}
}
} | UTF-8 | Java | 4,289 | java | ActivitiesController.java | Java | [] | null | [] | package Controllers;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import static Server.Main.db;
public class ActivitiesController
{
//Outputs the items in the Actvities table
public static void listActivities()
{
try
{
PreparedStatement ps = db.prepareStatement("SELECT ActivityID, LocationID, ActivityName, Description, Cost, Address, Website");
ResultSet results = ps.executeQuery();
while (results.next()) //returns the next record until there are no more values in the column
{
int ActivityID = results.getInt(1);
int LocationID = results.getInt(2);
String ActivityName = results.getString(3);
String Description = results.getString(4);
String Cost = results.getString(5);
String Address = results.getString(6);
String Website = results.getString(7);
System.out.println(ActivityID + " " + LocationID + " " + ActivityName + " " + Description + " " + Cost + " " + Address + " " + Website);
}
}
catch (Exception exception) //if an error occurs returns an error message
{
System.out.println("Database error: " + exception.getMessage());
}
}
//Adds a record to the Activities table
public static void insertActivities(int ActivityID, int LocationID, String ActivityName, String Description, String Cost, String Address, String Website)
{
try
{
PreparedStatement ps = db.prepareStatement("INSERT INTO Activities (ActivityID, LocationID, ActivityName, Description, Cost, Address, Website) VALUES (?, ?, ?, ?, ?, ?, ?");
//contain the values to be added through the SQL statement in place of the ?s
ps.setInt(1, ActivityID);
ps.setInt(2, LocationID);
ps.setString(3, ActivityName);
ps.setString(4, Description);
ps.setString(5, Cost);
ps.setString(6, Address);
ps.setString(7, Website);
ps.executeUpdate(); //executes the SQL statement in the PreparedStatement
System.out.println("Record added to Activities");
}
catch (Exception exception) //if an error occurs returns an error message
{
System.out.println("Database error: " + exception.getMessage());
}
}
//Changes a record within the Activities table
public static void updateActivities(int ActivityID, int LocationID, String ActivityName, String Description, String Cost, String Address, String Website)
{
try
{
PreparedStatement ps = db.prepareStatement("UPDATE Activities SET ActivityID = ?, LocationID = ?, ActivityName = ?, Description = ?, Cost = ?, Address = ?, Website = ?");
//contain the values to be changed through the SQL statement in place of the ?s
ps.setInt(1, ActivityID);
ps.setInt(2, LocationID);
ps.setString(3, ActivityName);
ps.setString(4, Description);
ps.setString(5, Cost);
ps.setString(6, Address);
ps.setString(7, Website);
ps.executeUpdate(); //executes the SQL statement in the PreparedStatement
}
catch(Exception exception) //if an error occurs returns an error message
{
System.out.println("Database error: " + exception.getMessage());
}
}
//Deletes a record from the Activities table
public static void deleteActivity(int ActivityID)
{
try
{
PreparedStatement ps = db.prepareStatement("DELETE FROM Activities SET ActivityID = ?");
ps.setInt(1, ActivityID);
ps.executeUpdate();
}
catch(Exception exception)
{
System.out.println("Database error: " + exception.getMessage());
}
}
} | 4,289 | 0.558638 | 0.553509 | 107 | 39.093456 | 42.066376 | 189 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.850467 | false | false | 1 |
839fbe2e627bfb0efbb90833ec1ac8db603bdab9 | 29,892,972,443,780 | 7268aa4e4efebe36288533e6efb97b5336ffd4a9 | /W10D1/src/vjezbe/Task1.java | a9b19631353d4c4ed1d56714255e7264a47554cf | [] | no_license | mladen91/vjezbe2 | https://github.com/mladen91/vjezbe2 | 1432ba1c3616518c1809db2b92e9c20be0b3a5ad | 0c392174cb46dad73bbcd72d9774b8fca6720ad4 | refs/heads/master | 2021-01-10T06:07:23.552000 | 2015-08-12T15:29:51 | 2015-08-12T15:29:51 | 36,082,522 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package vjezbe;
import java.awt.Component;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import javax.swing.JComponent;
public class Task1 {
public static <T> void printAll(Collection<T> coll) {
System.out.println(coll);
}
public static <T> int countOccurences(Collection<T> coll, T num) {
int counter = 0;
Iterator<T> iter = coll.iterator();
while (iter.hasNext()) {
if (iter.next().equals(num)) {
counter++;
}
}
return counter;
}
public static <T extends JComponent> void printComponentInfo(Component c) {
System.out.println("Width: " + c.getWidth() + "Height " + c.getHeight()
+ " X: " + c.getX() + " Y: " + c.getY());
}
public static <T> void printType(Collection<T> coll) {
if (coll instanceof List) {
System.out.println("List");
} else if (coll instanceof Map) {
System.out.println("Map");
} else if (coll instanceof Set) {
System.out.println("Set");
}
}
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
TreeSet<Integer> set = new TreeSet<Integer>();
list.add(2);
list.add(3);
list.add(1);
ArrayList<String> list2 = new ArrayList<String>();
list2.add("A");
printAll(list);
printAll(list2);
System.out.println(countOccurences(list, 2));
printType(set);
}
}
| UTF-8 | Java | 1,430 | java | Task1.java | Java | [] | null | [] | package vjezbe;
import java.awt.Component;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import javax.swing.JComponent;
public class Task1 {
public static <T> void printAll(Collection<T> coll) {
System.out.println(coll);
}
public static <T> int countOccurences(Collection<T> coll, T num) {
int counter = 0;
Iterator<T> iter = coll.iterator();
while (iter.hasNext()) {
if (iter.next().equals(num)) {
counter++;
}
}
return counter;
}
public static <T extends JComponent> void printComponentInfo(Component c) {
System.out.println("Width: " + c.getWidth() + "Height " + c.getHeight()
+ " X: " + c.getX() + " Y: " + c.getY());
}
public static <T> void printType(Collection<T> coll) {
if (coll instanceof List) {
System.out.println("List");
} else if (coll instanceof Map) {
System.out.println("Map");
} else if (coll instanceof Set) {
System.out.println("Set");
}
}
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
TreeSet<Integer> set = new TreeSet<Integer>();
list.add(2);
list.add(3);
list.add(1);
ArrayList<String> list2 = new ArrayList<String>();
list2.add("A");
printAll(list);
printAll(list2);
System.out.println(countOccurences(list, 2));
printType(set);
}
}
| 1,430 | 0.665734 | 0.659441 | 67 | 20.343283 | 19.812218 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.626866 | false | false | 1 |
4c6652219eb4326f9d378dde03d936f72664fe74 | 27,479,200,795,008 | fc000ac54855b7abdd3d6e8ef6ab4ec200ecf36f | /app/src/main/java/com/image/characterrecognition/module/MainActivity.java | 1662f6da26e1a85d5c1feccac683e89b678b54d8 | [] | no_license | zhangjilei106787/CharacterRecognition | https://github.com/zhangjilei106787/CharacterRecognition | b823a8756cfb74f9c204e26955c7853cd9562ff8 | 7f35a913aef0e6d1139cec7f0c578f6c6370a04a | refs/heads/master | 2022-11-13T01:38:16.714000 | 2020-07-13T09:38:12 | 2020-07-13T09:38:12 | 279,259,234 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.image.characterrecognition.module;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.image.characterrecognition.R;
import com.image.characterrecognition.utils.DialogLoadingFMV4;
import com.image.characterrecognition.utils.DialogUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;
import org.devio.takephoto.app.TakePhoto;
import org.devio.takephoto.app.TakePhotoImpl;
import org.devio.takephoto.compress.CompressConfig;
import org.devio.takephoto.model.CropOptions;
import org.devio.takephoto.model.InvokeParam;
import org.devio.takephoto.model.TContextWrap;
import org.devio.takephoto.model.TImage;
import org.devio.takephoto.model.TResult;
import org.devio.takephoto.permission.InvokeListener;
import org.devio.takephoto.permission.PermissionManager;
import org.devio.takephoto.permission.TakePhotoInvocationHandler;
import java.io.File;
import java.io.FileOutputStream;
import io.reactivex.functions.Consumer;
public class MainActivity extends AppCompatActivity implements MainContract.View, TakePhoto.TakeResultListener, InvokeListener, View.OnClickListener {
private TakePhoto takePhoto;
private InvokeParam invokeParam;
private Button btnPhoto;
private Button btnPhotos;
private Button btn_reset;
private TextView tv_content;
private TextView tv_path;
private CropOptions cropOptions; //裁剪参数
private CompressConfig compressConfig; //压缩参数
private Uri imageUri; //图片保存路径
private MainPresenter mainPresenter;
private File file1;
private RxPermissions rxPermissions;
private Boolean isPrand = true;
private DialogLoadingFMV4 dialogLoadingFMV4;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getTakePhoto().onCreate(savedInstanceState);
initView();
if (Build.VERSION.SDK_INT >= 23) { //6.0才用动态权限
//申请相关权限
initPermission();
}
initData(); //设置压缩、裁剪参数
}
@Override
protected void onSaveInstanceState(Bundle outState) {
getTakePhoto().onSaveInstanceState(outState);
super.onSaveInstanceState(outState);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
getTakePhoto().onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
}
/**
* 获取TakePhoto实例
*
* @return
*/
public TakePhoto getTakePhoto() {
if (takePhoto == null) {
takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
}
return takePhoto;
}
@Override
public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
if (PermissionManager.TPermissionType.WAIT.equals(type)) {
this.invokeParam = invokeParam;
}
return type;
}
private void initData() {
mainPresenter = new MainPresenter(this);
takePhoto = getTakePhoto();
initFileDir();
tv_path.setText("当前文件的路径" + getFilePath());
}
@SuppressLint("CheckResult")
private void initPermission() {
rxPermissions = new RxPermissions(this);
rxPermissions.request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
.subscribe(new Consumer<Boolean>() {
@Override
public void accept(Boolean aBoolean) throws Exception {
if (aBoolean) {
isPrand = aBoolean;
} else {
Toast.makeText(MainActivity.this, "授权失败", Toast.LENGTH_SHORT).show();
}
}
});
}
private void initView() {
btnPhoto = findViewById(R.id.btnPhoto1);
btnPhotos = findViewById(R.id.btnPhoto2);
tv_content = findViewById(R.id.tv_content);
tv_path = findViewById(R.id.tv_path);
btn_reset = findViewById(R.id.btn_reset);
btnPhoto.setOnClickListener(this);
btnPhotos.setOnClickListener(this);
btn_reset.setOnClickListener(this);
dialogLoadingFMV4 = DialogUtil.getProgressDialogV4(this, "图片识别中...");
}
@Override
public void onClick(View v) {
if (!isPrand) {
Toast.makeText(this, "请授权app读取文件权限和打开相机权限", Toast.LENGTH_SHORT).show();
return;
}
switch (v.getId()) {
case R.id.btnPhoto1:
showDialog();
imageUri = getImageCropUri();
takePhoto.onPickFromCapture(imageUri);
break;
case R.id.btnPhoto2:
showDialog();
imageUri = getImageCropUri();
takePhoto.onPickFromGallery();
break;
case R.id.btn_reset:
initFileDir();
tv_content.setText("");
tv_path.setText("当前文件的路径" + getFilePath());
Toast.makeText(this, "已经重新建立文件保存路径", Toast.LENGTH_SHORT).show();
break;
}
}
@Override
public void takeSuccess(TResult result) {
getAsscessToken(result);
}
private TResult result;
public void getAsscessToken(TResult result) {
this.result = result;
mainPresenter.getAccessToken();
}
@Override
public void getTokenSuccess() {
TImage image = result.getImage();
String originalPath = image.getOriginalPath();
if (image.getFromType() == TImage.FromType.CAMERA) {
originalPath = Environment.getExternalStorageDirectory() + originalPath;
}
mainPresenter.getRecognitionResultByImage(originalPath);
}
@Override
public void takeFail(TResult result, String msg) {
Toast.makeText(this, "识别失败" + msg, Toast.LENGTH_SHORT).show();
hideDialog();
}
@Override
public void takeCancel() {
hideDialog();
}
//获得照片的输出保存Uri
private Uri getImageCropUri() {
File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
return Uri.fromFile(file);
}
@Override
public void updateUI(String s) {
hideDialog();
String text = tv_content.getText().toString();
if (TextUtils.isEmpty(text)) {
tv_content.setText(s);
} else {
tv_content.append(s);
}
writeFile(s);
}
@Override
public void showDialog() {
DialogUtil.show(this, dialogLoadingFMV4);
}
@Override
public void hideDialog() {
DialogUtil.dismiss(this, dialogLoadingFMV4);
}
@Override
public void errorMessage(String mesage) {
Toast.makeText(this, "识别失败" + mesage, Toast.LENGTH_SHORT).show();
hideDialog();
}
private void writeFile(final String content) {
new Thread(new Runnable() {
@Override
public void run() {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file1.getAbsoluteFile() + "/1.txt", true);
//true表示在文件末尾追加
fos.write(content.getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
private void initFileDir() {
file1 = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis());
if (!file1.exists()) {
file1.mkdirs();
}
}
public String getFilePath() {
return file1.getAbsolutePath() + "/1.txt";
}
}
| UTF-8 | Java | 9,160 | java | MainActivity.java | Java | [] | null | [] | package com.image.characterrecognition.module;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.image.characterrecognition.R;
import com.image.characterrecognition.utils.DialogLoadingFMV4;
import com.image.characterrecognition.utils.DialogUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;
import org.devio.takephoto.app.TakePhoto;
import org.devio.takephoto.app.TakePhotoImpl;
import org.devio.takephoto.compress.CompressConfig;
import org.devio.takephoto.model.CropOptions;
import org.devio.takephoto.model.InvokeParam;
import org.devio.takephoto.model.TContextWrap;
import org.devio.takephoto.model.TImage;
import org.devio.takephoto.model.TResult;
import org.devio.takephoto.permission.InvokeListener;
import org.devio.takephoto.permission.PermissionManager;
import org.devio.takephoto.permission.TakePhotoInvocationHandler;
import java.io.File;
import java.io.FileOutputStream;
import io.reactivex.functions.Consumer;
public class MainActivity extends AppCompatActivity implements MainContract.View, TakePhoto.TakeResultListener, InvokeListener, View.OnClickListener {
private TakePhoto takePhoto;
private InvokeParam invokeParam;
private Button btnPhoto;
private Button btnPhotos;
private Button btn_reset;
private TextView tv_content;
private TextView tv_path;
private CropOptions cropOptions; //裁剪参数
private CompressConfig compressConfig; //压缩参数
private Uri imageUri; //图片保存路径
private MainPresenter mainPresenter;
private File file1;
private RxPermissions rxPermissions;
private Boolean isPrand = true;
private DialogLoadingFMV4 dialogLoadingFMV4;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getTakePhoto().onCreate(savedInstanceState);
initView();
if (Build.VERSION.SDK_INT >= 23) { //6.0才用动态权限
//申请相关权限
initPermission();
}
initData(); //设置压缩、裁剪参数
}
@Override
protected void onSaveInstanceState(Bundle outState) {
getTakePhoto().onSaveInstanceState(outState);
super.onSaveInstanceState(outState);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
getTakePhoto().onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
}
/**
* 获取TakePhoto实例
*
* @return
*/
public TakePhoto getTakePhoto() {
if (takePhoto == null) {
takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
}
return takePhoto;
}
@Override
public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
if (PermissionManager.TPermissionType.WAIT.equals(type)) {
this.invokeParam = invokeParam;
}
return type;
}
private void initData() {
mainPresenter = new MainPresenter(this);
takePhoto = getTakePhoto();
initFileDir();
tv_path.setText("当前文件的路径" + getFilePath());
}
@SuppressLint("CheckResult")
private void initPermission() {
rxPermissions = new RxPermissions(this);
rxPermissions.request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
.subscribe(new Consumer<Boolean>() {
@Override
public void accept(Boolean aBoolean) throws Exception {
if (aBoolean) {
isPrand = aBoolean;
} else {
Toast.makeText(MainActivity.this, "授权失败", Toast.LENGTH_SHORT).show();
}
}
});
}
private void initView() {
btnPhoto = findViewById(R.id.btnPhoto1);
btnPhotos = findViewById(R.id.btnPhoto2);
tv_content = findViewById(R.id.tv_content);
tv_path = findViewById(R.id.tv_path);
btn_reset = findViewById(R.id.btn_reset);
btnPhoto.setOnClickListener(this);
btnPhotos.setOnClickListener(this);
btn_reset.setOnClickListener(this);
dialogLoadingFMV4 = DialogUtil.getProgressDialogV4(this, "图片识别中...");
}
@Override
public void onClick(View v) {
if (!isPrand) {
Toast.makeText(this, "请授权app读取文件权限和打开相机权限", Toast.LENGTH_SHORT).show();
return;
}
switch (v.getId()) {
case R.id.btnPhoto1:
showDialog();
imageUri = getImageCropUri();
takePhoto.onPickFromCapture(imageUri);
break;
case R.id.btnPhoto2:
showDialog();
imageUri = getImageCropUri();
takePhoto.onPickFromGallery();
break;
case R.id.btn_reset:
initFileDir();
tv_content.setText("");
tv_path.setText("当前文件的路径" + getFilePath());
Toast.makeText(this, "已经重新建立文件保存路径", Toast.LENGTH_SHORT).show();
break;
}
}
@Override
public void takeSuccess(TResult result) {
getAsscessToken(result);
}
private TResult result;
public void getAsscessToken(TResult result) {
this.result = result;
mainPresenter.getAccessToken();
}
@Override
public void getTokenSuccess() {
TImage image = result.getImage();
String originalPath = image.getOriginalPath();
if (image.getFromType() == TImage.FromType.CAMERA) {
originalPath = Environment.getExternalStorageDirectory() + originalPath;
}
mainPresenter.getRecognitionResultByImage(originalPath);
}
@Override
public void takeFail(TResult result, String msg) {
Toast.makeText(this, "识别失败" + msg, Toast.LENGTH_SHORT).show();
hideDialog();
}
@Override
public void takeCancel() {
hideDialog();
}
//获得照片的输出保存Uri
private Uri getImageCropUri() {
File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
return Uri.fromFile(file);
}
@Override
public void updateUI(String s) {
hideDialog();
String text = tv_content.getText().toString();
if (TextUtils.isEmpty(text)) {
tv_content.setText(s);
} else {
tv_content.append(s);
}
writeFile(s);
}
@Override
public void showDialog() {
DialogUtil.show(this, dialogLoadingFMV4);
}
@Override
public void hideDialog() {
DialogUtil.dismiss(this, dialogLoadingFMV4);
}
@Override
public void errorMessage(String mesage) {
Toast.makeText(this, "识别失败" + mesage, Toast.LENGTH_SHORT).show();
hideDialog();
}
private void writeFile(final String content) {
new Thread(new Runnable() {
@Override
public void run() {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file1.getAbsoluteFile() + "/1.txt", true);
//true表示在文件末尾追加
fos.write(content.getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
private void initFileDir() {
file1 = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis());
if (!file1.exists()) {
file1.mkdirs();
}
}
public String getFilePath() {
return file1.getAbsolutePath() + "/1.txt";
}
}
| 9,160 | 0.638105 | 0.635193 | 276 | 31.347826 | 26.496145 | 150 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.615942 | false | false | 1 |
6f9f1f7161666be37d7044db057006182dc47053 | 26,079,041,432,843 | 2842047251b1ef14ebc9d36e70f5dd78ae5aae25 | /src/main/java/me/ANONIMUS/proxy/protocol/packet/impl/server/play/ServerUpdateScorePacket.java | a884a9bf1c3d45e2469e6ac6f88aafafb98711bc | [
"MIT"
] | permissive | CrackerCat/BetterProxy | https://github.com/CrackerCat/BetterProxy | 242103bec48e19b135f0e0e6dbfdd74cf5b7eb9c | b74c11058fe2603bddf3bab84d07398c0639b528 | refs/heads/master | 2023-07-21T19:31:30.906000 | 2021-08-23T01:30:14 | 2021-08-23T01:30:14 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package me.ANONIMUS.proxy.protocol.packet.impl.server.play;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import me.ANONIMUS.proxy.protocol.Protocol;
import me.ANONIMUS.proxy.protocol.packet.Packet;
import me.ANONIMUS.proxy.protocol.packet.PacketBuffer;
import java.util.Arrays;
import java.util.List;
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class ServerUpdateScorePacket extends Packet {
private String scoreName;
private int action;
private String objectiveName;
private int value;
@Override
public void write(PacketBuffer out, int protocol) throws Exception {
out.writeString(this.scoreName);
out.writeByte(this.action);
out.writeString(this.objectiveName);
if (action != 1) {
out.writeVarInt(this.value);
}
}
@Override
public void read(PacketBuffer in, int protocol) throws Exception {
this.scoreName = in.readString(128);
this.action = in.readByte();
this.objectiveName = in.readString(32767);
if (action != 1) {
this.value = in.readVarInt();
}
}
@Override
public List<Protocol> getProtocolList() {
return Arrays.asList(new Protocol(0x3C, 47), new Protocol(0x42, 107, 108, 109, 110, 210, 315, 316), new Protocol(0x44, 335), new Protocol(0x45, 338, 340));
}
} | UTF-8 | Java | 1,390 | java | ServerUpdateScorePacket.java | Java | [] | null | [] | package me.ANONIMUS.proxy.protocol.packet.impl.server.play;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import me.ANONIMUS.proxy.protocol.Protocol;
import me.ANONIMUS.proxy.protocol.packet.Packet;
import me.ANONIMUS.proxy.protocol.packet.PacketBuffer;
import java.util.Arrays;
import java.util.List;
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class ServerUpdateScorePacket extends Packet {
private String scoreName;
private int action;
private String objectiveName;
private int value;
@Override
public void write(PacketBuffer out, int protocol) throws Exception {
out.writeString(this.scoreName);
out.writeByte(this.action);
out.writeString(this.objectiveName);
if (action != 1) {
out.writeVarInt(this.value);
}
}
@Override
public void read(PacketBuffer in, int protocol) throws Exception {
this.scoreName = in.readString(128);
this.action = in.readByte();
this.objectiveName = in.readString(32767);
if (action != 1) {
this.value = in.readVarInt();
}
}
@Override
public List<Protocol> getProtocolList() {
return Arrays.asList(new Protocol(0x3C, 47), new Protocol(0x42, 107, 108, 109, 110, 210, 315, 316), new Protocol(0x44, 335), new Protocol(0x45, 338, 340));
}
} | 1,390 | 0.689209 | 0.651079 | 46 | 29.23913 | 27.92551 | 163 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.826087 | false | false | 1 |
1ed81868655487737bee8c5c6f0185a9fe4b9085 | 29,729,763,636,531 | 39c69dfbf2a38007e4c124a45331d398e9d5c35c | /cart-service/src/main/java/com/trendyol/cartservice/util/DeliveryCostCalculator.java | aaa2f900ee4f000d9fc9b0feac87bd222dab944c | [] | no_license | cemayan/cart-case | https://github.com/cemayan/cart-case | ead1516e423afd8a5a5d84087433673a9399bbd3 | a5dbc5326017ffbb26c67f7220bd06246176f5db | refs/heads/master | 2020-08-23T01:30:24.873000 | 2019-10-21T08:26:12 | 2019-10-21T08:26:12 | 216,403,322 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.trendyol.cartservice.util;
import com.trendyol.cartservice.model.Product;
import com.trendyol.cartservice.model.ShoppingCart;
import lombok.Getter;
import lombok.Setter;
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
public class DeliveryCostCalculator {
private static Double fixedCost = 2.99;
public static Double calculateFor(ShoppingCart shoppingCart, Double costPerDelivery, Double costPerProduct) {
Set<String> products = new HashSet<String>(shoppingCart.getCartItems().stream().map(x->x.getProduct().getId()).collect(Collectors.toList())) ;
Integer numberofProducts = products.size();
Set<String> categories = new HashSet<String>(shoppingCart.getCartItems().stream().map(x->x.getProduct().getCategory().getId()).collect(Collectors.toList())) ;
Integer numberofDeliveries = categories.size();
return (costPerDelivery * numberofDeliveries) + (costPerProduct * numberofProducts) + fixedCost;
}
}
| UTF-8 | Java | 1,040 | java | DeliveryCostCalculator.java | Java | [] | null | [] | package com.trendyol.cartservice.util;
import com.trendyol.cartservice.model.Product;
import com.trendyol.cartservice.model.ShoppingCart;
import lombok.Getter;
import lombok.Setter;
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
public class DeliveryCostCalculator {
private static Double fixedCost = 2.99;
public static Double calculateFor(ShoppingCart shoppingCart, Double costPerDelivery, Double costPerProduct) {
Set<String> products = new HashSet<String>(shoppingCart.getCartItems().stream().map(x->x.getProduct().getId()).collect(Collectors.toList())) ;
Integer numberofProducts = products.size();
Set<String> categories = new HashSet<String>(shoppingCart.getCartItems().stream().map(x->x.getProduct().getCategory().getId()).collect(Collectors.toList())) ;
Integer numberofDeliveries = categories.size();
return (costPerDelivery * numberofDeliveries) + (costPerProduct * numberofProducts) + fixedCost;
}
}
| 1,040 | 0.751923 | 0.749038 | 27 | 37.51852 | 45.157642 | 166 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.62963 | false | false | 1 |
7772c36c6791ed1ec4df20b86981c463253b2b40 | 15,513,421,891,081 | 1b886e8e31df92fa02a2528372e4be29f3d6a40d | /wechat/src/com/covisint/wechat/stat/service/impl/.svn/text-base/WebsiteHisServiceImpl.java.svn-base | 0d6d13ef696b4db8c283dc54d26a9fcc4e10f325 | [] | no_license | lisongqiu168/lsq-hunteron | https://github.com/lisongqiu168/lsq-hunteron | 37c0bc86b09094d442447d9a58e8506cebff201d | 6b087c9ee7aed7abd3bbeabac57b7552f9f7ae16 | refs/heads/master | 2019-06-21T11:34:33.236000 | 2017-08-21T02:05:02 | 2017-08-21T02:05:02 | 100,699,134 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /************************************************************************************
* @File name : WebsiteHisServiceImpl.java
*
* @Author : 马恩伟
*
* @Date : 2014-6-17
*
* @Copyright Notice:
* Copyright (c) 2011 SGM, Inc. All Rights Reserved.
* This software is published under the terms of the SGM Software
* License version 1.0, a copy of which has been included with this
* distribution in the LICENSE.txt file.
*
*
* ----------------------------------------------------------------------------------
* Date Who Version Comments
* 2014-6-17 下午04:47:33 马恩伟 1.0 Initial Version
************************************************************************************/
package com.covisint.wechat.stat.service.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
import com.covisint.wechat.data.dao.WxWebsiteHisDao;
import com.covisint.wechat.data.model.WxWebsiteHis;
import com.covisint.wechat.page.Page;
import com.covisint.wechat.stat.service.WebsiteHisService;
import com.covisint.wechat.utils.IdentifierUtils;
/**
*
*/
@Service
public class WebsiteHisServiceImpl implements WebsiteHisService {
@Autowired
private WxWebsiteHisDao wxWebsiteHisDao;
@Override
public boolean saveVisitHis(String resourceId, String redirect, String openId, String accountId, String source) {
WxWebsiteHis websiteHis = new WxWebsiteHis();
websiteHis.setAccountId(accountId);
websiteHis.setOpenId(openId);
websiteHis.setResourceId(resourceId);
UriComponents redirectUri = UriComponentsBuilder.fromHttpUrl(redirect).build().encode();
String weblink = redirectUri.getScheme() + "://" + redirectUri.getHost();
if (redirectUri.getPort() > 0) {
weblink += ":" + redirectUri.getPort();
}
if (redirectUri.getPath() != null) {
weblink += redirectUri.getPath();
}
websiteHis.setViewHref(weblink);
websiteHis.setViewSource(source);
websiteHis.setVisitHisId(IdentifierUtils.getId().generate().toString());
return wxWebsiteHisDao.insert(websiteHis) > 0;
}
@Override
public Page<Map<String, Object>> pageWebsiteHis(Map<String, Object> paramMap, Integer current, Integer pagesize) {
String startDay = (String) paramMap.get("startDay");
if (!StringUtils.isEmpty(startDay)) {
paramMap.put("startTime", startDay);
}
String endDay = (String) paramMap.get("endDay");
if (!StringUtils.isEmpty(endDay)) {
paramMap.put("endTime", endDay);
}
return wxWebsiteHisDao.pageWebsiteHis(paramMap, current, pagesize);
}
@Override
public Page<Map<String, Object>> pageDaySummary(Map<String, Object> paramMap, Integer current, Integer pagesize) {
String startDay = (String) paramMap.get("startDay");
if (!StringUtils.isEmpty(startDay)) {
paramMap.put("startTime", startDay);
}
String endDay = (String) paramMap.get("endDay");
if (!StringUtils.isEmpty(endDay)) {
paramMap.put("endTime", endDay);
}
String sortColumn = (String) paramMap.get("sort");
String sortOrder = (String) paramMap.get("order");
String order = this.getOrder(sortColumn, sortOrder);
if (!StringUtils.isEmpty(order)) {
paramMap.put("order", order);
}
return wxWebsiteHisDao.pageDaySummary(paramMap, current, pagesize);
}
public Map<String, Object> daysummary(Map<String, Object> paramMap) {
Map<String, Object> result = new HashMap<String, Object>();
String startDay = (String) paramMap.get("startDay");
if (!StringUtils.isEmpty(startDay)) {
paramMap.put("startTime", startDay);
}
String endDay = (String) paramMap.get("endDay");
if (!StringUtils.isEmpty(endDay)) {
paramMap.put("endTime", endDay);
}
List<Map<String, Object>> data = wxWebsiteHisDao.daysummary(paramMap);
List<String> dayList = new ArrayList<String>();
List<Integer> clickList = new ArrayList<Integer>();
List<Integer> memberList = new ArrayList<Integer>();
for (Map<String, Object> m : data) {
String date = (String) m.get("VISIT_DATE");
int click = Integer.valueOf(m.get("CLICK").toString());
int member = Integer.valueOf(m.get("MEMBER").toString());
dayList.add(date);
clickList.add(click);
memberList.add(member);
}
result.put("day", dayList);
result.put("click", clickList);
result.put("member", memberList);
return result;
}
@Override
public Page<Map<String, Object>> pageTimeSummary(Map<String, Object> paramMap, Integer current, Integer pagesize) {
String startTime = (String) paramMap.get("startTime");
if (!StringUtils.isEmpty(startTime)) {
paramMap.put("start", startTime);
}
String endTime = (String) paramMap.get("endTime");
if (!StringUtils.isEmpty(endTime)) {
paramMap.put("end", endTime);
}
String sortColumn = (String) paramMap.get("sort");
String sortOrder = (String) paramMap.get("order");
String order = this.getOrder(sortColumn, sortOrder);
if (!StringUtils.isEmpty(order)) {
paramMap.put("order", order);
}
return wxWebsiteHisDao.pageTimeSummary(paramMap, current, pagesize);
}
@Override
public Map<String, Object> timesummary(Map<String, Object> paramMap) {
Map<String, Object> result = new HashMap<String, Object>();
String startTime = (String) paramMap.get("startTime");
if (!StringUtils.isEmpty(startTime)) {
paramMap.put("start", startTime);
}
String endTime = (String) paramMap.get("endTime");
if (!StringUtils.isEmpty(endTime)) {
paramMap.put("end", endTime);
}
List<Map<String, Object>> data = wxWebsiteHisDao.timesummary(paramMap);
List<String> timeList = new ArrayList<String>();
List<Integer> clickList = new ArrayList<Integer>();
List<Integer> memberList = new ArrayList<Integer>();
for (Map<String, Object> m : data) {
String time = (String) m.get("VISIT_TIME");
int click = Integer.valueOf(m.get("CLICK").toString());
int member = Integer.valueOf(m.get("MEMBER").toString());
timeList.add(time);
clickList.add(click);
memberList.add(member);
}
result.put("time", timeList);
result.put("click", clickList);
result.put("member", memberList);
return result;
}
@Override
public Page<Map<String, Object>> pageAreaSummary(Map<String, Object> paramMap, Integer current, Integer pagesize) {
String startDay = (String) paramMap.get("startDay");
if (!StringUtils.isEmpty(startDay)) {
paramMap.put("startTime", startDay);
}
String endDay = (String) paramMap.get("endDay");
if (!StringUtils.isEmpty(endDay)) {
paramMap.put("endTime", endDay);
}
String sortColumn = (String) paramMap.get("sort");
String sortOrder = (String) paramMap.get("order");
String order = this.getOrder(sortColumn, sortOrder);
if (!StringUtils.isEmpty(order)) {
paramMap.put("order", order);
}
return wxWebsiteHisDao.pageAreaSummary(paramMap, current, pagesize);
}
/**
* 后台拼装 order 以免sql注入
*
* @author 马恩伟
* @date 2014-8-22
*/
private String getOrder(String sortColumn, String sortOrder) {
if (StringUtils.isEmpty(sortOrder)) {
sortOrder = "DESC";
} else if ("asc".equals(sortOrder)) {
sortOrder = "ASC";
} else {
sortOrder = "DESC";
}
if (StringUtils.isEmpty(sortColumn)) {
return null;
} else if ("VISIT_DATE".equals(sortColumn)) {
return "WWH.VISIT_DATE " + sortOrder;
} else if ("CLICK".equals(sortColumn)) {
return "CLICK " + sortOrder;
} else if ("MEMBER".equals(sortColumn)) {
return "MEMBER " + sortOrder;
} else if ("VISIT_TIME".equals(sortColumn)) {
return "TO_CHAR(TO_DATE(WWH.VISIT_TIME, 'hh24:MI:ss'),'hh24') " + sortOrder;
}
return null;
}
}
| UTF-8 | Java | 7,822 | WebsiteHisServiceImpl.java.svn-base | Java | [
{
"context": "siteHisServiceImpl.java\n *\n * @Author : 马恩伟\n *\n * @Date : 2014-6-17\n *\n * @Copyri",
"end": 165,
"score": 0.9991946220397949,
"start": 162,
"tag": "NAME",
"value": "马恩伟"
},
{
"context": "\t\t\t\tVersion\t\t\t\tComments\n * 2014-6-17 下午04:47:33... | null | [] | /************************************************************************************
* @File name : WebsiteHisServiceImpl.java
*
* @Author : 马恩伟
*
* @Date : 2014-6-17
*
* @Copyright Notice:
* Copyright (c) 2011 SGM, Inc. All Rights Reserved.
* This software is published under the terms of the SGM Software
* License version 1.0, a copy of which has been included with this
* distribution in the LICENSE.txt file.
*
*
* ----------------------------------------------------------------------------------
* Date Who Version Comments
* 2014-6-17 下午04:47:33 马恩伟 1.0 Initial Version
************************************************************************************/
package com.covisint.wechat.stat.service.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
import com.covisint.wechat.data.dao.WxWebsiteHisDao;
import com.covisint.wechat.data.model.WxWebsiteHis;
import com.covisint.wechat.page.Page;
import com.covisint.wechat.stat.service.WebsiteHisService;
import com.covisint.wechat.utils.IdentifierUtils;
/**
*
*/
@Service
public class WebsiteHisServiceImpl implements WebsiteHisService {
@Autowired
private WxWebsiteHisDao wxWebsiteHisDao;
@Override
public boolean saveVisitHis(String resourceId, String redirect, String openId, String accountId, String source) {
WxWebsiteHis websiteHis = new WxWebsiteHis();
websiteHis.setAccountId(accountId);
websiteHis.setOpenId(openId);
websiteHis.setResourceId(resourceId);
UriComponents redirectUri = UriComponentsBuilder.fromHttpUrl(redirect).build().encode();
String weblink = redirectUri.getScheme() + "://" + redirectUri.getHost();
if (redirectUri.getPort() > 0) {
weblink += ":" + redirectUri.getPort();
}
if (redirectUri.getPath() != null) {
weblink += redirectUri.getPath();
}
websiteHis.setViewHref(weblink);
websiteHis.setViewSource(source);
websiteHis.setVisitHisId(IdentifierUtils.getId().generate().toString());
return wxWebsiteHisDao.insert(websiteHis) > 0;
}
@Override
public Page<Map<String, Object>> pageWebsiteHis(Map<String, Object> paramMap, Integer current, Integer pagesize) {
String startDay = (String) paramMap.get("startDay");
if (!StringUtils.isEmpty(startDay)) {
paramMap.put("startTime", startDay);
}
String endDay = (String) paramMap.get("endDay");
if (!StringUtils.isEmpty(endDay)) {
paramMap.put("endTime", endDay);
}
return wxWebsiteHisDao.pageWebsiteHis(paramMap, current, pagesize);
}
@Override
public Page<Map<String, Object>> pageDaySummary(Map<String, Object> paramMap, Integer current, Integer pagesize) {
String startDay = (String) paramMap.get("startDay");
if (!StringUtils.isEmpty(startDay)) {
paramMap.put("startTime", startDay);
}
String endDay = (String) paramMap.get("endDay");
if (!StringUtils.isEmpty(endDay)) {
paramMap.put("endTime", endDay);
}
String sortColumn = (String) paramMap.get("sort");
String sortOrder = (String) paramMap.get("order");
String order = this.getOrder(sortColumn, sortOrder);
if (!StringUtils.isEmpty(order)) {
paramMap.put("order", order);
}
return wxWebsiteHisDao.pageDaySummary(paramMap, current, pagesize);
}
public Map<String, Object> daysummary(Map<String, Object> paramMap) {
Map<String, Object> result = new HashMap<String, Object>();
String startDay = (String) paramMap.get("startDay");
if (!StringUtils.isEmpty(startDay)) {
paramMap.put("startTime", startDay);
}
String endDay = (String) paramMap.get("endDay");
if (!StringUtils.isEmpty(endDay)) {
paramMap.put("endTime", endDay);
}
List<Map<String, Object>> data = wxWebsiteHisDao.daysummary(paramMap);
List<String> dayList = new ArrayList<String>();
List<Integer> clickList = new ArrayList<Integer>();
List<Integer> memberList = new ArrayList<Integer>();
for (Map<String, Object> m : data) {
String date = (String) m.get("VISIT_DATE");
int click = Integer.valueOf(m.get("CLICK").toString());
int member = Integer.valueOf(m.get("MEMBER").toString());
dayList.add(date);
clickList.add(click);
memberList.add(member);
}
result.put("day", dayList);
result.put("click", clickList);
result.put("member", memberList);
return result;
}
@Override
public Page<Map<String, Object>> pageTimeSummary(Map<String, Object> paramMap, Integer current, Integer pagesize) {
String startTime = (String) paramMap.get("startTime");
if (!StringUtils.isEmpty(startTime)) {
paramMap.put("start", startTime);
}
String endTime = (String) paramMap.get("endTime");
if (!StringUtils.isEmpty(endTime)) {
paramMap.put("end", endTime);
}
String sortColumn = (String) paramMap.get("sort");
String sortOrder = (String) paramMap.get("order");
String order = this.getOrder(sortColumn, sortOrder);
if (!StringUtils.isEmpty(order)) {
paramMap.put("order", order);
}
return wxWebsiteHisDao.pageTimeSummary(paramMap, current, pagesize);
}
@Override
public Map<String, Object> timesummary(Map<String, Object> paramMap) {
Map<String, Object> result = new HashMap<String, Object>();
String startTime = (String) paramMap.get("startTime");
if (!StringUtils.isEmpty(startTime)) {
paramMap.put("start", startTime);
}
String endTime = (String) paramMap.get("endTime");
if (!StringUtils.isEmpty(endTime)) {
paramMap.put("end", endTime);
}
List<Map<String, Object>> data = wxWebsiteHisDao.timesummary(paramMap);
List<String> timeList = new ArrayList<String>();
List<Integer> clickList = new ArrayList<Integer>();
List<Integer> memberList = new ArrayList<Integer>();
for (Map<String, Object> m : data) {
String time = (String) m.get("VISIT_TIME");
int click = Integer.valueOf(m.get("CLICK").toString());
int member = Integer.valueOf(m.get("MEMBER").toString());
timeList.add(time);
clickList.add(click);
memberList.add(member);
}
result.put("time", timeList);
result.put("click", clickList);
result.put("member", memberList);
return result;
}
@Override
public Page<Map<String, Object>> pageAreaSummary(Map<String, Object> paramMap, Integer current, Integer pagesize) {
String startDay = (String) paramMap.get("startDay");
if (!StringUtils.isEmpty(startDay)) {
paramMap.put("startTime", startDay);
}
String endDay = (String) paramMap.get("endDay");
if (!StringUtils.isEmpty(endDay)) {
paramMap.put("endTime", endDay);
}
String sortColumn = (String) paramMap.get("sort");
String sortOrder = (String) paramMap.get("order");
String order = this.getOrder(sortColumn, sortOrder);
if (!StringUtils.isEmpty(order)) {
paramMap.put("order", order);
}
return wxWebsiteHisDao.pageAreaSummary(paramMap, current, pagesize);
}
/**
* 后台拼装 order 以免sql注入
*
* @author 马恩伟
* @date 2014-8-22
*/
private String getOrder(String sortColumn, String sortOrder) {
if (StringUtils.isEmpty(sortOrder)) {
sortOrder = "DESC";
} else if ("asc".equals(sortOrder)) {
sortOrder = "ASC";
} else {
sortOrder = "DESC";
}
if (StringUtils.isEmpty(sortColumn)) {
return null;
} else if ("VISIT_DATE".equals(sortColumn)) {
return "WWH.VISIT_DATE " + sortOrder;
} else if ("CLICK".equals(sortColumn)) {
return "CLICK " + sortOrder;
} else if ("MEMBER".equals(sortColumn)) {
return "MEMBER " + sortOrder;
} else if ("VISIT_TIME".equals(sortColumn)) {
return "TO_CHAR(TO_DATE(WWH.VISIT_TIME, 'hh24:MI:ss'),'hh24') " + sortOrder;
}
return null;
}
}
| 7,822 | 0.681783 | 0.676387 | 220 | 34.381817 | 25.816654 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.490909 | false | false | 1 | |
a024644e6a0c6b2712f1348b24a1147b6a6e9414 | 27,041,114,135,420 | ac2bc57585055a013afd58d7e90c44bf0c6a071b | /app/src/main/java/com/example/qiulin/traffic/beans/Dangerous.java | 7f5bdf9a60d82ea8f4954f9a287e452092ba9ea3 | [] | no_license | QiulinZhan/traffic | https://github.com/QiulinZhan/traffic | dc5187729756704036352acbc0c279c62869857f | 90fe78be17782470e0b20aa0215188638db27aa3 | refs/heads/master | 2021-05-24T04:35:55.024000 | 2016-11-06T14:44:49 | 2016-11-06T14:44:49 | 51,059,868 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.qiulin.traffic.beans;
/**
* Created by zhanqiulin on 2016/2/3.
*/
public class Dangerous {
private Long id;
//检查时间
private String jcsj;
//是否为挂车
private Integer sfgc;
//通行证编号
private String txzbh;
//行驶证条形码
private String xsztxm;
//驾驶人驾驶证号
private String jsrjszh;
//驾驶人姓名
private String jsrxm;
//驾驶人下次体检日期
private String jsrxctjrq;
//驾驶人驾驶证条形码
private String jsrjsztxm;
//驾驶人驾驶资格
private String jsrjszg;
//押运员姓名
private String yyyxm;
//押运员押运证
private String yyyyyz;
//押运员电话
private String yyydh;
//供货厂家名称
private String ghcjmc;
//供货厂家联系人
private String ghcjlxr;
//供货厂家电话
private String ghcjdh;
//核载质量
private String hzzl;
//实载质量
private String szzl;
//企业等级
private String qydj;
//货物性质
private String hwxz;
//车辆下次检验日期
private String cjrq;
//安全设施
private String aqss;
//轮胎磨损
private String ltms;
//违法记录
private String wfjl;
//登记民警
private String djmj;
//源头管理民警
private String ytglmj;
//应急处理办法
private String yjclbf;
//备注
private String bz;
private String createTime;
private Integer isDel;
private Long creater;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getJcsj() {
return jcsj;
}
public void setJcsj(String jcsj) {
this.jcsj = jcsj;
}
public Integer getSfgc() {
return sfgc;
}
public void setSfgc(Integer sfgc) {
this.sfgc = sfgc;
}
public String getTxzbh() {
return txzbh;
}
public void setTxzbh(String txzbh) {
this.txzbh = txzbh;
}
public String getXsztxm() {
return xsztxm;
}
public void setXsztxm(String xsztxm) {
this.xsztxm = xsztxm;
}
public String getJsrjszh() {
return jsrjszh;
}
public void setJsrjszh(String jsrjszh) {
this.jsrjszh = jsrjszh;
}
public String getJsrxm() {
return jsrxm;
}
public void setJsrxm(String jsrxm) {
this.jsrxm = jsrxm;
}
public String getJsrxctjrq() {
return jsrxctjrq;
}
public void setJsrxctjrq(String jsrxctjrq) {
this.jsrxctjrq = jsrxctjrq;
}
public String getJsrjsztxm() {
return jsrjsztxm;
}
public void setJsrjsztxm(String jsrjsztxm) {
this.jsrjsztxm = jsrjsztxm;
}
public String getJsrjszg() {
return jsrjszg;
}
public void setJsrjszg(String jsrjszg) {
this.jsrjszg = jsrjszg;
}
public String getYyyxm() {
return yyyxm;
}
public void setYyyxm(String yyyxm) {
this.yyyxm = yyyxm;
}
public String getYyyyyz() {
return yyyyyz;
}
public void setYyyyyz(String yyyyyz) {
this.yyyyyz = yyyyyz;
}
public String getYyydh() {
return yyydh;
}
public void setYyydh(String yyydh) {
this.yyydh = yyydh;
}
public String getGhcjmc() {
return ghcjmc;
}
public void setGhcjmc(String ghcjmc) {
this.ghcjmc = ghcjmc;
}
public String getGhcjlxr() {
return ghcjlxr;
}
public void setGhcjlxr(String ghcjlxr) {
this.ghcjlxr = ghcjlxr;
}
public String getGhcjdh() {
return ghcjdh;
}
public void setGhcjdh(String ghcjdh) {
this.ghcjdh = ghcjdh;
}
public String getHzzl() {
return hzzl;
}
public void setHzzl(String hzzl) {
this.hzzl = hzzl;
}
public String getSzzl() {
return szzl;
}
public void setSzzl(String szzl) {
this.szzl = szzl;
}
public String getQydj() {
return qydj;
}
public void setQydj(String qydj) {
this.qydj = qydj;
}
public String getHwxz() {
return hwxz;
}
public void setHwxz(String hwxz) {
this.hwxz = hwxz;
}
public String getCjrq() {
return cjrq;
}
public void setCjrq(String cjrq) {
this.cjrq = cjrq;
}
public String getAqss() {
return aqss;
}
public void setAqss(String aqss) {
this.aqss = aqss;
}
public String getLtms() {
return ltms;
}
public void setLtms(String ltms) {
this.ltms = ltms;
}
public String getWfjl() {
return wfjl;
}
public void setWfjl(String wfjl) {
this.wfjl = wfjl;
}
public String getDjmj() {
return djmj;
}
public void setDjmj(String djmj) {
this.djmj = djmj;
}
public String getYtglmj() {
return ytglmj;
}
public void setYtglmj(String ytglmj) {
this.ytglmj = ytglmj;
}
public String getYjclbf() {
return yjclbf;
}
public void setYjclbf(String yjclbf) {
this.yjclbf = yjclbf;
}
public String getBz() {
return bz;
}
public void setBz(String bz) {
this.bz = bz;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public Integer getIsDel() {
return isDel;
}
public void setIsDel(Integer isDel) {
this.isDel = isDel;
}
public Long getCreater() {
return creater;
}
public void setCreater(Long creater) {
this.creater = creater;
}
@Override
public String toString() {
return "Dangerous{" +
"id=" + id +
", jcsj='" + jcsj + '\'' +
", sfgc=" + sfgc +
", txzbh='" + txzbh + '\'' +
", xsztxm='" + xsztxm + '\'' +
", jsrjszh='" + jsrjszh + '\'' +
", jsrxm='" + jsrxm + '\'' +
", jsrxctjrq='" + jsrxctjrq + '\'' +
", jsrjsztxm='" + jsrjsztxm + '\'' +
", jsrjszg='" + jsrjszg + '\'' +
", yyyxm='" + yyyxm + '\'' +
", yyyyyz='" + yyyyyz + '\'' +
", yyydh='" + yyydh + '\'' +
", ghcjmc='" + ghcjmc + '\'' +
", ghcjlxr='" + ghcjlxr + '\'' +
", ghcjdh='" + ghcjdh + '\'' +
", hzzl='" + hzzl + '\'' +
", szzl='" + szzl + '\'' +
", qydj='" + qydj + '\'' +
", hwxz='" + hwxz + '\'' +
", cjrq='" + cjrq + '\'' +
", aqss='" + aqss + '\'' +
", ltms='" + ltms + '\'' +
", wfjl='" + wfjl + '\'' +
", djmj='" + djmj + '\'' +
", ytglmj='" + ytglmj + '\'' +
", yjclbf='" + yjclbf + '\'' +
", bz='" + bz + '\'' +
", createTime='" + createTime + '\'' +
", isDel=" + isDel +
", creater=" + creater +
'}';
}
}
| UTF-8 | Java | 7,251 | java | Dangerous.java | Java | [
{
"context": "m.example.qiulin.traffic.beans;\n\n/**\n * Created by zhanqiulin on 2016/2/3.\n */\npublic class Dangerous {\n pri",
"end": 71,
"score": 0.9994834661483765,
"start": 61,
"tag": "USERNAME",
"value": "zhanqiulin"
}
] | null | [] | package com.example.qiulin.traffic.beans;
/**
* Created by zhanqiulin on 2016/2/3.
*/
public class Dangerous {
private Long id;
//检查时间
private String jcsj;
//是否为挂车
private Integer sfgc;
//通行证编号
private String txzbh;
//行驶证条形码
private String xsztxm;
//驾驶人驾驶证号
private String jsrjszh;
//驾驶人姓名
private String jsrxm;
//驾驶人下次体检日期
private String jsrxctjrq;
//驾驶人驾驶证条形码
private String jsrjsztxm;
//驾驶人驾驶资格
private String jsrjszg;
//押运员姓名
private String yyyxm;
//押运员押运证
private String yyyyyz;
//押运员电话
private String yyydh;
//供货厂家名称
private String ghcjmc;
//供货厂家联系人
private String ghcjlxr;
//供货厂家电话
private String ghcjdh;
//核载质量
private String hzzl;
//实载质量
private String szzl;
//企业等级
private String qydj;
//货物性质
private String hwxz;
//车辆下次检验日期
private String cjrq;
//安全设施
private String aqss;
//轮胎磨损
private String ltms;
//违法记录
private String wfjl;
//登记民警
private String djmj;
//源头管理民警
private String ytglmj;
//应急处理办法
private String yjclbf;
//备注
private String bz;
private String createTime;
private Integer isDel;
private Long creater;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getJcsj() {
return jcsj;
}
public void setJcsj(String jcsj) {
this.jcsj = jcsj;
}
public Integer getSfgc() {
return sfgc;
}
public void setSfgc(Integer sfgc) {
this.sfgc = sfgc;
}
public String getTxzbh() {
return txzbh;
}
public void setTxzbh(String txzbh) {
this.txzbh = txzbh;
}
public String getXsztxm() {
return xsztxm;
}
public void setXsztxm(String xsztxm) {
this.xsztxm = xsztxm;
}
public String getJsrjszh() {
return jsrjszh;
}
public void setJsrjszh(String jsrjszh) {
this.jsrjszh = jsrjszh;
}
public String getJsrxm() {
return jsrxm;
}
public void setJsrxm(String jsrxm) {
this.jsrxm = jsrxm;
}
public String getJsrxctjrq() {
return jsrxctjrq;
}
public void setJsrxctjrq(String jsrxctjrq) {
this.jsrxctjrq = jsrxctjrq;
}
public String getJsrjsztxm() {
return jsrjsztxm;
}
public void setJsrjsztxm(String jsrjsztxm) {
this.jsrjsztxm = jsrjsztxm;
}
public String getJsrjszg() {
return jsrjszg;
}
public void setJsrjszg(String jsrjszg) {
this.jsrjszg = jsrjszg;
}
public String getYyyxm() {
return yyyxm;
}
public void setYyyxm(String yyyxm) {
this.yyyxm = yyyxm;
}
public String getYyyyyz() {
return yyyyyz;
}
public void setYyyyyz(String yyyyyz) {
this.yyyyyz = yyyyyz;
}
public String getYyydh() {
return yyydh;
}
public void setYyydh(String yyydh) {
this.yyydh = yyydh;
}
public String getGhcjmc() {
return ghcjmc;
}
public void setGhcjmc(String ghcjmc) {
this.ghcjmc = ghcjmc;
}
public String getGhcjlxr() {
return ghcjlxr;
}
public void setGhcjlxr(String ghcjlxr) {
this.ghcjlxr = ghcjlxr;
}
public String getGhcjdh() {
return ghcjdh;
}
public void setGhcjdh(String ghcjdh) {
this.ghcjdh = ghcjdh;
}
public String getHzzl() {
return hzzl;
}
public void setHzzl(String hzzl) {
this.hzzl = hzzl;
}
public String getSzzl() {
return szzl;
}
public void setSzzl(String szzl) {
this.szzl = szzl;
}
public String getQydj() {
return qydj;
}
public void setQydj(String qydj) {
this.qydj = qydj;
}
public String getHwxz() {
return hwxz;
}
public void setHwxz(String hwxz) {
this.hwxz = hwxz;
}
public String getCjrq() {
return cjrq;
}
public void setCjrq(String cjrq) {
this.cjrq = cjrq;
}
public String getAqss() {
return aqss;
}
public void setAqss(String aqss) {
this.aqss = aqss;
}
public String getLtms() {
return ltms;
}
public void setLtms(String ltms) {
this.ltms = ltms;
}
public String getWfjl() {
return wfjl;
}
public void setWfjl(String wfjl) {
this.wfjl = wfjl;
}
public String getDjmj() {
return djmj;
}
public void setDjmj(String djmj) {
this.djmj = djmj;
}
public String getYtglmj() {
return ytglmj;
}
public void setYtglmj(String ytglmj) {
this.ytglmj = ytglmj;
}
public String getYjclbf() {
return yjclbf;
}
public void setYjclbf(String yjclbf) {
this.yjclbf = yjclbf;
}
public String getBz() {
return bz;
}
public void setBz(String bz) {
this.bz = bz;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public Integer getIsDel() {
return isDel;
}
public void setIsDel(Integer isDel) {
this.isDel = isDel;
}
public Long getCreater() {
return creater;
}
public void setCreater(Long creater) {
this.creater = creater;
}
@Override
public String toString() {
return "Dangerous{" +
"id=" + id +
", jcsj='" + jcsj + '\'' +
", sfgc=" + sfgc +
", txzbh='" + txzbh + '\'' +
", xsztxm='" + xsztxm + '\'' +
", jsrjszh='" + jsrjszh + '\'' +
", jsrxm='" + jsrxm + '\'' +
", jsrxctjrq='" + jsrxctjrq + '\'' +
", jsrjsztxm='" + jsrjsztxm + '\'' +
", jsrjszg='" + jsrjszg + '\'' +
", yyyxm='" + yyyxm + '\'' +
", yyyyyz='" + yyyyyz + '\'' +
", yyydh='" + yyydh + '\'' +
", ghcjmc='" + ghcjmc + '\'' +
", ghcjlxr='" + ghcjlxr + '\'' +
", ghcjdh='" + ghcjdh + '\'' +
", hzzl='" + hzzl + '\'' +
", szzl='" + szzl + '\'' +
", qydj='" + qydj + '\'' +
", hwxz='" + hwxz + '\'' +
", cjrq='" + cjrq + '\'' +
", aqss='" + aqss + '\'' +
", ltms='" + ltms + '\'' +
", wfjl='" + wfjl + '\'' +
", djmj='" + djmj + '\'' +
", ytglmj='" + ytglmj + '\'' +
", yjclbf='" + yjclbf + '\'' +
", bz='" + bz + '\'' +
", createTime='" + createTime + '\'' +
", isDel=" + isDel +
", creater=" + creater +
'}';
}
}
| 7,251 | 0.505389 | 0.504526 | 288 | 23.163195 | 13.741326 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.434028 | false | false | 1 |
a6bf6d193b6f6a95ead4923e5f48a2d9b9165b80 | 33,792,802,729,363 | 8f52a0130e0f0380576d90775b1219e0afec1415 | /app/src/main/java/org/happymtb/unofficial/adapter/ListHomeAdapter.java | 77a2d9edaaef1b5a179f797f8c2886eec4351098 | [] | no_license | tanion/happymtb | https://github.com/tanion/happymtb | 38a47678fb5f8a960aa7000929c980eb6c29250c | 080e563e43190d2d37533c41fa1ae1dba7622aed | refs/heads/main | 2020-12-20T23:06:10.339000 | 2015-09-28T07:39:48 | 2015-09-28T07:39:48 | 32,138,256 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.happymtb.unofficial.adapter;
import java.util.ArrayList;
import java.util.List;
import org.happymtb.unofficial.view.HomeRowView;
import org.happymtb.unofficial.item.Home;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
public class ListHomeAdapter extends BaseAdapter {
private Context mContext;
private List<Home> mHomes = new ArrayList<Home>();
public ListHomeAdapter(Context context, List<Home> Homes) {
mContext = context;
mHomes = Homes;
}
@Override
public int getCount() {
return mHomes.size();
}
@Override
public Home getItem(int position) {
return mHomes.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
HomeRowView homeRowView;
if (convertView == null) {
homeRowView = new HomeRowView(mContext);
} else {
homeRowView = (HomeRowView) convertView;
}
homeRowView.setTitle(mHomes.get(position).getTitle());
homeRowView.setText(mHomes.get(position).getText());
homeRowView.setDate(mHomes.get(position).getDate());
return homeRowView;
}
} | UTF-8 | Java | 1,212 | java | ListHomeAdapter.java | Java | [] | null | [] | package org.happymtb.unofficial.adapter;
import java.util.ArrayList;
import java.util.List;
import org.happymtb.unofficial.view.HomeRowView;
import org.happymtb.unofficial.item.Home;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
public class ListHomeAdapter extends BaseAdapter {
private Context mContext;
private List<Home> mHomes = new ArrayList<Home>();
public ListHomeAdapter(Context context, List<Home> Homes) {
mContext = context;
mHomes = Homes;
}
@Override
public int getCount() {
return mHomes.size();
}
@Override
public Home getItem(int position) {
return mHomes.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
HomeRowView homeRowView;
if (convertView == null) {
homeRowView = new HomeRowView(mContext);
} else {
homeRowView = (HomeRowView) convertView;
}
homeRowView.setTitle(mHomes.get(position).getTitle());
homeRowView.setText(mHomes.get(position).getText());
homeRowView.setDate(mHomes.get(position).getDate());
return homeRowView;
}
} | 1,212 | 0.747525 | 0.747525 | 55 | 21.054546 | 19.786514 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.436364 | false | false | 1 |
0ccd2869c4f0d7a62e58e71c6adf5f589c4be354 | 35,648,228,579,557 | 320d75a57835dd5f818c1697f93987cce2489f99 | /http-core/src/main/java/com/liupeiqing/http/core/intercept/AbstractCicadaInterceptorAdapter.java | 7b479db766303457ed45427b2edf26ebe94b38ac | [] | no_license | peiqingliu/lightweightWebframework | https://github.com/peiqingliu/lightweightWebframework | 044e851e1cb3d0902c8f734ec1c00751d811413c | 4daf7dea1ec2a6626e5504d18cbf4e20cce0512c | refs/heads/master | 2020-04-25T08:01:43.155000 | 2019-02-26T03:41:41 | 2019-02-26T03:41:41 | 172,632,742 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.liupeiqing.http.core.intercept;
import com.liupeiqing.http.core.action.param.Param;
import com.liupeiqing.http.core.context.HttpContext;
/**
* @author liupeqing
* @date 2019/2/25 20:15
*/
public abstract class AbstractCicadaInterceptorAdapter extends CicadaInterceptor{
@Override
protected boolean before(HttpContext context, Param param) throws Exception {
return true;
}
@Override
protected void after(HttpContext context, Param param) throws Exception {
}
}
| UTF-8 | Java | 512 | java | AbstractCicadaInterceptorAdapter.java | Java | [
{
"context": "ing.http.core.context.HttpContext;\n\n/**\n * @author liupeqing\n * @date 2019/2/25 20:15\n */\npublic abstract clas",
"end": 175,
"score": 0.9996488094329834,
"start": 166,
"tag": "USERNAME",
"value": "liupeqing"
}
] | null | [] | package com.liupeiqing.http.core.intercept;
import com.liupeiqing.http.core.action.param.Param;
import com.liupeiqing.http.core.context.HttpContext;
/**
* @author liupeqing
* @date 2019/2/25 20:15
*/
public abstract class AbstractCicadaInterceptorAdapter extends CicadaInterceptor{
@Override
protected boolean before(HttpContext context, Param param) throws Exception {
return true;
}
@Override
protected void after(HttpContext context, Param param) throws Exception {
}
}
| 512 | 0.746094 | 0.724609 | 20 | 24.6 | 28.182264 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3 | false | false | 1 |
dcb0f1dfa8a3d38228f7dadd28578f7e6a00c7d6 | 2,430,951,550,896 | 6bd3740712d0358302f55ec9b01fc5512cbe1e3f | /app/src/main/java/com/example/student/teamproject/SignInFragment.java | 609a031b340376db97fe43779111096800644dc4 | [] | no_license | DoxPL/TeamProject | https://github.com/DoxPL/TeamProject | 00917c66609d7f2963d659c89ab66c639367e990 | 275974e317765c6e7ace0469301bb8d9332d3a04 | refs/heads/master | 2020-03-31T02:55:15.147000 | 2019-02-28T23:09:56 | 2019-02-28T23:09:56 | 151,844,676 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.student.teamproject;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SignInFragment extends Fragment {
private static final String TAG = "SignInFragment";
private OnFragmentInteractionListener mListener;
private List<NotesModel> notesList;
// default constructor
public SignInFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_sign_in, container, false);
return view;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
try {
View fragmentSignInView = (View) getActivity().findViewById(R.id.fragment_sign_in_id);
if (fragmentSignInView != null) {
KeyboardUtils.setupKeyboardVisibility(fragmentSignInView, getActivity());
}
} catch (NullPointerException exception) {
Log.e(TAG, "Fragment view is null. @onViewCreated(..)");
exception.printStackTrace();
}
try {
TopBarUtils.setTopBar(
(AppCompatActivity) getActivity(), view, getString(R.string.signing_in));
} catch (NullPointerException e) {
Log.e(TAG, "Cannot get activity. @onViewCreated(..)");
}
SqliteDbUtils db = new SqliteDbUtils(getContext());
db.addItem("date", "title1", "desc", true);
db.addItem("date", "title2", "desc", true);
db.addItem("date", "title3", "desc", true);
db.addItem("date", "title4", "desc", true);
// db.deleteItem("date", "title1");
// db.deleteItem("date", "title2");
// db.deleteItem("date", "title3");
db.deleteItem("date", "title4");
notesList = db.getList();
setButtons();
}
@Override
public void onDetach() {
super.onDetach();
try {
FragmentActivity activity = getActivity();
if (activity != null) {
KeyboardUtils.hideSoftKeyboard(getActivity());
}
} catch (NullPointerException exception) {
Log.e(TAG, "Cannot get activity. @onDetach(..)");
exception.printStackTrace();
}
mListener = null;
}
private void setButtons() {
try {
Button getListBut =
(Button) getActivity().findViewById(R.id.sign_in_get_list_button_id);
Button eyeButton = (Button) getActivity().findViewById(R.id.eye_button_id);
final EditText emailInput =
(EditText) getActivity().findViewById(R.id.sign_in_email_input_id);
final EditText passwordInput =
(EditText) getActivity().findViewById(R.id.sign_in_password_input_id);
Button signInButton = (Button) getActivity().findViewById(R.id.sign_in_login_button_id);
Button signupButton =
(Button) getActivity().findViewById(R.id.sign_in_sign_up_button_id);
final List<NotesModel> fList = notesList;
getListBut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("list", fList.toString());
Log.d("list.size", "" + fList.size());
}
});
eyeButton.setOnClickListener(new View.OnClickListener() {
boolean isClicked = false;
@Override
public void onClick(View view) {
if (!isClicked) {
passwordInput.setTransformationMethod(null);
isClicked = true;
} else {
passwordInput.setTransformationMethod(new PasswordTransformationMethod());
isClicked = false;
}
passwordInput.setSelection(passwordInput.getText().length());
}
});
signInButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String email = emailInput.getText().toString();
String password = passwordInput.getText().toString();
signIn(email, password);
}
});
signupButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Fragment fragment = new SignUpFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.contentContainer, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
} catch (NullPointerException exception) {
Log.e(TAG, "Some button is null. @setButtons()");
exception.printStackTrace();
}
}
private void signIn(final String email, final String password) {
if (email.equals("root") && password.equals("foobar")) {
Toast.makeText(getContext(), R.string.correct_login_data, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(
getContext(), R.string.incorrect_login_data, Toast.LENGTH_LONG).show();
}
String apiUrl = getString(R.string.calendar_api_link1);
if (getContext() != null) {
Object queue = Volley.newRequestQueue(getContext());
StringRequest postRequest = new StringRequest(Request.Method.POST, apiUrl,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
Log.d(TAG, "UserResponse: " + response);
// Gson gson = new GsonBuilder().create();
// UserModel feed = gson.fromJson(response, UserModel.class);
//
// if (feed.data != null) {
// UserModel.id = feed.data.id
// UserModel.name = "${feed.data.first_name} ${feed.data.last_name}"
// UserModel.email = feed.data.email
// }
} catch (Exception exception) {
Log.e(TAG, "@onResponse(..)");
exception.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
String errorText = "Błąd połączenia z serwerem.";
Toast.makeText(getContext(), errorText, Toast.LENGTH_LONG).show();
Log.e(TAG, error.toString());
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("login", email);
params.put("passwd", password);
Log.d(TAG, "Params: " + params + " @getParams()");
return params;
}
};
((RequestQueue) queue).add(postRequest);
} else {
Log.e(TAG, "Response: context is null. @signIn(..)");
}
}
// String body = "";
// //get status code here
// String statusCode = String.valueOf(error.networkResponse.statusCode);
// //get response body and parse with appropriate encoding
//
// if(error.networkResponse.data!=null) {
// try {
// body = new String(
// error.networkResponse.data,"UTF-8");
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
// }
//
// Log.d(TAG, "Body: " + body + " @onErrorResponse(..)");
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
| UTF-8 | Java | 10,437 | java | SignInFragment.java | Java | [
{
"context": " if (email.equals(\"root\") && password.equals(\"foobar\")) {\n Toast.makeText(getContext(), R.s",
"end": 6412,
"score": 0.9994432330131531,
"start": 6406,
"tag": "PASSWORD",
"value": "foobar"
},
{
"context": ", email);\n params.put(\"p... | null | [] | package com.example.student.teamproject;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SignInFragment extends Fragment {
private static final String TAG = "SignInFragment";
private OnFragmentInteractionListener mListener;
private List<NotesModel> notesList;
// default constructor
public SignInFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_sign_in, container, false);
return view;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
try {
View fragmentSignInView = (View) getActivity().findViewById(R.id.fragment_sign_in_id);
if (fragmentSignInView != null) {
KeyboardUtils.setupKeyboardVisibility(fragmentSignInView, getActivity());
}
} catch (NullPointerException exception) {
Log.e(TAG, "Fragment view is null. @onViewCreated(..)");
exception.printStackTrace();
}
try {
TopBarUtils.setTopBar(
(AppCompatActivity) getActivity(), view, getString(R.string.signing_in));
} catch (NullPointerException e) {
Log.e(TAG, "Cannot get activity. @onViewCreated(..)");
}
SqliteDbUtils db = new SqliteDbUtils(getContext());
db.addItem("date", "title1", "desc", true);
db.addItem("date", "title2", "desc", true);
db.addItem("date", "title3", "desc", true);
db.addItem("date", "title4", "desc", true);
// db.deleteItem("date", "title1");
// db.deleteItem("date", "title2");
// db.deleteItem("date", "title3");
db.deleteItem("date", "title4");
notesList = db.getList();
setButtons();
}
@Override
public void onDetach() {
super.onDetach();
try {
FragmentActivity activity = getActivity();
if (activity != null) {
KeyboardUtils.hideSoftKeyboard(getActivity());
}
} catch (NullPointerException exception) {
Log.e(TAG, "Cannot get activity. @onDetach(..)");
exception.printStackTrace();
}
mListener = null;
}
private void setButtons() {
try {
Button getListBut =
(Button) getActivity().findViewById(R.id.sign_in_get_list_button_id);
Button eyeButton = (Button) getActivity().findViewById(R.id.eye_button_id);
final EditText emailInput =
(EditText) getActivity().findViewById(R.id.sign_in_email_input_id);
final EditText passwordInput =
(EditText) getActivity().findViewById(R.id.sign_in_password_input_id);
Button signInButton = (Button) getActivity().findViewById(R.id.sign_in_login_button_id);
Button signupButton =
(Button) getActivity().findViewById(R.id.sign_in_sign_up_button_id);
final List<NotesModel> fList = notesList;
getListBut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("list", fList.toString());
Log.d("list.size", "" + fList.size());
}
});
eyeButton.setOnClickListener(new View.OnClickListener() {
boolean isClicked = false;
@Override
public void onClick(View view) {
if (!isClicked) {
passwordInput.setTransformationMethod(null);
isClicked = true;
} else {
passwordInput.setTransformationMethod(new PasswordTransformationMethod());
isClicked = false;
}
passwordInput.setSelection(passwordInput.getText().length());
}
});
signInButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String email = emailInput.getText().toString();
String password = passwordInput.getText().toString();
signIn(email, password);
}
});
signupButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Fragment fragment = new SignUpFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.contentContainer, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
} catch (NullPointerException exception) {
Log.e(TAG, "Some button is null. @setButtons()");
exception.printStackTrace();
}
}
private void signIn(final String email, final String password) {
if (email.equals("root") && password.equals("<PASSWORD>")) {
Toast.makeText(getContext(), R.string.correct_login_data, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(
getContext(), R.string.incorrect_login_data, Toast.LENGTH_LONG).show();
}
String apiUrl = getString(R.string.calendar_api_link1);
if (getContext() != null) {
Object queue = Volley.newRequestQueue(getContext());
StringRequest postRequest = new StringRequest(Request.Method.POST, apiUrl,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
Log.d(TAG, "UserResponse: " + response);
// Gson gson = new GsonBuilder().create();
// UserModel feed = gson.fromJson(response, UserModel.class);
//
// if (feed.data != null) {
// UserModel.id = feed.data.id
// UserModel.name = "${feed.data.first_name} ${feed.data.last_name}"
// UserModel.email = feed.data.email
// }
} catch (Exception exception) {
Log.e(TAG, "@onResponse(..)");
exception.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
String errorText = "Błąd połączenia z serwerem.";
Toast.makeText(getContext(), errorText, Toast.LENGTH_LONG).show();
Log.e(TAG, error.toString());
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("login", email);
params.put("passwd", <PASSWORD>);
Log.d(TAG, "Params: " + params + " @getParams()");
return params;
}
};
((RequestQueue) queue).add(postRequest);
} else {
Log.e(TAG, "Response: context is null. @signIn(..)");
}
}
// String body = "";
// //get status code here
// String statusCode = String.valueOf(error.networkResponse.statusCode);
// //get response body and parse with appropriate encoding
//
// if(error.networkResponse.data!=null) {
// try {
// body = new String(
// error.networkResponse.data,"UTF-8");
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
// }
//
// Log.d(TAG, "Body: " + body + " @onErrorResponse(..)");
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
| 10,443 | 0.543564 | 0.542126 | 273 | 37.216118 | 28.89315 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.611722 | false | false | 1 |
a5acb82dcc4f2d2739dd70159d2d1159efece2ef | 36,378,373,022,961 | 4d14cbd90f8c24af1ee82b46560f667d55449bb8 | /Main.java | e12299c5f97a68fb9863528c3b77820aefb73783 | [] | no_license | hscragg/project3 | https://github.com/hscragg/project3 | ec7c5a8d402cb844170c5a5409b65c05748fba9e | cdd5aa5bbdd1f86edc8f263739d990faf4c456e2 | refs/heads/master | 2023-01-24T15:53:18.614000 | 2020-11-10T17:04:19 | 2020-11-10T17:04:19 | 310,310,823 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Scanner;
class Main {
public static void main(String[] args) {
System.out.println("Welcome to Ms. Benny's Class!");
int[] seatNumbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
String[] names = new String[15];
Scanner scan = new Scanner(System.in);
for (int i = 0; i < 15; i++) {
System.out.println(" What is the students name? ");
names[i] = scan.next();
}
int i = 0;
while (i < 15) {
System.out.println(names[i] + " Sits at chair " + seatNumbers[i]);
i++;
}
}
}
| UTF-8 | Java | 562 | java | Main.java | Java | [
{
"context": "g[] args) {\n System.out.println(\"Welcome to Ms. Benny's Class!\");\n int[] seatNumbers = { 1, 2, 3, 4,",
"end": 127,
"score": 0.9868944883346558,
"start": 122,
"tag": "NAME",
"value": "Benny"
}
] | null | [] | import java.util.Scanner;
class Main {
public static void main(String[] args) {
System.out.println("Welcome to Ms. Benny's Class!");
int[] seatNumbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
String[] names = new String[15];
Scanner scan = new Scanner(System.in);
for (int i = 0; i < 15; i++) {
System.out.println(" What is the students name? ");
names[i] = scan.next();
}
int i = 0;
while (i < 15) {
System.out.println(names[i] + " Sits at chair " + seatNumbers[i]);
i++;
}
}
}
| 562 | 0.544484 | 0.492883 | 21 | 25.761906 | 23.966057 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.238095 | false | false | 1 |
d633bfcc5fb0075539fd69d667872b7803bc6845 | 38,671,885,548,777 | 02d48f5aaefd4c73c3169100d61a807b7a5a3107 | /src/main/java/com/linkage/contacts/server/dao/mybatis/impl/MybatisUserInfoDaoImpl.java | 2580feadb8f45ba5feb35d6141ac8b456cce8249 | [] | no_license | wj20130722/StudentsContacts | https://github.com/wj20130722/StudentsContacts | bf1db0925b08c5b3e3e00343d997290e6d384e44 | f27645175eb6b6d880023f241e40d599ab24ce3c | refs/heads/master | 2021-01-22T09:48:15.846000 | 2014-08-26T06:56:14 | 2014-08-26T06:56:14 | 23,340,999 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.linkage.contacts.server.dao.mybatis.impl;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.linkage.contacts.core.exception.ContactException;
import com.linkage.contacts.server.dao.UserInfoDAO;
import com.linkage.contacts.server.entity.UserInfo;
import com.linkage.contacts.server.mybatis.persistence.UserInfoMapper;
import com.linkage.contacts.server.vo.FormUserInfo;
import com.linkage.contacts.server.vo.FormUserInfo2;
import com.linkage.mybatis.util.CriteriaManager;
import com.linkage.mybatis.util.Restrictions;
@Repository("mybatisUserInfoDao")
public class MybatisUserInfoDaoImpl implements UserInfoDAO
{
@Autowired
private UserInfoMapper userInfoMapper;
@Override
public void insert(UserInfo userInfo)
{
int count = userInfoMapper.insert(userInfo);
if (count != 1)
throw new ContactException("影响了" + count + "条记录(正确的应该是1条),可能是Mybatis映射SQL语句错误,请检查SQL\n");
}
@Override
public void update(UserInfo userInfo)
{
int count = userInfoMapper.updateByPrimaryKey(userInfo);
if (count != 1)
throw new ContactException("影响了" + count + "条记录(正确的应该是1条),可能是Mybatis映射SQL语句错误,请检查SQL\n");
}
@Override
public void delete(UserInfo userInfo)
{
int count = userInfoMapper.deleteByPrimaryKey(userInfo.getUser_id());
if (count != 1)
throw new ContactException("影响了" + count + "条记录(正确的应该是1条),可能是Mybatis映射SQL语句错误,请检查SQL\n");
}
@Override
public UserInfo selectByPrimaryKey(int user_id)
{
return userInfoMapper.selectByPrimaryKey(user_id);
}
@Override
public UserInfo selectByTokenid(String tokenid)
{
UserInfo userInfo = new UserInfo();
CriteriaManager cri = new CriteriaManager();
cri.or().add(Restrictions.equalTo("access_token", tokenid));
List<UserInfo> userinfos = userInfoMapper.selectByWhereCondition(cri);
if(null!=userinfos && userinfos.size()>0)
userInfo = userinfos.get(0);
return userInfo;
}
@Override
public UserInfo selectByUserName(String username)
{
UserInfo userInfo = new UserInfo();
CriteriaManager cri = new CriteriaManager();
cri.or().add(Restrictions.equalTo("user_name", username));
List<UserInfo> userinfos = userInfoMapper.selectByWhereCondition(cri);
if(null!=userinfos && userinfos.size()>0)
userInfo = userinfos.get(0);
return userInfo;
}
@Override
public UserInfo selectByPhoneNum(String phonenum)
{
UserInfo userInfo = new UserInfo();
CriteriaManager cri = new CriteriaManager();
cri.or().add(Restrictions.equalTo("phonenum", phonenum));
List<UserInfo> userinfos = userInfoMapper.selectByWhereCondition(cri);
if(null!=userinfos && userinfos.size()>0)
userInfo = userinfos.get(0);
return userInfo;
}
@Override
public UserInfo selectByEmail(String email)
{
UserInfo userInfo = new UserInfo();
CriteriaManager cri = new CriteriaManager();
cri.or().add(Restrictions.equalTo("mail", email));
List<UserInfo> userinfos = userInfoMapper.selectByWhereCondition(cri);
if(null!=userinfos && userinfos.size()>0)
userInfo = userinfos.get(0);
return userInfo;
}
@Override
public void saveUserInfo(FormUserInfo userInfo)
{
int count = userInfoMapper.insertUserInfo(userInfo);
if (count != 1)
throw new ContactException("影响了" + count + "条记录(正确的应该是1条),可能是Mybatis映射SQL语句错误,请检查SQL\n");
}
@Override
public int countByUserInfo(String user_name, int college_id, int university_id, int year)
{
CriteriaManager cri = new CriteriaManager();
cri.or().add(Restrictions.equalTo("user_name", user_name)).add(Restrictions.equalTo("college_id", college_id))
.add(Restrictions.equalTo("university_id", university_id)).add(Restrictions.equalTo("year", year));
return userInfoMapper.countByWhereCondition(cri);
}
@Override
public void updateUserInfo(FormUserInfo userInfo)
{
int count = userInfoMapper.updateUserInfo(userInfo);
if (count != 1)
throw new ContactException("影响了" + count + "条记录(正确的应该是1条),可能是Mybatis映射SQL语句错误,请检查SQL\n");
}
@Override
public void updatePersonalInfo(FormUserInfo2 userInfo)
{
int count = userInfoMapper.updatePersonalInfo(userInfo);
if (count != 1)
throw new ContactException("影响了" + count + "条记录(正确的应该是1条),可能是Mybatis映射SQL语句错误,请检查SQL\n");
}
@Override
public List<UserInfo> getSysAdmin(int university_id)
{
CriteriaManager cri = new CriteriaManager();
cri.or().add(Restrictions.equalTo("university_id", university_id))
.add(Restrictions.equalTo("super_admin", 1));
List<UserInfo> list = userInfoMapper.selectByWhereCondition(cri);
if(null == list)
list = new ArrayList<UserInfo>();
return list;
}
@Override
public int count2ByUserInfo(String user_name, String xuehao, int university_id,int year)
{
CriteriaManager cri = new CriteriaManager();
cri.or().add(Restrictions.equalTo("user_name", user_name)).add(Restrictions.equalTo("xuehao", xuehao))
.add(Restrictions.equalTo("university_id", university_id)).add(Restrictions.equalTo("year", year));
return userInfoMapper.countByWhereCondition(cri);
}
@Override
public int countByEmail(String email)
{
CriteriaManager cri = new CriteriaManager();
cri.or().add(Restrictions.equalTo("mail", email));
return userInfoMapper.countByWhereCondition(cri);
}
@Override
public int countByPhoneNum(String phonenum)
{
CriteriaManager cri = new CriteriaManager();
cri.or().add(Restrictions.equalTo("phonenum", phonenum));
return userInfoMapper.countByWhereCondition(cri);
}
@Override
public int countByQQ(String qq)
{
CriteriaManager cri = new CriteriaManager();
cri.or().add(Restrictions.equalTo("qq", qq));
return userInfoMapper.countByWhereCondition(cri);
}
@Override
public UserInfo selectByXuehao(String xuehao)
{
UserInfo userInfo = new UserInfo();
CriteriaManager cri = new CriteriaManager();
cri.or().add(Restrictions.equalTo("xuehao", xuehao))
.add(Restrictions.equalTo("is_authentication", 1));
List<UserInfo> userinfos = userInfoMapper.selectByWhereCondition(cri);
if(null!=userinfos && userinfos.size()>0)
userInfo = userinfos.get(0);
return userInfo;
}
@Override
public int countByEmailUser(String email, int user_id)
{
CriteriaManager cri = new CriteriaManager();
cri.or().add(Restrictions.equalTo("mail", email)).add(Restrictions.notEqualTo("user_id", user_id));
return userInfoMapper.countByWhereCondition(cri);
}
@Override
public int countByPhoneNumUser(String phonenum, int user_id)
{
CriteriaManager cri = new CriteriaManager();
cri.or().add(Restrictions.equalTo("phonenum", phonenum)).add(Restrictions.notEqualTo("user_id", user_id));
return userInfoMapper.countByWhereCondition(cri);
}
@Override
public int countByQQUser(String qq, int user_id)
{
CriteriaManager cri = new CriteriaManager();
cri.or().add(Restrictions.equalTo("qq", qq)).add(Restrictions.notEqualTo("user_id", user_id));
return userInfoMapper.countByWhereCondition(cri);
}
}
| UTF-8 | Java | 7,570 | java | MybatisUserInfoDaoImpl.java | Java | [] | null | [] | package com.linkage.contacts.server.dao.mybatis.impl;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.linkage.contacts.core.exception.ContactException;
import com.linkage.contacts.server.dao.UserInfoDAO;
import com.linkage.contacts.server.entity.UserInfo;
import com.linkage.contacts.server.mybatis.persistence.UserInfoMapper;
import com.linkage.contacts.server.vo.FormUserInfo;
import com.linkage.contacts.server.vo.FormUserInfo2;
import com.linkage.mybatis.util.CriteriaManager;
import com.linkage.mybatis.util.Restrictions;
@Repository("mybatisUserInfoDao")
public class MybatisUserInfoDaoImpl implements UserInfoDAO
{
@Autowired
private UserInfoMapper userInfoMapper;
@Override
public void insert(UserInfo userInfo)
{
int count = userInfoMapper.insert(userInfo);
if (count != 1)
throw new ContactException("影响了" + count + "条记录(正确的应该是1条),可能是Mybatis映射SQL语句错误,请检查SQL\n");
}
@Override
public void update(UserInfo userInfo)
{
int count = userInfoMapper.updateByPrimaryKey(userInfo);
if (count != 1)
throw new ContactException("影响了" + count + "条记录(正确的应该是1条),可能是Mybatis映射SQL语句错误,请检查SQL\n");
}
@Override
public void delete(UserInfo userInfo)
{
int count = userInfoMapper.deleteByPrimaryKey(userInfo.getUser_id());
if (count != 1)
throw new ContactException("影响了" + count + "条记录(正确的应该是1条),可能是Mybatis映射SQL语句错误,请检查SQL\n");
}
@Override
public UserInfo selectByPrimaryKey(int user_id)
{
return userInfoMapper.selectByPrimaryKey(user_id);
}
@Override
public UserInfo selectByTokenid(String tokenid)
{
UserInfo userInfo = new UserInfo();
CriteriaManager cri = new CriteriaManager();
cri.or().add(Restrictions.equalTo("access_token", tokenid));
List<UserInfo> userinfos = userInfoMapper.selectByWhereCondition(cri);
if(null!=userinfos && userinfos.size()>0)
userInfo = userinfos.get(0);
return userInfo;
}
@Override
public UserInfo selectByUserName(String username)
{
UserInfo userInfo = new UserInfo();
CriteriaManager cri = new CriteriaManager();
cri.or().add(Restrictions.equalTo("user_name", username));
List<UserInfo> userinfos = userInfoMapper.selectByWhereCondition(cri);
if(null!=userinfos && userinfos.size()>0)
userInfo = userinfos.get(0);
return userInfo;
}
@Override
public UserInfo selectByPhoneNum(String phonenum)
{
UserInfo userInfo = new UserInfo();
CriteriaManager cri = new CriteriaManager();
cri.or().add(Restrictions.equalTo("phonenum", phonenum));
List<UserInfo> userinfos = userInfoMapper.selectByWhereCondition(cri);
if(null!=userinfos && userinfos.size()>0)
userInfo = userinfos.get(0);
return userInfo;
}
@Override
public UserInfo selectByEmail(String email)
{
UserInfo userInfo = new UserInfo();
CriteriaManager cri = new CriteriaManager();
cri.or().add(Restrictions.equalTo("mail", email));
List<UserInfo> userinfos = userInfoMapper.selectByWhereCondition(cri);
if(null!=userinfos && userinfos.size()>0)
userInfo = userinfos.get(0);
return userInfo;
}
@Override
public void saveUserInfo(FormUserInfo userInfo)
{
int count = userInfoMapper.insertUserInfo(userInfo);
if (count != 1)
throw new ContactException("影响了" + count + "条记录(正确的应该是1条),可能是Mybatis映射SQL语句错误,请检查SQL\n");
}
@Override
public int countByUserInfo(String user_name, int college_id, int university_id, int year)
{
CriteriaManager cri = new CriteriaManager();
cri.or().add(Restrictions.equalTo("user_name", user_name)).add(Restrictions.equalTo("college_id", college_id))
.add(Restrictions.equalTo("university_id", university_id)).add(Restrictions.equalTo("year", year));
return userInfoMapper.countByWhereCondition(cri);
}
@Override
public void updateUserInfo(FormUserInfo userInfo)
{
int count = userInfoMapper.updateUserInfo(userInfo);
if (count != 1)
throw new ContactException("影响了" + count + "条记录(正确的应该是1条),可能是Mybatis映射SQL语句错误,请检查SQL\n");
}
@Override
public void updatePersonalInfo(FormUserInfo2 userInfo)
{
int count = userInfoMapper.updatePersonalInfo(userInfo);
if (count != 1)
throw new ContactException("影响了" + count + "条记录(正确的应该是1条),可能是Mybatis映射SQL语句错误,请检查SQL\n");
}
@Override
public List<UserInfo> getSysAdmin(int university_id)
{
CriteriaManager cri = new CriteriaManager();
cri.or().add(Restrictions.equalTo("university_id", university_id))
.add(Restrictions.equalTo("super_admin", 1));
List<UserInfo> list = userInfoMapper.selectByWhereCondition(cri);
if(null == list)
list = new ArrayList<UserInfo>();
return list;
}
@Override
public int count2ByUserInfo(String user_name, String xuehao, int university_id,int year)
{
CriteriaManager cri = new CriteriaManager();
cri.or().add(Restrictions.equalTo("user_name", user_name)).add(Restrictions.equalTo("xuehao", xuehao))
.add(Restrictions.equalTo("university_id", university_id)).add(Restrictions.equalTo("year", year));
return userInfoMapper.countByWhereCondition(cri);
}
@Override
public int countByEmail(String email)
{
CriteriaManager cri = new CriteriaManager();
cri.or().add(Restrictions.equalTo("mail", email));
return userInfoMapper.countByWhereCondition(cri);
}
@Override
public int countByPhoneNum(String phonenum)
{
CriteriaManager cri = new CriteriaManager();
cri.or().add(Restrictions.equalTo("phonenum", phonenum));
return userInfoMapper.countByWhereCondition(cri);
}
@Override
public int countByQQ(String qq)
{
CriteriaManager cri = new CriteriaManager();
cri.or().add(Restrictions.equalTo("qq", qq));
return userInfoMapper.countByWhereCondition(cri);
}
@Override
public UserInfo selectByXuehao(String xuehao)
{
UserInfo userInfo = new UserInfo();
CriteriaManager cri = new CriteriaManager();
cri.or().add(Restrictions.equalTo("xuehao", xuehao))
.add(Restrictions.equalTo("is_authentication", 1));
List<UserInfo> userinfos = userInfoMapper.selectByWhereCondition(cri);
if(null!=userinfos && userinfos.size()>0)
userInfo = userinfos.get(0);
return userInfo;
}
@Override
public int countByEmailUser(String email, int user_id)
{
CriteriaManager cri = new CriteriaManager();
cri.or().add(Restrictions.equalTo("mail", email)).add(Restrictions.notEqualTo("user_id", user_id));
return userInfoMapper.countByWhereCondition(cri);
}
@Override
public int countByPhoneNumUser(String phonenum, int user_id)
{
CriteriaManager cri = new CriteriaManager();
cri.or().add(Restrictions.equalTo("phonenum", phonenum)).add(Restrictions.notEqualTo("user_id", user_id));
return userInfoMapper.countByWhereCondition(cri);
}
@Override
public int countByQQUser(String qq, int user_id)
{
CriteriaManager cri = new CriteriaManager();
cri.or().add(Restrictions.equalTo("qq", qq)).add(Restrictions.notEqualTo("user_id", user_id));
return userInfoMapper.countByWhereCondition(cri);
}
}
| 7,570 | 0.722376 | 0.718638 | 219 | 30.977169 | 28.874384 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.511415 | false | false | 1 |
b96b814d3fe60d10e09203206d7484efed1d7cd3 | 38,019,050,519,834 | 983733d2c87ede1b1ba7a5612ba12ff2552be23d | /app/src/main/java/com/example/evelina/befit/model/MyReceiver.java | 0de619ef01d19e5fd29f97463949dee9f74759fe | [] | no_license | ivetmetodieva/Be-fit | https://github.com/ivetmetodieva/Be-fit | a029766efe1db4593037e8861099f8e7ae9a9e21 | e57ce70a84ee05936c83b6bf04e3bcfd7972545a | refs/heads/master | 2021-01-17T15:47:05.716000 | 2016-10-17T21:30:38 | 2016-10-17T21:30:38 | 69,040,930 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.evelina.befit.model;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import com.example.evelina.befit.LoginActivity;
import com.example.evelina.befit.R;
public class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
long alarmTime = (long) intent.getExtras().get("ALARM TIME");
String username = intent.getStringExtra("username");
String currentUser = context.getSharedPreferences("Login", Context.MODE_PRIVATE).getString("currentUser", "no Users");
if (currentUser.equals(username)) {
if (!(System.currentTimeMillis() < alarmTime)) {
Intent resultIntent = new Intent(context, LoginActivity.class);
long[] pattern = {0, 300, 0};
PendingIntent pi = PendingIntent.getActivity(context, 01234, resultIntent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.logo)
.setContentTitle("Be fit")
.setContentText("Start training!")
.setVibrate(pattern);
mBuilder.setContentIntent(pi);
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(01234, mBuilder.build());
} else {
Intent resultIntent = new Intent(context, LoginActivity.class);
long[] pattern = {0, 300, 0};
PendingIntent pi = PendingIntent.getActivity(context, 01234, resultIntent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.logo)
.setContentTitle("Be fit")
.setContentText("You haven`t trained for a while.Start training!")
.setVibrate(pattern);
mBuilder.setContentIntent(pi);
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(01234, mBuilder.build());
}
}
}
}
| UTF-8 | Java | 2,787 | java | MyReceiver.java | Java | [
{
"context": "\n String username = intent.getStringExtra(\"username\");\n String currentUser = context.getShared",
"end": 677,
"score": 0.7299889922142029,
"start": 669,
"tag": "USERNAME",
"value": "username"
}
] | null | [] | package com.example.evelina.befit.model;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import com.example.evelina.befit.LoginActivity;
import com.example.evelina.befit.R;
public class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
long alarmTime = (long) intent.getExtras().get("ALARM TIME");
String username = intent.getStringExtra("username");
String currentUser = context.getSharedPreferences("Login", Context.MODE_PRIVATE).getString("currentUser", "no Users");
if (currentUser.equals(username)) {
if (!(System.currentTimeMillis() < alarmTime)) {
Intent resultIntent = new Intent(context, LoginActivity.class);
long[] pattern = {0, 300, 0};
PendingIntent pi = PendingIntent.getActivity(context, 01234, resultIntent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.logo)
.setContentTitle("Be fit")
.setContentText("Start training!")
.setVibrate(pattern);
mBuilder.setContentIntent(pi);
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(01234, mBuilder.build());
} else {
Intent resultIntent = new Intent(context, LoginActivity.class);
long[] pattern = {0, 300, 0};
PendingIntent pi = PendingIntent.getActivity(context, 01234, resultIntent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.logo)
.setContentTitle("Be fit")
.setContentText("You haven`t trained for a while.Start training!")
.setVibrate(pattern);
mBuilder.setContentIntent(pi);
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(01234, mBuilder.build());
}
}
}
}
| 2,787 | 0.639038 | 0.627198 | 61 | 44.688526 | 34.151802 | 136 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.786885 | false | false | 1 |
0f10c7a2de39a93bf485fd126fc50ce2aa5dc986 | 38,783,554,690,707 | 887bb7c98d3fd01551109f8f58b7bad958b3cf75 | /ruiTianXia_cus/src/main/java/com/lvdi/ruitianxia_cus/request/DeleteAddressRequest.java | f192ee23c3b1febf150212c6dd385c6bae2c3618 | [] | no_license | xubiao/LvdiCusAs | https://github.com/xubiao/LvdiCusAs | 996445707a4a79e95eaa4ef4d4724e7895d519d9 | ad7443ee289add46333d9fbf697ed7f17522aefe | refs/heads/master | 2021-01-09T20:22:26.280000 | 2016-05-29T03:57:34 | 2016-05-29T03:57:34 | 59,924,955 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lvdi.ruitianxia_cus.request;
import org.json.JSONObject;
import android.os.Handler;
import android.os.Message;
import com.ab.http.AbRequestParams;
import com.ab.util.AbJsonUtil;
import com.ab.util.AbLogUtil;
import com.ab.util.AbSharedUtil;
import com.lvdi.ruitianxia_cus.global.Cache;
import com.lvdi.ruitianxia_cus.global.Config;
import com.lvdi.ruitianxia_cus.global.HandleAction;
import com.lvdi.ruitianxia_cus.global.IStrutsAction;
import com.lvdi.ruitianxia_cus.global.MyApplication;
import com.lvdi.ruitianxia_cus.global.ShareKey;
import com.lvdi.ruitianxia_cus.model.AccountInfo;
import com.lvdi.ruitianxia_cus.model.BaseObject;
/**
* 删除地址 类的详细描述:
*
* @author XuBiao
* @version 1.0.1
* @time 2015年10月30日 下午8:00:57
*/
public class DeleteAddressRequest extends BaseRequest {
private Handler mHandler;
private String partyId;// 客户的partyId、
private String contactMechId;// 收货地址的contactMechId
private static DeleteAddressRequest loginRequest;
public static DeleteAddressRequest getInstance() {
if (null == loginRequest) {
loginRequest = new DeleteAddressRequest();
}
return loginRequest;
}
public void sendRequest(Handler handler, String... params) {
// TODO Auto-generated method stub
mHandler = handler;
partyId = params[0];
contactMechId = params[1];
httpConnect(false, this);
}
@Override
public String getPrefix() {
// TODO Auto-generated method stub
return Config.HttpURLPrefix;
}
@Override
public String getAction() {
// TODO Auto-generated method stub
return IStrutsAction.HTTP_DELETE_ADDRESS;
}
@Override
public AbRequestParams getPostParams() {
// TODO Auto-generated method stub
AbRequestParams params = new AbRequestParams();
params.put("partyId", partyId);
params.put("contactMechId", contactMechId);
return params;
}
@Override
public void onSuccess(int statusCode, String content) {
// TODO Auto-generated method stub
AbLogUtil.d(getClass(), "onSuccess--" + "statusCode:" + statusCode
+ "content:" + content);
BaseObject baseObject = (BaseObject) AbJsonUtil.fromJson(content,
BaseObject.class);
Message msg;
if (null != baseObject
&& baseObject.resultCode.equals(Config.HTTPSUCCESSRESULT)) {
msg = mHandler.obtainMessage(
HandleAction.HttpType.HTTP_DELETE_ADDRESS_SUCC,
Integer.parseInt(contactMechId), 0, "删除成功");
} else {
msg = mHandler.obtainMessage(
HandleAction.HttpType.HTTP_DELETE_ADDRESS_FAIL,
null != baseObject ? baseObject.errorMessage : "删除失败");
}
mHandler.sendMessage(msg);
}
@Override
public void onStart() {
// TODO Auto-generated method stub
}
@Override
public void onFinish() {
// TODO Auto-generated method stub
}
@Override
public void onFailure(int statusCode, String content, Throwable error) {
// TODO Auto-generated method stub
AbLogUtil.d(getClass(), "onFailure--" + "statusCode:" + statusCode
+ "content:" + content);
Message msg = mHandler.obtainMessage(
HandleAction.HttpType.HTTP_DELETE_ADDRESS_FAIL, "删除失败");
mHandler.sendMessage(msg);
}
}
| UTF-8 | Java | 3,131 | java | DeleteAddressRequest.java | Java | [
{
"context": "el.BaseObject;\n\n/**\n * 删除地址 类的详细描述:\n * \n * @author XuBiao\n * @version 1.0.1\n * @time 2015年10月30日 下午8:00:57\n",
"end": 694,
"score": 0.9971367716789246,
"start": 688,
"tag": "NAME",
"value": "XuBiao"
}
] | null | [] | package com.lvdi.ruitianxia_cus.request;
import org.json.JSONObject;
import android.os.Handler;
import android.os.Message;
import com.ab.http.AbRequestParams;
import com.ab.util.AbJsonUtil;
import com.ab.util.AbLogUtil;
import com.ab.util.AbSharedUtil;
import com.lvdi.ruitianxia_cus.global.Cache;
import com.lvdi.ruitianxia_cus.global.Config;
import com.lvdi.ruitianxia_cus.global.HandleAction;
import com.lvdi.ruitianxia_cus.global.IStrutsAction;
import com.lvdi.ruitianxia_cus.global.MyApplication;
import com.lvdi.ruitianxia_cus.global.ShareKey;
import com.lvdi.ruitianxia_cus.model.AccountInfo;
import com.lvdi.ruitianxia_cus.model.BaseObject;
/**
* 删除地址 类的详细描述:
*
* @author XuBiao
* @version 1.0.1
* @time 2015年10月30日 下午8:00:57
*/
public class DeleteAddressRequest extends BaseRequest {
private Handler mHandler;
private String partyId;// 客户的partyId、
private String contactMechId;// 收货地址的contactMechId
private static DeleteAddressRequest loginRequest;
public static DeleteAddressRequest getInstance() {
if (null == loginRequest) {
loginRequest = new DeleteAddressRequest();
}
return loginRequest;
}
public void sendRequest(Handler handler, String... params) {
// TODO Auto-generated method stub
mHandler = handler;
partyId = params[0];
contactMechId = params[1];
httpConnect(false, this);
}
@Override
public String getPrefix() {
// TODO Auto-generated method stub
return Config.HttpURLPrefix;
}
@Override
public String getAction() {
// TODO Auto-generated method stub
return IStrutsAction.HTTP_DELETE_ADDRESS;
}
@Override
public AbRequestParams getPostParams() {
// TODO Auto-generated method stub
AbRequestParams params = new AbRequestParams();
params.put("partyId", partyId);
params.put("contactMechId", contactMechId);
return params;
}
@Override
public void onSuccess(int statusCode, String content) {
// TODO Auto-generated method stub
AbLogUtil.d(getClass(), "onSuccess--" + "statusCode:" + statusCode
+ "content:" + content);
BaseObject baseObject = (BaseObject) AbJsonUtil.fromJson(content,
BaseObject.class);
Message msg;
if (null != baseObject
&& baseObject.resultCode.equals(Config.HTTPSUCCESSRESULT)) {
msg = mHandler.obtainMessage(
HandleAction.HttpType.HTTP_DELETE_ADDRESS_SUCC,
Integer.parseInt(contactMechId), 0, "删除成功");
} else {
msg = mHandler.obtainMessage(
HandleAction.HttpType.HTTP_DELETE_ADDRESS_FAIL,
null != baseObject ? baseObject.errorMessage : "删除失败");
}
mHandler.sendMessage(msg);
}
@Override
public void onStart() {
// TODO Auto-generated method stub
}
@Override
public void onFinish() {
// TODO Auto-generated method stub
}
@Override
public void onFailure(int statusCode, String content, Throwable error) {
// TODO Auto-generated method stub
AbLogUtil.d(getClass(), "onFailure--" + "statusCode:" + statusCode
+ "content:" + content);
Message msg = mHandler.obtainMessage(
HandleAction.HttpType.HTTP_DELETE_ADDRESS_FAIL, "删除失败");
mHandler.sendMessage(msg);
}
}
| 3,131 | 0.740595 | 0.73438 | 111 | 26.540541 | 20.338037 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.765766 | false | false | 1 |
2bb2d7d742891dcfc571cb896df00520bac5ccff | 3,410,204,086,236 | 61901e8ca9df09e91d3e8b7df5858598f843e156 | /Diabetes_Surveillance_Project/Suep_Native App/Suep/MyApplication/app/src/main/java/com/example/myapplication/MapsActivity.java | d5bc2d0e1f2a53b7e53ffcede585946a1a87f87c | [
"MIT"
] | permissive | paulmexa/Groupe1__INF4077 | https://github.com/paulmexa/Groupe1__INF4077 | b053c146824bf409ce5f56397a64dcc0b95c40cf | 42929fa5b5daa746166e2e9599dd46791a19bd33 | refs/heads/main | 2023-02-18T17:56:51.917000 | 2021-01-22T10:08:28 | 2021-01-22T10:08:28 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.myapplication;
import androidx.fragment.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Yaounde and move the camera
LatLng chuYaounde = new LatLng(3.863212572632019, 11.497202528074194);
LatLng centralHospitalYaounde = new LatLng(3.871255293040369, 11.510426383286989);
LatLng centrePasteur = new LatLng(3.872266884066907, 11.511386667941895);
LatLng hopitalGeneral = new LatLng(3.9071662829804397, 11.542086225614531);
LatLng genico = new LatLng(3.907819220596098, 11.53940401712668);
LatLng hopitalDjoungolo = new LatLng(3.88364902281552, 11.520266121255256);
LatLng hopitalCiteVerte = new LatLng(3.877531933062619, 11.48974772990604);
LatLng hopitalBiyemassi = new LatLng(3.8378931555102365, 11.485277481671247);
mMap.addMarker(new MarkerOptions().position(chuYaounde).title("CHU de Yaounde"));
mMap.addMarker(new MarkerOptions().position(centralHospitalYaounde).title("Hopital central de Yaounde"));
mMap.addMarker(new MarkerOptions().position(centrePasteur).title("Centre Pasteur"));
mMap.addMarker(new MarkerOptions().position(hopitalGeneral).title("Hopital général"));
mMap.addMarker(new MarkerOptions().position(genico).title("Hopital gyneco"));
mMap.addMarker(new MarkerOptions().position(hopitalDjoungolo).title("Hopital EPC djoungolo"));
mMap.addMarker(new MarkerOptions().position(hopitalCiteVerte).title("Hopital cité verte"));
mMap.addMarker(new MarkerOptions().position(hopitalBiyemassi).title("Hopital de district de Biyemassi"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(chuYaounde));
}
} | UTF-8 | Java | 3,197 | java | MapsActivity.java | Java | [] | null | [] | package com.example.myapplication;
import androidx.fragment.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Yaounde and move the camera
LatLng chuYaounde = new LatLng(3.863212572632019, 11.497202528074194);
LatLng centralHospitalYaounde = new LatLng(3.871255293040369, 11.510426383286989);
LatLng centrePasteur = new LatLng(3.872266884066907, 11.511386667941895);
LatLng hopitalGeneral = new LatLng(3.9071662829804397, 11.542086225614531);
LatLng genico = new LatLng(3.907819220596098, 11.53940401712668);
LatLng hopitalDjoungolo = new LatLng(3.88364902281552, 11.520266121255256);
LatLng hopitalCiteVerte = new LatLng(3.877531933062619, 11.48974772990604);
LatLng hopitalBiyemassi = new LatLng(3.8378931555102365, 11.485277481671247);
mMap.addMarker(new MarkerOptions().position(chuYaounde).title("CHU de Yaounde"));
mMap.addMarker(new MarkerOptions().position(centralHospitalYaounde).title("Hopital central de Yaounde"));
mMap.addMarker(new MarkerOptions().position(centrePasteur).title("Centre Pasteur"));
mMap.addMarker(new MarkerOptions().position(hopitalGeneral).title("Hopital général"));
mMap.addMarker(new MarkerOptions().position(genico).title("Hopital gyneco"));
mMap.addMarker(new MarkerOptions().position(hopitalDjoungolo).title("Hopital EPC djoungolo"));
mMap.addMarker(new MarkerOptions().position(hopitalCiteVerte).title("Hopital cité verte"));
mMap.addMarker(new MarkerOptions().position(hopitalBiyemassi).title("Hopital de district de Biyemassi"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(chuYaounde));
}
} | 3,197 | 0.739199 | 0.656857 | 62 | 50.532257 | 35.84227 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.709677 | false | false | 1 |
f0d2f2f403b1338fc4c5e0ca2b91addd232a5e1c | 35,390,530,557,742 | 104b421e536d1667a70f234ec61864f9278137c4 | /code/com/ons/bellareader/DownloadReceiver.java | 5861386c275b2031fb2d54a422486dcd1ca690f9 | [] | no_license | AshwiniVijayaKumar/Chrome-Cars | https://github.com/AshwiniVijayaKumar/Chrome-Cars | f2e61347c7416d37dae228dfeaa58c3845c66090 | 6a5e824ad5889f0e29d1aa31f7a35b1f6894f089 | refs/heads/master | 2021-01-15T11:07:57.050000 | 2016-05-13T05:01:09 | 2016-05-13T05:01:09 | 58,521,050 | 1 | 0 | null | true | 2016-05-11T06:51:56 | 2016-05-11T06:51:56 | 2016-05-06T14:21:56 | 2016-05-11T06:20:45 | 45,786 | 0 | 0 | 0 | null | null | null | package com.ons.bellareader;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
import java.io.PrintStream;
public class DownloadReceiver
extends BroadcastReceiver
{
public void onReceive(Context paramContext, Intent paramIntent)
{
Toast.makeText(paramContext, "??????????????????????????????????????????", 1).show();
String str = paramIntent.getAction();
Toast.makeText(paramContext, "action=" + str, 1).show();
if ("android.intent.action.DOWNLOAD_COMPLETE".equals(str))
{
paramIntent = paramIntent.getStringExtra("uri");
System.out.println(paramIntent);
Toast.makeText(paramContext, "" + paramIntent, 1).show();
}
}
}
/* Location: C:\Users\ADMIN\Desktop\foss\dex2jar-2.0\classes-dex2jar.jar!\com\ons\bellareader\DownloadReceiver.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | UTF-8 | Java | 957 | java | DownloadReceiver.java | Java | [] | null | [] | package com.ons.bellareader;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
import java.io.PrintStream;
public class DownloadReceiver
extends BroadcastReceiver
{
public void onReceive(Context paramContext, Intent paramIntent)
{
Toast.makeText(paramContext, "??????????????????????????????????????????", 1).show();
String str = paramIntent.getAction();
Toast.makeText(paramContext, "action=" + str, 1).show();
if ("android.intent.action.DOWNLOAD_COMPLETE".equals(str))
{
paramIntent = paramIntent.getStringExtra("uri");
System.out.println(paramIntent);
Toast.makeText(paramContext, "" + paramIntent, 1).show();
}
}
}
/* Location: C:\Users\ADMIN\Desktop\foss\dex2jar-2.0\classes-dex2jar.jar!\com\ons\bellareader\DownloadReceiver.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | 957 | 0.680251 | 0.665622 | 30 | 30.933332 | 30.077602 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.633333 | false | false | 1 |
5c9acb86953b35248ed6dcde645d16ab024e9e3d | 33,870,112,148,478 | c97a38ceaa2c916fadc125f5c4ea981089460ec6 | /hjf-app/src/main/java/com/hjf/app/core/bean/respBean/NoteDetailRespBean.java | 8c8944eaf8cffde6b8ca81042d43f8e4622cbe16 | [] | no_license | haijun0314/hjf | https://github.com/haijun0314/hjf | e08c4dfb3ef0120b8479a1165ab03b26301373c6 | 65638595693c798de4f32bc421c4d93b4454532e | refs/heads/master | 2022-12-23T14:56:50.916000 | 2021-05-17T09:55:53 | 2021-05-17T09:55:53 | 99,891,978 | 0 | 2 | null | false | 2022-12-16T10:46:38 | 2017-08-10T07:01:27 | 2021-05-17T09:55:55 | 2022-12-16T10:46:35 | 111,903 | 0 | 1 | 16 | JavaScript | false | false | package com.hjf.app.core.bean.respBean;
import com.hjf.common.bean.BaseRespBean;
/**
* 笔记详情
* author lihaijun
* createTime 2014-11-21
*/
public class NoteDetailRespBean extends BaseRespBean {
private Integer customerId; //用户编号
private Integer noteId; //笔记编号
private String content; //笔记内容
private String title; //标题
private String photos; //图片 ,分割
private String noteType; //笔记类型 0 图片 1 文字
private String customerName;//用户名称
private String headPic; //头像地址
private String babyName; //头像地址
private String babyAge; //发布时间
private String createdTime; //发布时间
private Integer commentCount;//评论数量
private Integer praiseCount;//点赞数量
public Integer getCustomerId() {
return customerId;
}
public void setCustomerId(Integer customerId) {
this.customerId = customerId;
}
public Integer getNoteId() {
return noteId;
}
public void setNoteId(Integer noteId) {
this.noteId = noteId;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPhotos() {
return photos;
}
public void setPhotos(String photos) {
this.photos = photos;
}
public String getNoteType() {
return noteType;
}
public void setNoteType(String noteType) {
this.noteType = noteType;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getHeadPic() {
return headPic;
}
public void setHeadPic(String headPic) {
this.headPic = headPic;
}
public String getBabyName() {
return babyName;
}
public void setBabyName(String babyName) {
this.babyName = babyName;
}
public String getBabyAge() {
return babyAge;
}
public void setBabyAge(String babyAge) {
this.babyAge = babyAge;
}
public String getCreatedTime() {
return createdTime;
}
public void setCreatedTime(String createdTime) {
this.createdTime = createdTime;
}
public Integer getCommentCount() {
return commentCount;
}
public void setCommentCount(Integer commentCount) {
this.commentCount = commentCount;
}
public Integer getPraiseCount() {
return praiseCount;
}
public void setPraiseCount(Integer praiseCount) {
this.praiseCount = praiseCount;
}
} | UTF-8 | Java | 2,611 | java | NoteDetailRespBean.java | Java | [
{
"context": "common.bean.BaseRespBean;\r\n/**\r\n * 笔记详情\r\n * author lihaijun\r\n * createTime 2014-11-21\r\n */\r\npublic class No",
"end": 117,
"score": 0.9986481666564941,
"start": 109,
"tag": "USERNAME",
"value": "lihaijun"
}
] | null | [] | package com.hjf.app.core.bean.respBean;
import com.hjf.common.bean.BaseRespBean;
/**
* 笔记详情
* author lihaijun
* createTime 2014-11-21
*/
public class NoteDetailRespBean extends BaseRespBean {
private Integer customerId; //用户编号
private Integer noteId; //笔记编号
private String content; //笔记内容
private String title; //标题
private String photos; //图片 ,分割
private String noteType; //笔记类型 0 图片 1 文字
private String customerName;//用户名称
private String headPic; //头像地址
private String babyName; //头像地址
private String babyAge; //发布时间
private String createdTime; //发布时间
private Integer commentCount;//评论数量
private Integer praiseCount;//点赞数量
public Integer getCustomerId() {
return customerId;
}
public void setCustomerId(Integer customerId) {
this.customerId = customerId;
}
public Integer getNoteId() {
return noteId;
}
public void setNoteId(Integer noteId) {
this.noteId = noteId;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPhotos() {
return photos;
}
public void setPhotos(String photos) {
this.photos = photos;
}
public String getNoteType() {
return noteType;
}
public void setNoteType(String noteType) {
this.noteType = noteType;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getHeadPic() {
return headPic;
}
public void setHeadPic(String headPic) {
this.headPic = headPic;
}
public String getBabyName() {
return babyName;
}
public void setBabyName(String babyName) {
this.babyName = babyName;
}
public String getBabyAge() {
return babyAge;
}
public void setBabyAge(String babyAge) {
this.babyAge = babyAge;
}
public String getCreatedTime() {
return createdTime;
}
public void setCreatedTime(String createdTime) {
this.createdTime = createdTime;
}
public Integer getCommentCount() {
return commentCount;
}
public void setCommentCount(Integer commentCount) {
this.commentCount = commentCount;
}
public Integer getPraiseCount() {
return praiseCount;
}
public void setPraiseCount(Integer praiseCount) {
this.praiseCount = praiseCount;
}
} | 2,611 | 0.692986 | 0.688978 | 105 | 21.780952 | 16.099678 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.685714 | false | false | 1 |
ae87e2b24c5c53193148a8f4ba7290b6e80ff67e | 39,384,850,121,978 | 226700382a053caece1bb9dc21b09bac7b796ef2 | /src/main/java/com/example/steam/controller/GameController.java | eb70e1682c1cb5890e14f78a5fa42629edaa59ee | [
"MIT"
] | permissive | drizzle888/steamMall | https://github.com/drizzle888/steamMall | da7d68edca1b2bd0d2dbb4b0d0fb0ba5eaa4da01 | 8d6a25571230151fb7ba2374149fa325b1db8a38 | refs/heads/master | 2023-08-26T03:06:36.584000 | 2019-07-10T12:40:02 | 2019-07-10T12:40:02 | 425,309,051 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.steam.controller;
import com.alibaba.fastjson.JSON;
import com.example.steam.service.GameService;
import com.example.steam.service.RecentGameService;
import com.example.steam.service.UserGameService;
import com.example.steam.utils.ResultMsg;
import com.example.steam.vo.GameDetail;
import com.example.steam.vo.SpecialGame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Created with IntelliJ IDEA.
*
* @author: Suyeq
* @date: 2019-04-27
* @time: 11:02
*/
@Controller
public class GameController {
// private Map<String,String> map=new ConcurrentHashMap<>();
Logger log= LoggerFactory.getLogger(GameController.class);
@Autowired
GameService gameService;
@Autowired
UserGameService userGameService;
@Autowired
RecentGameService recentGameService;
@ResponseBody
@RequestMapping("/feturedCarousel")
public String feturedCarousel(){
return JSON.toJSONString(ResultMsg.SUCCESS(gameService.findGamesFetured()));
}
@ResponseBody
@RequestMapping("/specialCarousel")
public String specialCarousel(){
List<SpecialGame> list=gameService.findSpecialGames();
return JSON.toJSONString(ResultMsg.SUCCESS(list));
}
@ResponseBody
@RequestMapping("/newRelease_index/{page}")
public String newRelease(@PathVariable("page")long page){
long start=System.currentTimeMillis();
List<GameDetail> list=gameService.findNewRelease(page);
long end=System.currentTimeMillis();
long result=end-start;
log.error(result+"");
return JSON.toJSONString(ResultMsg.SUCCESS(list));
}
@ResponseBody
@RequestMapping("/hotSell_index/{page}")
public String hotSell(@PathVariable("page")long page){
return JSON.toJSONString(ResultMsg.SUCCESS(gameService.findHotSell(page)));
}
@ResponseBody
@RequestMapping("/upComing_index/{page}")
public String upComing(@PathVariable("page")long page){
return JSON.toJSONString(ResultMsg.SUCCESS(gameService.findUpComing(page)));
}
@ResponseBody
@RequestMapping("/app/{id}")
public String oneGameDetail(@PathVariable("id")long id){
return JSON.toJSONString(ResultMsg.SUCCESS(gameService.findGameById(id)));
}
@ResponseBody
@RequestMapping("/classGame/{typeName}")
public String findGamesToClassCarouselBy(@PathVariable("typeName")String typeName){
return JSON.toJSONString(ResultMsg.SUCCESS(gameService.findGamesToClassCarousel(typeName)));
}
@ResponseBody
@RequestMapping("/classGame/newRelease/{typeName}/{page}")
public String findGamesNewReleaseByType(@PathVariable("typeName")String typeName,
@PathVariable("page")long page){
return JSON.toJSONString(ResultMsg.SUCCESS(gameService.findGamesNewReleaseByType(typeName,page)));
}
@ResponseBody
@RequestMapping("/classGame/hotSell/{typeName}/{page}")
public String findGamesHotSellByType(@PathVariable("typeName")String typeName,
@PathVariable("page")long page){
return JSON.toJSONString(ResultMsg.SUCCESS(gameService.findGamesHotSellByType(typeName,page)));
}
@ResponseBody
@RequestMapping("/classGame/upComing/{typeName}/{page}")
public String findGamesUpComingByType(@PathVariable("typeName")String typeName,
@PathVariable("page")long page){
return JSON.toJSONString(ResultMsg.SUCCESS(gameService.findGamesUpComingByType(typeName,page)));
}
@ResponseBody
@RequestMapping("issued/classGame/{typeName}")
public String findGamesIssuedSumByType(@PathVariable("typeName")String typeName){
return JSON.toJSONString(ResultMsg.SUCCESS(gameService.findGamesSumByType(typeName)));
}
@ResponseBody
@RequestMapping("upComing/classGame/{typeName}")
public String findGamesUpComingSumByType(@PathVariable("typeName")String typeName){
return JSON.toJSONString(ResultMsg.SUCCESS(gameService.findGamesUpComingSumByType(typeName)));
}
@ResponseBody
@RequestMapping("/issued/sum")
public String findIssuedGameSum(){
return JSON.toJSONString(ResultMsg.SUCCESS(gameService.findIssuedGamesSum()));
}
@ResponseBody
@RequestMapping("/upcoming/sum")
public String findUpComingGameSum(){
return JSON.toJSONString(ResultMsg.SUCCESS(gameService.findUpComingGamesSum()));
}
@ResponseBody
@RequestMapping("/searchresult")
public String searchResult(@RequestParam("content")String content){
return JSON.toJSONString(ResultMsg.SUCCESS(gameService.findGamesBySearchContent(content)));
}
@ResponseBody
@RequestMapping("/iscontains")
public String isContainsGame(@RequestParam("email")String email,
@RequestParam("gameId")long gameId){
return JSON.toJSONString(ResultMsg.SUCCESS(userGameService.isContains(email,gameId)));
}
@ResponseBody
@RequestMapping("/recentplaygame/{email}")
public String showRecentGame(@PathVariable("email") String email){
return JSON.toJSONString(ResultMsg.SUCCESS(userGameService.findThreeRecentGameVoListByEmail(email)));
}
@ResponseBody
@RequestMapping("/game/user/all/{email}")
public String showAllGamesByUserEmail(@PathVariable("email")String email){
return JSON.toJSONString(ResultMsg.SUCCESS(gameService.findAllGameShowByEmail(email)));
}
@ResponseBody
@RequestMapping("/game/count/{email}")
public String gameCountByEmail(@PathVariable("email") String email){
return JSON.toJSONString(ResultMsg.SUCCESS(gameService.findContainGamesNum(email)));
}
/**
* @return
*/
@ResponseBody
@RequestMapping("/game/add")
public String addGame(@RequestParam("newGameName")String newGameName,
@RequestParam("newGameIntroduction")String newGameIntroduction,
@RequestParam("newGameAbout")String newGameAbout,
@RequestParam("newGameKind")String newGameKind,
@RequestParam("newGamePrice")int newGamePrice,
@RequestParam("newGameDiscount")int newGameDiscount,
@RequestParam("newGameLowestCpu")String newGameLowestCpu,
@RequestParam("newGameLowestOs")String newGameLowestOs,
@RequestParam("newGameLowestRam")String newGameLowestRam,
@RequestParam("newGameLowestXianka")String newGameLowestXianka,
@RequestParam("newGameLowestNetwork")String newGameLowestNetwork,
@RequestParam("newGameLowestDirectx")String newGameLowestDirectx,
@RequestParam("newGameLowestRom")String newGameLowestRom,
@RequestParam("newGameLowestShenka")String newGameLowestShenka,
@RequestParam("newGameGoodCpu")String newGameGoodCpu,
@RequestParam("newGameGoodOs")String newGameGoodOs,
@RequestParam("newGameGoodRam")String newGameGoodRam,
@RequestParam("newGameGoodXianka")String newGameGoodXianka,
@RequestParam("newGameGoodNetwork")String newGameGoodNetwork,
@RequestParam("newGameGoodDirectx")String newGameGoodDirectx,
@RequestParam("newGameGoodRom")String newGameGoodRom,
@RequestParam("newGameGoodShenka")String newGameGoodShenka){
long result=gameService.addGame(newGameName,newGameIntroduction, newGameAbout, newGameKind, newGamePrice, newGameDiscount,
newGameLowestCpu,newGameLowestOs,newGameLowestRam,newGameLowestXianka,newGameLowestNetwork,newGameLowestDirectx,
newGameLowestRom,newGameLowestShenka,newGameGoodCpu,newGameGoodOs,newGameGoodRam,newGameGoodXianka,newGameGoodNetwork,
newGameGoodDirectx,newGameGoodRom, newGameGoodShenka);
return JSON.toJSONString(ResultMsg.SUCCESS(result));
}
@ResponseBody
@RequestMapping("/game/update")
public String addGame(@RequestParam("gameId")long gameId,
@RequestParam("newGameName")String newGameName,
@RequestParam("newGameIntroduction")String newGameIntroduction,
@RequestParam("newGameAbout")String newGameAbout,
//@RequestParam("newGameKind")String newGameKind,
@RequestParam("newGamePrice")int newGamePrice,
@RequestParam("newGameDiscount")int newGameDiscount){
long result=gameService.updateGame(gameId,newGameName,newGameIntroduction, newGameAbout, null, newGamePrice, newGameDiscount);
return JSON.toJSONString(ResultMsg.SUCCESS(result));
}
@ResponseBody
@RequestMapping("/game/delete/{gameId}")
public String deleteGame(@PathVariable("gameId")long gameId){
return JSON.toJSONString(ResultMsg.SUCCESS(gameService.deleteGame(gameId)));
}
@ResponseBody
@RequestMapping("/game/issued/{gameId}")
public String publishGame(@PathVariable("gameId")long gameId){
return JSON.toJSONString(ResultMsg.SUCCESS(gameService.updateGameIssuedStatu(gameId)));
}
}
| UTF-8 | Java | 9,957 | java | GameController.java | Java | [
{
"context": "\n/**\n * Created with IntelliJ IDEA.\n *\n * @author: Suyeq\n * @date: 2019-04-27\n * @time: 11:02\n */\n@Control",
"end": 959,
"score": 0.7834701538085938,
"start": 954,
"tag": "NAME",
"value": "Suyeq"
}
] | null | [] | package com.example.steam.controller;
import com.alibaba.fastjson.JSON;
import com.example.steam.service.GameService;
import com.example.steam.service.RecentGameService;
import com.example.steam.service.UserGameService;
import com.example.steam.utils.ResultMsg;
import com.example.steam.vo.GameDetail;
import com.example.steam.vo.SpecialGame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Created with IntelliJ IDEA.
*
* @author: Suyeq
* @date: 2019-04-27
* @time: 11:02
*/
@Controller
public class GameController {
// private Map<String,String> map=new ConcurrentHashMap<>();
Logger log= LoggerFactory.getLogger(GameController.class);
@Autowired
GameService gameService;
@Autowired
UserGameService userGameService;
@Autowired
RecentGameService recentGameService;
@ResponseBody
@RequestMapping("/feturedCarousel")
public String feturedCarousel(){
return JSON.toJSONString(ResultMsg.SUCCESS(gameService.findGamesFetured()));
}
@ResponseBody
@RequestMapping("/specialCarousel")
public String specialCarousel(){
List<SpecialGame> list=gameService.findSpecialGames();
return JSON.toJSONString(ResultMsg.SUCCESS(list));
}
@ResponseBody
@RequestMapping("/newRelease_index/{page}")
public String newRelease(@PathVariable("page")long page){
long start=System.currentTimeMillis();
List<GameDetail> list=gameService.findNewRelease(page);
long end=System.currentTimeMillis();
long result=end-start;
log.error(result+"");
return JSON.toJSONString(ResultMsg.SUCCESS(list));
}
@ResponseBody
@RequestMapping("/hotSell_index/{page}")
public String hotSell(@PathVariable("page")long page){
return JSON.toJSONString(ResultMsg.SUCCESS(gameService.findHotSell(page)));
}
@ResponseBody
@RequestMapping("/upComing_index/{page}")
public String upComing(@PathVariable("page")long page){
return JSON.toJSONString(ResultMsg.SUCCESS(gameService.findUpComing(page)));
}
@ResponseBody
@RequestMapping("/app/{id}")
public String oneGameDetail(@PathVariable("id")long id){
return JSON.toJSONString(ResultMsg.SUCCESS(gameService.findGameById(id)));
}
@ResponseBody
@RequestMapping("/classGame/{typeName}")
public String findGamesToClassCarouselBy(@PathVariable("typeName")String typeName){
return JSON.toJSONString(ResultMsg.SUCCESS(gameService.findGamesToClassCarousel(typeName)));
}
@ResponseBody
@RequestMapping("/classGame/newRelease/{typeName}/{page}")
public String findGamesNewReleaseByType(@PathVariable("typeName")String typeName,
@PathVariable("page")long page){
return JSON.toJSONString(ResultMsg.SUCCESS(gameService.findGamesNewReleaseByType(typeName,page)));
}
@ResponseBody
@RequestMapping("/classGame/hotSell/{typeName}/{page}")
public String findGamesHotSellByType(@PathVariable("typeName")String typeName,
@PathVariable("page")long page){
return JSON.toJSONString(ResultMsg.SUCCESS(gameService.findGamesHotSellByType(typeName,page)));
}
@ResponseBody
@RequestMapping("/classGame/upComing/{typeName}/{page}")
public String findGamesUpComingByType(@PathVariable("typeName")String typeName,
@PathVariable("page")long page){
return JSON.toJSONString(ResultMsg.SUCCESS(gameService.findGamesUpComingByType(typeName,page)));
}
@ResponseBody
@RequestMapping("issued/classGame/{typeName}")
public String findGamesIssuedSumByType(@PathVariable("typeName")String typeName){
return JSON.toJSONString(ResultMsg.SUCCESS(gameService.findGamesSumByType(typeName)));
}
@ResponseBody
@RequestMapping("upComing/classGame/{typeName}")
public String findGamesUpComingSumByType(@PathVariable("typeName")String typeName){
return JSON.toJSONString(ResultMsg.SUCCESS(gameService.findGamesUpComingSumByType(typeName)));
}
@ResponseBody
@RequestMapping("/issued/sum")
public String findIssuedGameSum(){
return JSON.toJSONString(ResultMsg.SUCCESS(gameService.findIssuedGamesSum()));
}
@ResponseBody
@RequestMapping("/upcoming/sum")
public String findUpComingGameSum(){
return JSON.toJSONString(ResultMsg.SUCCESS(gameService.findUpComingGamesSum()));
}
@ResponseBody
@RequestMapping("/searchresult")
public String searchResult(@RequestParam("content")String content){
return JSON.toJSONString(ResultMsg.SUCCESS(gameService.findGamesBySearchContent(content)));
}
@ResponseBody
@RequestMapping("/iscontains")
public String isContainsGame(@RequestParam("email")String email,
@RequestParam("gameId")long gameId){
return JSON.toJSONString(ResultMsg.SUCCESS(userGameService.isContains(email,gameId)));
}
@ResponseBody
@RequestMapping("/recentplaygame/{email}")
public String showRecentGame(@PathVariable("email") String email){
return JSON.toJSONString(ResultMsg.SUCCESS(userGameService.findThreeRecentGameVoListByEmail(email)));
}
@ResponseBody
@RequestMapping("/game/user/all/{email}")
public String showAllGamesByUserEmail(@PathVariable("email")String email){
return JSON.toJSONString(ResultMsg.SUCCESS(gameService.findAllGameShowByEmail(email)));
}
@ResponseBody
@RequestMapping("/game/count/{email}")
public String gameCountByEmail(@PathVariable("email") String email){
return JSON.toJSONString(ResultMsg.SUCCESS(gameService.findContainGamesNum(email)));
}
/**
* @return
*/
@ResponseBody
@RequestMapping("/game/add")
public String addGame(@RequestParam("newGameName")String newGameName,
@RequestParam("newGameIntroduction")String newGameIntroduction,
@RequestParam("newGameAbout")String newGameAbout,
@RequestParam("newGameKind")String newGameKind,
@RequestParam("newGamePrice")int newGamePrice,
@RequestParam("newGameDiscount")int newGameDiscount,
@RequestParam("newGameLowestCpu")String newGameLowestCpu,
@RequestParam("newGameLowestOs")String newGameLowestOs,
@RequestParam("newGameLowestRam")String newGameLowestRam,
@RequestParam("newGameLowestXianka")String newGameLowestXianka,
@RequestParam("newGameLowestNetwork")String newGameLowestNetwork,
@RequestParam("newGameLowestDirectx")String newGameLowestDirectx,
@RequestParam("newGameLowestRom")String newGameLowestRom,
@RequestParam("newGameLowestShenka")String newGameLowestShenka,
@RequestParam("newGameGoodCpu")String newGameGoodCpu,
@RequestParam("newGameGoodOs")String newGameGoodOs,
@RequestParam("newGameGoodRam")String newGameGoodRam,
@RequestParam("newGameGoodXianka")String newGameGoodXianka,
@RequestParam("newGameGoodNetwork")String newGameGoodNetwork,
@RequestParam("newGameGoodDirectx")String newGameGoodDirectx,
@RequestParam("newGameGoodRom")String newGameGoodRom,
@RequestParam("newGameGoodShenka")String newGameGoodShenka){
long result=gameService.addGame(newGameName,newGameIntroduction, newGameAbout, newGameKind, newGamePrice, newGameDiscount,
newGameLowestCpu,newGameLowestOs,newGameLowestRam,newGameLowestXianka,newGameLowestNetwork,newGameLowestDirectx,
newGameLowestRom,newGameLowestShenka,newGameGoodCpu,newGameGoodOs,newGameGoodRam,newGameGoodXianka,newGameGoodNetwork,
newGameGoodDirectx,newGameGoodRom, newGameGoodShenka);
return JSON.toJSONString(ResultMsg.SUCCESS(result));
}
@ResponseBody
@RequestMapping("/game/update")
public String addGame(@RequestParam("gameId")long gameId,
@RequestParam("newGameName")String newGameName,
@RequestParam("newGameIntroduction")String newGameIntroduction,
@RequestParam("newGameAbout")String newGameAbout,
//@RequestParam("newGameKind")String newGameKind,
@RequestParam("newGamePrice")int newGamePrice,
@RequestParam("newGameDiscount")int newGameDiscount){
long result=gameService.updateGame(gameId,newGameName,newGameIntroduction, newGameAbout, null, newGamePrice, newGameDiscount);
return JSON.toJSONString(ResultMsg.SUCCESS(result));
}
@ResponseBody
@RequestMapping("/game/delete/{gameId}")
public String deleteGame(@PathVariable("gameId")long gameId){
return JSON.toJSONString(ResultMsg.SUCCESS(gameService.deleteGame(gameId)));
}
@ResponseBody
@RequestMapping("/game/issued/{gameId}")
public String publishGame(@PathVariable("gameId")long gameId){
return JSON.toJSONString(ResultMsg.SUCCESS(gameService.updateGameIssuedStatu(gameId)));
}
}
| 9,957 | 0.694988 | 0.693582 | 234 | 41.551281 | 34.884907 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.508547 | false | false | 1 |
fb9a3fed5671af8b412dca2666e1ea5d248cfed8 | 15,547,781,675,911 | 6470df0bb53db4726bea6bf564d1febd7e025936 | /BBS-src/com/laoer/bbscs/web/taglib/UserInfoInPost.java | 7f6c261b13c17c94a6343852d94f34dd0f013770 | [] | no_license | yunlugu/yunluyuan-bbs | https://github.com/yunlugu/yunluyuan-bbs | 3d9a8069f4eb1843859a8dff117680037d2ec471 | 9d3121246c2b65a371e129c7b34f6680c748f319 | refs/heads/master | 2021-01-24T01:29:54.622000 | 2018-02-25T06:43:51 | 2018-02-25T06:43:51 | 122,812,187 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.laoer.bbscs.web.taglib;
import java.io.IOException;
import java.io.Writer;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.PageContext;
import org.apache.struts2.components.Component;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.laoer.bbscs.bean.UserInfoSimple;
import com.laoer.bbscs.comm.BBSCSUtil;
import com.laoer.bbscs.comm.Constant;
import com.laoer.bbscs.service.UserService;
import com.laoer.bbscs.service.config.SysConfig;
import com.opensymphony.xwork2.util.ValueStack;
public class UserInfoInPost extends Component {
private PageContext pageContext;
private HttpServletRequest request;
//private HttpServletResponse response;
protected String idValue = "";
protected String styleClass = "pic1";
protected String facePicName = "images/defaultFace.gif";
public UserInfoInPost(ValueStack stack, PageContext pageContext, HttpServletRequest request,
HttpServletResponse response) {
super(stack);
this.pageContext = pageContext;
this.request = request;
//this.response = response;
}
public boolean start(Writer writer) {
boolean result = super.start(writer);
if (idValue == null) {
idValue = "top";
} else if (altSyntax()) {
if (idValue.startsWith("%{") && idValue.endsWith("}")) {
idValue = idValue.substring(2, idValue.length() - 1);
}
}
Object value = this.getStack().findValue(idValue);
StringBuffer sb = new StringBuffer();
if (value == null) {
sb.append("");
return result;
}
String userID = (String) value;
WebApplicationContext wc = WebApplicationContextUtils.getWebApplicationContext(this.pageContext
.getServletContext());
UserService userService = (UserService) wc.getBean("userService");
SysConfig sysConfig = (SysConfig) wc.getBean("sysConfig");
ResourceBundleMessageSource messageSource = (ResourceBundleMessageSource) wc.getBean("messageSource");
UserInfoSimple uis = userService.getUserInfoSimple(userID);
if (sysConfig.getPostShowUserImg() == 1) {
if (uis.getHavePic() == 1 && !uis.getPicFileName().equals("-")) {
sb.append("<a href=\"");
sb.append(BBSCSUtil.getUserWebPath(uis.getId()));
sb.append(uis.getPicFileName());
sb.append("\" target=\"_blank\">");
sb.append("<img src=\"");
sb.append(BBSCSUtil.getUserWebPath(uis.getId()));
sb.append(uis.getPicFileName());
sb.append(Constant.IMG_SMALL_FILEPREFIX);
sb.append("\" alt=\"Face\" class=\"");
sb.append(this.getStyleClass());
sb.append("\" border=\"0\"/>");
sb.append("</a><br/>");
} else {
sb.append("<img src=\"");
sb.append(facePicName);
sb.append("\" alt=\"Face\" /><br/>");
}
sb.append("<br/>");
}
sb.append(messageSource.getMessage("uiinpost.artnum", null, request.getLocale()));
sb.append(":");
// sb.append("发帖:");
sb.append(uis.getArticleNum());
sb.append("<br/>");
sb.append(messageSource.getMessage("uiinpost.elitenum", null, request.getLocale()));
sb.append(":");
// sb.append("精华:");
sb.append(uis.getArticleEliteNum());
sb.append("<br/>");
int titleValue = userService.getUserTitleValue(uis);
sb.append(messageSource.getMessage("uiinpost.point", null, request.getLocale()));
sb.append(":");
// sb.append("积分:");
sb.append(titleValue);
sb.append("<br/>");
// String userTitle = BBSCSUtil.getUserTitle(uis.getUserTitle(),
// titleValue, request.getLocale());
String userTitle = userService.getUserTitle(uis);
sb.append(messageSource.getMessage("uiinpost.level", null, request.getLocale()));
sb.append(":");
// sb.append("等级:");
sb.append(userTitle);
sb.append("<br/>");
sb.append(messageSource.getMessage("bbscs.coin", null, request.getLocale()));
sb.append(":");
sb.append(uis.getCoin());
sb.append("<br/>");
sb.append(messageSource.getMessage("uiinpost.from", null, request.getLocale()));
sb.append(":");
// sb.append("来自:");
sb.append(uis.getUserFrom());
sb.append("<br/>");
sb.append(messageSource.getMessage("uiinpost.regtime", null, request.getLocale()));
sb.append(":");
// sb.append("注册:");
sb.append(BBSCSUtil.formatDateTime(new Date(uis.getRegTime()), sysConfig.getRegDateTimeFormat()));
sb.append("<br/>");
sb.append(messageSource.getMessage("uiinpost.lastlogin", null, request.getLocale()));
sb.append(":");
// sb.append("最后登录:");
sb.append(BBSCSUtil.formatDateTime(new Date(uis.getLoginTime()), "MM-dd HH:mm"));
try {
writer.write(sb.toString());
} catch (IOException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
return result;
}
public String getFacePicName() {
return facePicName;
}
public void setFacePicName(String facePicName) {
this.facePicName = facePicName;
}
public String getIdValue() {
return idValue;
}
public void setIdValue(String idValue) {
this.idValue = idValue;
}
public String getStyleClass() {
return styleClass;
}
public void setStyleClass(String styleClass) {
this.styleClass = styleClass;
}
}
| UTF-8 | Java | 5,432 | java | UserInfoInPost.java | Java | [] | null | [] | package com.laoer.bbscs.web.taglib;
import java.io.IOException;
import java.io.Writer;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.PageContext;
import org.apache.struts2.components.Component;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.laoer.bbscs.bean.UserInfoSimple;
import com.laoer.bbscs.comm.BBSCSUtil;
import com.laoer.bbscs.comm.Constant;
import com.laoer.bbscs.service.UserService;
import com.laoer.bbscs.service.config.SysConfig;
import com.opensymphony.xwork2.util.ValueStack;
public class UserInfoInPost extends Component {
private PageContext pageContext;
private HttpServletRequest request;
//private HttpServletResponse response;
protected String idValue = "";
protected String styleClass = "pic1";
protected String facePicName = "images/defaultFace.gif";
public UserInfoInPost(ValueStack stack, PageContext pageContext, HttpServletRequest request,
HttpServletResponse response) {
super(stack);
this.pageContext = pageContext;
this.request = request;
//this.response = response;
}
public boolean start(Writer writer) {
boolean result = super.start(writer);
if (idValue == null) {
idValue = "top";
} else if (altSyntax()) {
if (idValue.startsWith("%{") && idValue.endsWith("}")) {
idValue = idValue.substring(2, idValue.length() - 1);
}
}
Object value = this.getStack().findValue(idValue);
StringBuffer sb = new StringBuffer();
if (value == null) {
sb.append("");
return result;
}
String userID = (String) value;
WebApplicationContext wc = WebApplicationContextUtils.getWebApplicationContext(this.pageContext
.getServletContext());
UserService userService = (UserService) wc.getBean("userService");
SysConfig sysConfig = (SysConfig) wc.getBean("sysConfig");
ResourceBundleMessageSource messageSource = (ResourceBundleMessageSource) wc.getBean("messageSource");
UserInfoSimple uis = userService.getUserInfoSimple(userID);
if (sysConfig.getPostShowUserImg() == 1) {
if (uis.getHavePic() == 1 && !uis.getPicFileName().equals("-")) {
sb.append("<a href=\"");
sb.append(BBSCSUtil.getUserWebPath(uis.getId()));
sb.append(uis.getPicFileName());
sb.append("\" target=\"_blank\">");
sb.append("<img src=\"");
sb.append(BBSCSUtil.getUserWebPath(uis.getId()));
sb.append(uis.getPicFileName());
sb.append(Constant.IMG_SMALL_FILEPREFIX);
sb.append("\" alt=\"Face\" class=\"");
sb.append(this.getStyleClass());
sb.append("\" border=\"0\"/>");
sb.append("</a><br/>");
} else {
sb.append("<img src=\"");
sb.append(facePicName);
sb.append("\" alt=\"Face\" /><br/>");
}
sb.append("<br/>");
}
sb.append(messageSource.getMessage("uiinpost.artnum", null, request.getLocale()));
sb.append(":");
// sb.append("发帖:");
sb.append(uis.getArticleNum());
sb.append("<br/>");
sb.append(messageSource.getMessage("uiinpost.elitenum", null, request.getLocale()));
sb.append(":");
// sb.append("精华:");
sb.append(uis.getArticleEliteNum());
sb.append("<br/>");
int titleValue = userService.getUserTitleValue(uis);
sb.append(messageSource.getMessage("uiinpost.point", null, request.getLocale()));
sb.append(":");
// sb.append("积分:");
sb.append(titleValue);
sb.append("<br/>");
// String userTitle = BBSCSUtil.getUserTitle(uis.getUserTitle(),
// titleValue, request.getLocale());
String userTitle = userService.getUserTitle(uis);
sb.append(messageSource.getMessage("uiinpost.level", null, request.getLocale()));
sb.append(":");
// sb.append("等级:");
sb.append(userTitle);
sb.append("<br/>");
sb.append(messageSource.getMessage("bbscs.coin", null, request.getLocale()));
sb.append(":");
sb.append(uis.getCoin());
sb.append("<br/>");
sb.append(messageSource.getMessage("uiinpost.from", null, request.getLocale()));
sb.append(":");
// sb.append("来自:");
sb.append(uis.getUserFrom());
sb.append("<br/>");
sb.append(messageSource.getMessage("uiinpost.regtime", null, request.getLocale()));
sb.append(":");
// sb.append("注册:");
sb.append(BBSCSUtil.formatDateTime(new Date(uis.getRegTime()), sysConfig.getRegDateTimeFormat()));
sb.append("<br/>");
sb.append(messageSource.getMessage("uiinpost.lastlogin", null, request.getLocale()));
sb.append(":");
// sb.append("最后登录:");
sb.append(BBSCSUtil.formatDateTime(new Date(uis.getLoginTime()), "MM-dd HH:mm"));
try {
writer.write(sb.toString());
} catch (IOException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
return result;
}
public String getFacePicName() {
return facePicName;
}
public void setFacePicName(String facePicName) {
this.facePicName = facePicName;
}
public String getIdValue() {
return idValue;
}
public void setIdValue(String idValue) {
this.idValue = idValue;
}
public String getStyleClass() {
return styleClass;
}
public void setStyleClass(String styleClass) {
this.styleClass = styleClass;
}
}
| 5,432 | 0.676623 | 0.675139 | 179 | 28.111732 | 25.111792 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.251397 | false | false | 1 |
828149d70b2144694c7a1ed36951f9ce16c4b999 | 7,052,336,369,770 | 3f6b5198816e666480af2238f17971770d86a1a2 | /EarthGadget/src/earthgadget/EarthGadgetApp.java | 2b0dc0a5b8967a281050b12f027ee1328d37a3f2 | [
"Apache-2.0"
] | permissive | torutk/jjugccc2017spring-javafx | https://github.com/torutk/jjugccc2017spring-javafx | 2a67c3b644abc78bd778f16e2d71669b756aedee | 53a258d01e87118de03a9089c82ed6a279f1386b | refs/heads/master | 2021-01-20T00:34:06.478000 | 2017-05-29T21:51:37 | 2017-05-29T21:51:37 | 89,151,064 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* © 2017 TAKAHASHI,Toru
*/
package earthgadget;
import java.util.prefs.Preferences;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.AmbientLight;
import javafx.scene.Group;
import javafx.scene.PerspectiveCamera;
import javafx.scene.PointLight;
import javafx.scene.Scene;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.image.Image;
import javafx.scene.paint.Color;
import javafx.scene.paint.PhongMaterial;
import javafx.scene.shape.Sphere;
import javafx.scene.transform.Rotate;
import javafx.scene.transform.Translate;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.stage.WindowEvent;
import javafx.util.Duration;
/**
* 地球が3次元表示で回転するデスクトップガジェット。
*/
public class EarthGadgetApp extends Application {
private static final double FRAMES_PER_SECOND = 5;
private static final double AZIMUTH_SPEED_PER_SECOND = 2; // degree
private Translate cameraTranslate = new Translate(0, 0, -300);
private Rotate cameraRotateY = new Rotate(0, Rotate.Y_AXIS);
// ドラッグ&ドロップでウィンドウの移動
private double dragStartX;
private double dragStartY;
// 設定の保存で使用するプリファレンスとキー
private Preferences prefs = Preferences.userNodeForPackage(this.getClass());
private static final String KEY_STAGE_X = "stageX";
private static final String KEY_STAGE_Y = "stageY";
private static final String KEY_STAGE_WIDTH = "stageWidth";
private static final String KEY_STAGE_HEIGHT = "stageHeight";
@Override
public void start(Stage primaryStage) {
Group root = new Group();
Sphere earth = new Sphere(100);
root.getChildren().add(earth);
PhongMaterial material = new PhongMaterial();
Image earthTexture = new Image(getClass().getResourceAsStream("earth.png"));
material.setDiffuseMap(earthTexture);
earth.setMaterial(material);
PerspectiveCamera camera = new PerspectiveCamera(true);
camera.setFieldOfView(45);
camera.setFarClip(1000);
camera.getTransforms().addAll(cameraRotateY, cameraTranslate);
// 点光源の定義
final PointLight pointLight = new PointLight(Color.WHITE);
pointLight.setTranslateX(500);
pointLight.setTranslateY(0);
pointLight.setTranslateZ(-500);
root.getChildren().add(pointLight);
// 環境光の定義
AmbientLight ambientLight = new AmbientLight(Color.rgb(192, 192, 192, 0.75));
root.getChildren().add(ambientLight);
Scene scene = new Scene(root, 300, 250);
scene.setCamera(camera);
// ウィンドウ枠の非表示と背景透明化
scene.setFill(Color.TRANSPARENT);
primaryStage.initStyle(StageStyle.TRANSPARENT);
// ドラッグ操作でウィンドウを移動
scene.setOnMousePressed(event -> {
dragStartX = event.getSceneX();
dragStartY = event.getSceneY();
});
scene.setOnMouseDragged(event -> {
primaryStage.setX(event.getScreenX() - dragStartX);
primaryStage.setY(event.getScreenY() - dragStartY);
});
// マウスホイール操作でウィンドウの大きさを変更
scene.setOnScroll(event -> {
if (event.isControlDown()) {
zoom(event.getDeltaY() > 0 ? 1.1 : 0.9, primaryStage);
}
});
// タッチパネルのズーム(ピンチ)操作でウィンドウサイズを変更
scene.setOnZoom(event -> {
zoom(event.getZoomFactor(), primaryStage);
});
// マウス右クリックでポップアップメニューを表示
ContextMenu popup = createContextMenu(primaryStage);
root.setOnContextMenuRequested(event -> {
popup.show(primaryStage, event.getScreenX(), event.getScreenY());
});
// ウィンドウが終了するときに状態を保存
primaryStage.setOnCloseRequest(event -> {
saveStatus(primaryStage);
});
// 保存した状態があれば復元
loadStatus(primaryStage);
primaryStage.setTitle("Hello Earth!");
primaryStage.setScene(scene);
primaryStage.show();
Timeline animation = createAnimation();
animation.play();
}
/**
* カメラを地球中心に1周回転するアニメーションを作成する。
*
* @return 360度回転するアニメーション
*/
private Timeline createAnimation() {
Timeline animation = new Timeline(FRAMES_PER_SECOND);
animation.setCycleCount(Animation.INDEFINITE);
animation.getKeyFrames().addAll(
new KeyFrame(Duration.ZERO,
new KeyValue(cameraRotateY.angleProperty(), 0)
),
new KeyFrame(Duration.seconds(360d / AZIMUTH_SPEED_PER_SECOND),
new KeyValue(cameraRotateY.angleProperty(), -360)
)
);
return animation;
}
/**
* 指定した拡大率で指定した stage の大きさを変更する。
*
* @param factor 拡大率(1.0が等倍で、 1.0 より大で大きく、 1.0 より小で小さくする)
* @param stage 大きさを変更する対象
*/
private void zoom(double factor, Stage stage) {
stage.setWidth(stage.getWidth() * factor);
stage.setHeight(stage.getHeight() * factor);
}
/**
* ポップアップメニューを生成する。
*
* @return ポップアップメニュー
*/
private ContextMenu createContextMenu(Stage stage) {
MenuItem exitItem = new MenuItem("終了");
exitItem.setStyle("-fx-font-size: 2em");
exitItem.setOnAction(event -> {
stage.fireEvent(new WindowEvent(stage, WindowEvent.WINDOW_CLOSE_REQUEST));
});
ContextMenu popup = new ContextMenu(exitItem);
return popup;
}
/**
* 状態を永続領域に保存する。
*/
private void saveStatus(Stage stage) {
prefs.putInt(KEY_STAGE_X, (int) stage.getX());
prefs.putInt(KEY_STAGE_Y, (int) stage.getY());
prefs.putInt(KEY_STAGE_WIDTH, (int) stage.getWidth());
prefs.putInt(KEY_STAGE_HEIGHT, (int) stage.getHeight());
}
/**
* 永続領域に保存された状態を復元する。
*/
private void loadStatus(Stage stage) {
stage.setX(prefs.getInt(KEY_STAGE_X, 0));
stage.setY(prefs.getInt(KEY_STAGE_Y, 0));
stage.setWidth(prefs.getInt(KEY_STAGE_WIDTH, 320));
stage.setHeight(prefs.getInt(KEY_STAGE_HEIGHT, 200));
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
| UTF-8 | Java | 7,402 | java | EarthGadgetApp.java | Java | [
{
"context": "/*\r\n * © 2017 TAKAHASHI,Toru\r\n */\r\npackage earthgadget;\r\n\r\nimport java.ut",
"end": 23,
"score": 0.9994570016860962,
"start": 14,
"tag": "NAME",
"value": "TAKAHASHI"
},
{
"context": "/*\r\n * © 2017 TAKAHASHI,Toru\r\n */\r\npackage earthgadget;\r\n\r\nimport ja... | null | [] | /*
* © 2017 TAKAHASHI,Toru
*/
package earthgadget;
import java.util.prefs.Preferences;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.AmbientLight;
import javafx.scene.Group;
import javafx.scene.PerspectiveCamera;
import javafx.scene.PointLight;
import javafx.scene.Scene;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.image.Image;
import javafx.scene.paint.Color;
import javafx.scene.paint.PhongMaterial;
import javafx.scene.shape.Sphere;
import javafx.scene.transform.Rotate;
import javafx.scene.transform.Translate;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.stage.WindowEvent;
import javafx.util.Duration;
/**
* 地球が3次元表示で回転するデスクトップガジェット。
*/
public class EarthGadgetApp extends Application {
private static final double FRAMES_PER_SECOND = 5;
private static final double AZIMUTH_SPEED_PER_SECOND = 2; // degree
private Translate cameraTranslate = new Translate(0, 0, -300);
private Rotate cameraRotateY = new Rotate(0, Rotate.Y_AXIS);
// ドラッグ&ドロップでウィンドウの移動
private double dragStartX;
private double dragStartY;
// 設定の保存で使用するプリファレンスとキー
private Preferences prefs = Preferences.userNodeForPackage(this.getClass());
private static final String KEY_STAGE_X = "stageX";
private static final String KEY_STAGE_Y = "stageY";
private static final String KEY_STAGE_WIDTH = "stageWidth";
private static final String KEY_STAGE_HEIGHT = "stageHeight";
@Override
public void start(Stage primaryStage) {
Group root = new Group();
Sphere earth = new Sphere(100);
root.getChildren().add(earth);
PhongMaterial material = new PhongMaterial();
Image earthTexture = new Image(getClass().getResourceAsStream("earth.png"));
material.setDiffuseMap(earthTexture);
earth.setMaterial(material);
PerspectiveCamera camera = new PerspectiveCamera(true);
camera.setFieldOfView(45);
camera.setFarClip(1000);
camera.getTransforms().addAll(cameraRotateY, cameraTranslate);
// 点光源の定義
final PointLight pointLight = new PointLight(Color.WHITE);
pointLight.setTranslateX(500);
pointLight.setTranslateY(0);
pointLight.setTranslateZ(-500);
root.getChildren().add(pointLight);
// 環境光の定義
AmbientLight ambientLight = new AmbientLight(Color.rgb(192, 192, 192, 0.75));
root.getChildren().add(ambientLight);
Scene scene = new Scene(root, 300, 250);
scene.setCamera(camera);
// ウィンドウ枠の非表示と背景透明化
scene.setFill(Color.TRANSPARENT);
primaryStage.initStyle(StageStyle.TRANSPARENT);
// ドラッグ操作でウィンドウを移動
scene.setOnMousePressed(event -> {
dragStartX = event.getSceneX();
dragStartY = event.getSceneY();
});
scene.setOnMouseDragged(event -> {
primaryStage.setX(event.getScreenX() - dragStartX);
primaryStage.setY(event.getScreenY() - dragStartY);
});
// マウスホイール操作でウィンドウの大きさを変更
scene.setOnScroll(event -> {
if (event.isControlDown()) {
zoom(event.getDeltaY() > 0 ? 1.1 : 0.9, primaryStage);
}
});
// タッチパネルのズーム(ピンチ)操作でウィンドウサイズを変更
scene.setOnZoom(event -> {
zoom(event.getZoomFactor(), primaryStage);
});
// マウス右クリックでポップアップメニューを表示
ContextMenu popup = createContextMenu(primaryStage);
root.setOnContextMenuRequested(event -> {
popup.show(primaryStage, event.getScreenX(), event.getScreenY());
});
// ウィンドウが終了するときに状態を保存
primaryStage.setOnCloseRequest(event -> {
saveStatus(primaryStage);
});
// 保存した状態があれば復元
loadStatus(primaryStage);
primaryStage.setTitle("Hello Earth!");
primaryStage.setScene(scene);
primaryStage.show();
Timeline animation = createAnimation();
animation.play();
}
/**
* カメラを地球中心に1周回転するアニメーションを作成する。
*
* @return 360度回転するアニメーション
*/
private Timeline createAnimation() {
Timeline animation = new Timeline(FRAMES_PER_SECOND);
animation.setCycleCount(Animation.INDEFINITE);
animation.getKeyFrames().addAll(
new KeyFrame(Duration.ZERO,
new KeyValue(cameraRotateY.angleProperty(), 0)
),
new KeyFrame(Duration.seconds(360d / AZIMUTH_SPEED_PER_SECOND),
new KeyValue(cameraRotateY.angleProperty(), -360)
)
);
return animation;
}
/**
* 指定した拡大率で指定した stage の大きさを変更する。
*
* @param factor 拡大率(1.0が等倍で、 1.0 より大で大きく、 1.0 より小で小さくする)
* @param stage 大きさを変更する対象
*/
private void zoom(double factor, Stage stage) {
stage.setWidth(stage.getWidth() * factor);
stage.setHeight(stage.getHeight() * factor);
}
/**
* ポップアップメニューを生成する。
*
* @return ポップアップメニュー
*/
private ContextMenu createContextMenu(Stage stage) {
MenuItem exitItem = new MenuItem("終了");
exitItem.setStyle("-fx-font-size: 2em");
exitItem.setOnAction(event -> {
stage.fireEvent(new WindowEvent(stage, WindowEvent.WINDOW_CLOSE_REQUEST));
});
ContextMenu popup = new ContextMenu(exitItem);
return popup;
}
/**
* 状態を永続領域に保存する。
*/
private void saveStatus(Stage stage) {
prefs.putInt(KEY_STAGE_X, (int) stage.getX());
prefs.putInt(KEY_STAGE_Y, (int) stage.getY());
prefs.putInt(KEY_STAGE_WIDTH, (int) stage.getWidth());
prefs.putInt(KEY_STAGE_HEIGHT, (int) stage.getHeight());
}
/**
* 永続領域に保存された状態を復元する。
*/
private void loadStatus(Stage stage) {
stage.setX(prefs.getInt(KEY_STAGE_X, 0));
stage.setY(prefs.getInt(KEY_STAGE_Y, 0));
stage.setWidth(prefs.getInt(KEY_STAGE_WIDTH, 320));
stage.setHeight(prefs.getInt(KEY_STAGE_HEIGHT, 200));
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
| 7,402 | 0.611936 | 0.60024 | 199 | 31.512564 | 21.621426 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.643216 | false | false | 1 |
9e75ec72d2f6972780aa591f5581e9a0d3a5e3b0 | 7,773,890,806,539 | 7e7bf02d437e95ec18a5b271e28338f0d305ee4b | /gcdemos/FeetConversionApp.java | 76097f775a2d5a0a634ffb6f49f617bdb7851a52 | [] | no_license | jlcenters/GrandCircusResourceCode | https://github.com/jlcenters/GrandCircusResourceCode | 17196cf1bd7a8c0afc828a89f95b85b55d52b1a8 | b3f44dda8e16f318d7d5d0b0b5b369be1bb4ac2b | refs/heads/master | 2022-04-28T04:41:53.568000 | 2020-04-27T06:10:23 | 2020-04-27T06:10:23 | 259,219,020 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package gcdemos;
import java.util.Scanner;
public class FeetConversionApp { //FeetConversionApp is an identifier
//this is a single line comment; close not used
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.println("Enter distance in feet."); //<-- that is 1 statement
double feet = scnr.nextInt();
/*These are block comments
* they cover multiple lines and can be placed between code bc of the closing punctuation
*/
double inches = feet * 12;
System.out.println("Inches: " + inches);
}
}
| UTF-8 | Java | 582 | java | FeetConversionApp.java | Java | [] | null | [] | package gcdemos;
import java.util.Scanner;
public class FeetConversionApp { //FeetConversionApp is an identifier
//this is a single line comment; close not used
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.println("Enter distance in feet."); //<-- that is 1 statement
double feet = scnr.nextInt();
/*These are block comments
* they cover multiple lines and can be placed between code bc of the closing punctuation
*/
double inches = feet * 12;
System.out.println("Inches: " + inches);
}
}
| 582 | 0.687285 | 0.682131 | 19 | 28.631578 | 26.948706 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.526316 | false | false | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.