blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 132 | path stringlengths 2 382 | src_encoding stringclasses 34
values | length_bytes int64 9 3.8M | score float64 1.5 4.94 | int_score int64 2 5 | detected_licenses listlengths 0 142 | license_type stringclasses 2
values | text stringlengths 9 3.8M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
3219141748b111a9f83495b34aa2a175eab7d935 | Java | beiyuanbing/aatrox-cloud | /services/oa/oa-service/src/main/java/com/aatrox/oaservice/service/impl/UserInfoServiceImpl.java | UTF-8 | 931 | 1.835938 | 2 | [] | no_license | package com.aatrox.oaservice.service.impl;
import com.aatrox.oa.apilist.form.UserInfoQueryPageForm;
import com.aatrox.oa.apilist.model.UserInfoModel;
import com.aatrox.oaservice.dao.UserInfoDao;
import com.aatrox.oaservice.service.UserInfoService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 用户表 服务实现类
* </p>
*
* @author aatrox
* @since 2019-08-21
*/
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoDao, UserInfoModel> implements UserInfoService {
@Override
public Page<UserInfoModel> selectPage(UserInfoQueryPageForm queryForm) {
Page<UserInfoModel> page = new Page<>(queryForm.getCurrentPage(), queryForm.getPageSize());
page.setRecords(baseMapper.selectPage(queryForm, page));
return page;
}
}
| true |
afddd79aa3b4d0f891eff103d32cad1ce341840f | Java | sulei945/t2 | /src/test/java/com/arrays/IntersectionOfTwoArrays.java | UTF-8 | 4,568 | 3.828125 | 4 | [] | no_license | package com.arrays;
import java.util.*;
/**
* Created by zhangwei on 2018/5/22.
* 两个数组的交集
给定两个数组,写一个函数来计算它们的交集。
例子:
给定 num1= [1, 2, 2, 1], nums2 = [2, 2], 返回 [2].
提示:
每个在结果中的元素必定是唯一的。
我们可以不考虑输出结果的顺序。
*/
public class IntersectionOfTwoArrays {
public static void main(String[] s){
new IntersectionOfTwoArrays().myIntersection1(new int[]{1}, new int[]{1});
}
//beats 11.43%
public int[] myintersection(int[] nums1, int[] nums2) {
//先对数组排序
Arrays.sort(nums1);
Arrays.sort(nums2);
//以更小对数组对长度为基准创建一个列表
List<Integer> result = new ArrayList<Integer>(nums1.length>nums2.length?nums2.length:nums1.length);
for(int i=0; i<nums1.length; i++){
//忽略nums1里相同元素的数据
if(i > 0 && nums1[i-1] == nums1[i]) continue;
//todo 这样循环好像会重复很多次每必要的情况
for(int j=0; j<nums2.length; j++){
//忽略nums2里相同元素的数据
if(j > 0 && nums2[j-1] == nums2[j]) continue;
//遇到相同的元素保存起来
if(nums1[i] == nums2[j]){
result.add(nums1[i]);
}
}
}
//整理并返回结果
int[] r = new int[result.size()];
for(int i=0; i<r.length; i++){
r[i] = result.get(i);
}
return r;
}
//beats 49.8%
public int[] myIntersection1(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
int l1 = nums1.length;
int l2 = nums2.length;
int[] r = new int[l1>l2?l2:l1];
int c1 = 0;
int c2 = 0;
int rc = 0;
while (c1 < l1 && c2 < l2){
if(c1>0 && nums1[c1] == nums1[c1-1]){
c1++;
continue;
}
if(c2>0 && nums2[c2] == nums2[c2-1]){
c2++;
continue;
}
if(nums1[c1] == nums2[c2]){
r[rc] = nums1[c1];
c1++;
c2++;
rc++;
}else if(nums1[c1] > nums2[c2]){
c2++;
}else {
c1++;
}
}
return Arrays.copyOfRange(r, 0, rc);
}
//beats 93.06%
public int[] myintersection2(int[] nums1, int[] nums2) {
//将nums1里的数据放在set里
Set<Integer> set = new HashSet<Integer>();
for(int i : nums1){
set.add(i);
}
List<Integer> result = new ArrayList<Integer>(nums1.length);
//分别对nums2里的数据探测是否是重合的
for(int i:nums2){
if(set.contains(i)){
result.add(i);
set.remove(i);
}
}
//整理并返回结果
int[] r = new int[result.size()];
for(int i=0; i<r.length; i++){
r[i] = result.get(i);
}
return r;
}
//beats 99.18%
public int[] myintersection3(int[] nums1, int[] nums2) {
Set<Integer> set = new HashSet<Integer>();
for(int i : nums1){
set.add(i);
}
//直接使用int[]来存储数据
int[] res = new int[nums1.length];
int c = 0;
for(int i:nums2){
if(set.contains(i)){
res[c++]=i;
set.remove(i);
}
}
//截取有效数据
return Arrays.copyOfRange(res, 0, c); //!!!!!!
}
//beats 100%
public int[] intersection(int[] nums1, int[] nums2) {
int[] res = new int[nums1.length];
if (nums1.length == 0 || nums2.length == 0) return new int[0];
int index = 0;
//对nums1里对所有数据做处理,通过对数子对应的位设置标记来记录数据
BitSet set = new BitSet(); //!!!!!!!
for (int i = 0; i < nums1.length; i++) {
set.set(nums1[i]);
}
//分别查看nums2里的所有数字对应的bit位标记的情况比对是否是nums1里存在的
for (int i = 0; i < nums2.length; i++) {
if (set.get(nums2[i]) == true) {
res[index++] = nums2[i];
set.set(nums2[i], false);
}
}
//截取有效数据
return Arrays.copyOfRange(res, 0, index);
}
}
| true |
9b871b9ff4df86eaaff1ba193c14aeb44572407e | Java | jesusjiyuan/web-handler | /common/src/main/java/com/bluexiii/jwh/util/StringUtil.java | UTF-8 | 1,969 | 2.953125 | 3 | [] | no_license | package com.bluexiii.jwh.util;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
public class StringUtil {
/**
* 格式化时间
*
* @param date
* @return
*/
public static String dateFormat(Date date) {
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = sdf.format(date);
return (date == null) ? "" : sdf.format(date);
}
/**
* 格式化Object[]
*
* @param obj
* @return
*/
public static Object[] convertObjects(Object[] obj) {
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (int j = 0; j < obj.length; j++) {
if (obj[j] == null) {
obj[j] = "";
} else if (obj[j] instanceof java.sql.Timestamp) {
obj[j] = sdf.format(obj[j]).toString();
} else {
obj[j] = obj[j].toString().trim();
}
}
return obj;
}
/**
* 格式化Object[]
*
* @param obj
* @return
*/
public static Object convertObjectToInt(Object obj) {
Object o;
if (obj.toString().length() == 0) {
o = new String("0");
} else {
o = obj;
}
return o;
}
/**
* 格式化str
*
* @param str
* @return
*/
public static String convertNullStr(String str) {
if (str == null || str.equalsIgnoreCase("null")) {
str = "";
}
return str;
}
public static String getSequence() {
UUID uuid = UUID.randomUUID();
String sequence = uuid.toString();
return sequence;
}
public static String getBornDate(String cardNum) {
if (cardNum == null || cardNum.length() != 18) {
return "";
}
cardNum = cardNum.substring(6, 14);
return cardNum;
}
}
| true |
43f9a22f9d818576e50eb335cb0c3fd56b492c42 | Java | Donotknowwhy/GameOTT | /src/client/LoginControl.java | UTF-8 | 2,267 | 2.234375 | 2 | [] | no_license | /*
* 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 client;
/**
*
* @author Admin
*/
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import model.Account;
import model.Message;
import model.User;
import ui.ListFrm;
import ui.LoginFrm;
import ui.RegisterFrm;
/**
*
* @author lamit
*/
public class LoginControl {
Account account = new Account();
Message mesRecei = new Message();
private LoginFrm loginFrm;
private ClientControl clientControl;
private ListFrm listFrm;
public LoginControl(LoginFrm loginFrm, ClientControl clientControl) {
this.clientControl = clientControl;
this.clientControl.setLoginControl(this);
this.loginFrm = loginFrm;
this.loginFrm.setAction(new ButtonListener(), new ButtonRegister());
}
class ButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String username = loginFrm.getUsername();
String password = loginFrm.getPassword();
account.setUsername(username);
account.setPassword(password);
Message mesSend = new Message(account, Message.MesType.LOGIN);
clientControl.sendData(mesSend);
}
}
public void showMessageFail() {
loginFrm.showMessage("Login Fail");
}
public void showMessageSuccess(Message mesRecei) {
loginFrm.showMessage("Login Success");
Message mesReq = new Message(account, Message.MesType.GET_SCOREBOARD);
clientControl.sendData(mesReq);
listFrm = new ListFrm();
InviteControl inviteControl = new InviteControl(clientControl, listFrm);
inviteControl.setUser((User) mesRecei.getObject());
listFrm.setVisible(true);
}
class ButtonRegister implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
RegisterFrm registerFrm = new RegisterFrm();
registerFrm.setVisible(true);
RegisterControl registerControl = new RegisterControl(registerFrm, clientControl);
}
}
} | true |
e3a7ec089940babde53098ce9b4a90bee7a59127 | Java | cgb-extjs-gwt/lingfeng | /src/com/lingfeng/service/sys/impl/RoleAuthorityServiceImpl.java | UTF-8 | 703 | 1.859375 | 2 | [] | no_license | package com.lingfeng.service.sys.impl;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.lingfeng.dao.sys.RoleAuthorityDao;
import com.lingfeng.model.sys.RoleAuthority;
import com.lingfeng.service.sys.RoleAuthorityService;
import core.service.BaseService;
/**
* @author David.Wang
* @email wangfeng090809@gmail.com
*/
@Service
public class RoleAuthorityServiceImpl extends BaseService<RoleAuthority> implements RoleAuthorityService {
private RoleAuthorityDao roleAuthorityDao;
@Resource
public void setRoleAuthorityDao(RoleAuthorityDao roleAuthorityDao) {
this.roleAuthorityDao = roleAuthorityDao;
this.dao = roleAuthorityDao;
}
}
| true |
3ced0a2b246bdd23c39bd5f41573e8d1a8dfa02c | Java | bestans/bestan | /bestan-db/src/main/java/bestan/common/db/RocksDBConfig.java | UTF-8 | 10,536 | 2.125 | 2 | [] | no_license | package bestan.common.db;
import java.util.Map;
import org.rocksdb.CompactionStyle;
import org.rocksdb.util.SizeUnit;
import com.google.common.collect.Maps;
import com.google.protobuf.Message;
import bestan.common.logic.FormatException;
import bestan.common.lua.BaseLuaConfig;
import bestan.common.lua.LuaAnnotation;
import bestan.common.lua.LuaException;
import bestan.common.lua.LuaParamAnnotation;
import bestan.common.lua.LuaParamAnnotation.LuaParamPolicy;
import bestan.common.message.IMessageLoadFinishCallback;
import bestan.common.message.MessageFactory;
import bestan.common.net.operation.TableDataType;
import bestan.common.net.operation.TableDataType.DataProcess;
@LuaAnnotation(load = false, optional = true)
public class RocksDBConfig extends BaseLuaConfig {
public static final RocksDBConfig option = new RocksDBConfig();
/**
* 数据库所在路径
*/
public String dbPath;
/**
* 数据库table表,key是数据库表名,value是解析的数据格式
*/
@LuaParamAnnotation(policy=LuaParamPolicy.REQUIRED)
public Map<String, TableStruct> tables = Maps.newHashMap();
/**
* 检查表message有效性
*/
public boolean checkTableMessageValid = false;
/**
* If true, the database will be created if it is missing
* Default: false
*/
public boolean createIfMissing = false;
/**
* If true, missing column families will be automatically created.
* Default: false
*/
public boolean createMissingColumnFamilies = false;
/**
* Maximal info log files to be kept.
* Default: 100
*/
public int keepLogFileNum = 100;
/**
* The periodicity when obsolete files get deleted. The default
* value is 6 hours. The files that get out of scope by compaction
* process will still get automatically delete on every compaction,
* regardless of this setting
*/
public long deleteObsoleteFilesPeriodMicros = 6L * 60 * 60 * 1000000;
/**
* The maximum number of write buffers that are built up in memory.
* The default and the minimum number is 2, so that when 1 write buffer
* is being flushed to storage, new writes can continue to the other write buffer.
* If max_write_buffer_number > 3, writing will be slowed down to options.
* delayed_write_rate if we are writing to the last write buffer allowed.
*
* DEFAULT:4
*/
public int maxWriteBufferNumber = 4;
/**
* Amount of data to build up in memory (backed by an unsorted log on disk)
* before converting to a sorted on-disk file.
* Larger values increase performance, especially during bulk loads.
* Up to max_write_buffer_number write buffers may be held in memory at the same time,
* so you may wish to adjust this parameter to control memory usage.
* Also, a larger write buffer will result in a longer recovery time
* the next time the database is opened.
* Note that write_buffer_size is enforced per column family.
* See db_write_buffer_size for sharing memory across column families.
* Default: 64MB
*
* the memory used by memtables is capped at maxWriteBufferNumber*writeBufferSize.
* When that is reached, any further writes are blocked until the flush finishes and frees memory used by the memtables.
* 期望的内存使用4 * 64M = 256M
*/
public long writeBufferSize = 64 * SizeUnit.MB;
/**
* The minimum number of write buffers that will be merged together
* before writing to storage. If set to 1, then
* all write buffers are flushed to L0 as individual files and this increases
* read amplification because a get request has to check in all of these
* files. Also, an in-memory merge may result in writing lesser
* data to storage if there are duplicate records in each of these
* individual write buffers.
*
* min_write_buffer_number_to_merge is the minimum number of memtables to be
* merged before flushing to storage. For example, if this option is set to 2,
* immutable memtables are only flushed when there are two of them - a single
* immutable memtable will never be flushed. If multiple memtables are merged together,
* less data may be written to storage since two updates are merged to a single key.
* However, every Get() must traverse all immutable memtables linearly to check if the key is there.
* Setting this option too high may hurt read performance.
* Default: 1
*/
public int minWriteBufferNumberToMerge = 1;
/**
* Target file size for compaction.
* target_file_size_base is per-file size for level-1.
* Target file size for level L can be calculated by
* target_file_size_base * (target_file_size_multiplier ^ (L-1))
* For example, if target_file_size_base is 2MB and
* target_file_size_multiplier is 10, then each file on level-1 will
* be 2MB, and each file on level 2 will be 20MB,
* and each file on level-3 will be 200MB.
*
* Default: 64MB.
*
* target_file_size_base and target_file_size_multiplier --
* Files in level 1 will have target_file_size_base bytes.
* Each next level's file size will be target_file_size_multiplier
* bigger than previous one. However, by default target_file_size_multiplier is 1,
* so files in all L1..Lmax levels are equal.
* Increasing target_file_size_base will reduce total number of database files,
* which is generally a good thing. We recommend setting target_file_size_base
* to be maxBytesForLevelBase / 10, so that there are 10 files in level 1.
*/
public long targetFileSizeBase = 32 * SizeUnit.MB;
/**
* Control maximum total data size for a level.
* max_bytes_for_level_base is the max total for level-1.
* Maximum number of bytes for level L can be calculated as
* (max_bytes_for_level_base) * (max_bytes_for_level_multiplier ^ (L-1))
* For example, if max_bytes_for_level_base is 200MB, and if
* max_bytes_for_level_multiplier is 10, total data size for level-1
* will be 200MB, total file size for level-2 will be 2GB,
* and total file size for level-3 will be 20GB.
*
* max_bytes_for_level_base and max_bytes_for_level_multiplier --
* max_bytes_for_level_base is total size of level 1. As mentioned,
* we recommend that this be around the size of level 0.
* Each subsequent level is max_bytes_for_level_multiplier larger than previous one.
* The default is 10 and we do not recommend changing that.
*
* Default: 256MB.
*/
public long maxBytesForLevelBase = 256 * SizeUnit.MB;
/**
* Number of open files that can be used by the DB. You may need to
* increase this if your database has a large working set. Value -1 means
* files opened are always kept open. You can estimate number of files based
* on target_file_size_base and target_file_size_multiplier for level-based
* compaction. For universal-style compaction, you can usually set it to -1.
*
* max_open_files -- RocksDB keeps all file descriptors in a table cache.
* If number of file descriptors exceeds max_open_files,
* some files are evicted from table cache and their file descriptors closed.
* This means that every read must go through the table cache to lookup the file needed.
* Set max_open_files to -1 to always keep all files open, which avoids expensive table cache calls.
* Default: -1
*/
public int maxOpenFiles = -1;
/**
* Maximum number of concurrent background jobs (compactions and flushes).
*/
public int maxBackgroundJobs = 2;
@LuaParamAnnotation(policy=LuaParamPolicy.OPTIONAL)
public CompactionStyle compactionStyle = CompactionStyle.LEVEL;
/**
* Number of files to trigger level-0 compaction. A value <0 means that
* level-0 compaction will not be triggered by number of files at all.
* Default: 4
*/
public int levelZeroFileNumCompactionTrigger = 4;
/**
* Soft limit on number of level-0 files. We start slowing down writes at this
* point. A value <0 means that no writing slow down will be triggered by
* number of files in level-0.
* Default: 20
*/
public int levelZeroSlowdownWritesTrigger = 20;
/**
* Maximum number of level-0 files. We stop writes at this point.
* Default: 30
*/
public int levelZeroStopWritesTrigger = 30;
/**
* Number of levels for this database
* Default: 5
*/
public int numLevels = 5;
/**
* table_factory -- Defines the table format. Here's the list of tables we support:
* Block based -- This is the default table. It is suited for storing data on disk and flash storage.
* It is addressed and loaded in block sized chunks (see block_size option). Thus the name block based.
* Plain Table -- Only makes sense with prefix_extractor.
* It is suited for storing data on memory (on tmpfs filesystem). It is byte-addressible.
* 默认使用Block based
* 以下都是BlockBasedTableConfig配置项
*/
/**
* Approximate size of user data packed per block. Note that the
* block size specified here corresponds to uncompressed data.
* The actual size of the unit read from disk may be smaller if compression is enabled.
* This parameter can be changed dynamically.
*/
public long blockSize = 32 * SizeUnit.KB;
public long blockCacheSize = 64 * SizeUnit.MB;
public boolean cacheIndexAndFilterBlocks = true;
@LuaAnnotation(optional=true)
public final static class TableStruct extends BaseLuaConfig implements IMessageLoadFinishCallback {
@LuaParamAnnotation(policy=LuaParamPolicy.REQUIRED)
public TableDataType keyType;
@LuaParamAnnotation(policy=LuaParamPolicy.REQUIRED)
public TableDataType valueType;
public String keyName = "";
public String valueName = "";
public DataProcess keyProcess;
public DataProcess valueProcess;
@Override
public void afterLoad() throws LuaException {
//注册回调,当message载入后,回调计算message
MessageFactory.registerLoadFinishCallback(this);
}
@Override
public void onMessageLoadFinish() throws Exception {
Message keyInstance = null;
if (keyType == TableDataType.MESSAGE) {
keyInstance = MessageFactory.getMessageInstance(keyName);
if (null == keyInstance) {
throw new FormatException("TableStruct parse key message type failed:invalid keyName=%s", keyName);
}
}
Message valueInstance = null;
if (valueType == TableDataType.MESSAGE) {
valueInstance = MessageFactory.getMessageInstance(valueName);
if (null == valueInstance) {
throw new FormatException("TableStruct parse value message type failed:invalid valueName=%s", valueName);
}
}
keyProcess = keyType.getProcess(keyInstance);
valueProcess = valueType.getProcess(valueInstance);
}
}
}
| true |
b439434af6cb96a8547e9ae1a381566267abf359 | Java | yanlei1117/iframe | /component.workflow/src/main/java/com/asiainfo/dbx/ln/component/workflow/activiti/tasklistener/ResultValue.java | UTF-8 | 1,075 | 2.40625 | 2 | [] | no_license | package com.asiainfo.dbx.ln.component.workflow.activiti.tasklistener;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ResultValue {
Logger logger = LoggerFactory.getLogger(ResultValue.class);
Map<String,Object> getResultMap(){
Map<String,Object> params = new HashMap<String,Object>();
params.put("result", getInput("please type task result :true/false?"));
return params;
}
Map<String,Object> getResultAndLoopMap(){
Map<String,Object> params = new HashMap<String,Object>();
params.put("result", getInput("please type task result :true/false?"));
params.put("loop", getInput("please type task loop :true/false?"));
return params;
}
Scanner scanner = new Scanner(System.in);
private String getInput(String tip){
logger.info(tip);
String line = scanner.nextLine();
line = line.trim();
if(line.equalsIgnoreCase("true")||line.equalsIgnoreCase("false")){
return line;
}else{
return getInput(tip);
}
}
}
| true |
fcd5ed5f97994eb4439db00ddddd18325b8cfc7c | Java | teiid/teiid | /connectors/infinispan/translator-infinispan-hotrod/src/main/java/org/teiid/translator/infinispan/hotrod/InfinispanUpdateVisitor.java | UTF-8 | 14,211 | 1.585938 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags and
* the COPYRIGHT.txt file distributed with this work.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.teiid.translator.infinispan.hotrod;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.teiid.infinispan.api.InfinispanDocument;
import org.teiid.infinispan.api.InfinispanPlugin;
import org.teiid.infinispan.api.MarshallerBuilder;
import org.teiid.infinispan.api.ProtobufMetadataProcessor;
import org.teiid.infinispan.api.TableWireFormat;
import org.teiid.language.ColumnReference;
import org.teiid.language.Condition;
import org.teiid.language.Delete;
import org.teiid.language.Expression;
import org.teiid.language.ExpressionValueSource;
import org.teiid.language.Insert;
import org.teiid.language.Literal;
import org.teiid.language.SQLConstants;
import org.teiid.language.SQLConstants.Tokens;
import org.teiid.language.Update;
import org.teiid.metadata.Column;
import org.teiid.metadata.RuntimeMetadata;
import org.teiid.metadata.Table;
import org.teiid.translator.TranslatorException;
public class InfinispanUpdateVisitor extends IckleConversionVisitor {
protected enum OperationType {INSERT, UPDATE, DELETE, UPSERT};
private OperationType operationType;
private InfinispanDocument insertPayload;
private Map<String, Object> updatePayload = new HashMap<>();
private Object identity;
private Condition whereClause;
public InfinispanUpdateVisitor(RuntimeMetadata metadata) {
super(metadata, true);
}
public Object getIdentity() {
return identity;
}
public OperationType getOperationType() {
return this.operationType;
}
public InfinispanDocument getInsertPayload() {
return insertPayload;
}
public Map<String, Object> getUpdatePayload() {
return updatePayload;
}
@Override
public void visit(Insert obj) {
this.operationType = OperationType.INSERT;
if (obj.isUpsert()) {
this.operationType = OperationType.UPSERT;
}
visitNode(obj.getTable());
Column pkColumn = getPrimaryKey();
if (pkColumn == null) {
this.exceptions.add(new TranslatorException(
InfinispanPlugin.Util.gs(InfinispanPlugin.Event.TEIID25013, getParentTable().getName())));
return;
}
if (obj.getParameterValues() == null) {
List<Expression> values = ((ExpressionValueSource)obj.getValueSource()).getValues();
this.insertPayload = buildInsertPayload(obj, values);
if (this.insertPayload != null) {
this.identity = this.insertPayload.getIdentifier();
}
}
}
Map<Object, InfinispanDocument> getBulkInsertPayload(Insert obj, int batchSize, Iterator<? extends List<Expression>> iter){
Map<Object, InfinispanDocument> updates = new TreeMap<>();
int count = 0;
while (iter.hasNext() && count++ < batchSize) {
InfinispanDocument doc = buildInsertPayload(obj, iter.next());
updates.put(doc.getIdentifier(), doc);
}
return updates;
}
private InfinispanDocument buildInsertPayload(Insert obj, List<Expression> values) {
InfinispanDocument targetDocument = null;
try {
// table that insert issued for
Table table = obj.getTable().getMetadataObject();
Column pkColumn = getPrimaryKey();
// create the top table parent document, where insert is actually being done at
targetDocument = buildTargetDocument(table, true);
// build the payload object from insert
int elementCount = obj.getColumns().size();
for (int i = 0; i < elementCount; i++) {
ColumnReference columnReference = obj.getColumns().get(i);
Column column = columnReference.getMetadataObject();
Object value = null;
if (values.get(i) instanceof Expression) {
Expression expr = values.get(i);
value = resolveExpressionValue(expr);
} else {
value = values.get(i);
}
updateDocument(targetDocument, column, value);
if (column.getName().equalsIgnoreCase(pkColumn.getName()) || pkColumn.getName()
.equalsIgnoreCase(normalizePseudoColumn(column, this.metadata).getName())) {
targetDocument.setIdentifier(value);
}
}
if (targetDocument.getIdentifier() == null) {
this.exceptions.add(new TranslatorException(
InfinispanPlugin.Util.gs(InfinispanPlugin.Event.TEIID25004, getParentTable().getName())));
}
} catch (NumberFormatException e) {
this.exceptions.add(new TranslatorException(e));
} catch (TranslatorException e) {
this.exceptions.add(new TranslatorException(e));
}
return targetDocument;
}
@SuppressWarnings("unchecked")
private void updateDocument(InfinispanDocument parentDocument, Column column, Object value)
throws TranslatorException {
boolean complexObject = this.nested;
InfinispanDocument targetDocument = parentDocument;
int parentTag = ProtobufMetadataProcessor.getParentTag(column);
if (parentTag != -1) {
// this is in one-2-one case. Dummy child will be there due to buildTargetDocument logic.
String messageName = ProtobufMetadataProcessor.getMessageName(column);
InfinispanDocument child = (InfinispanDocument)parentDocument.getChildDocuments(messageName).get(0);
targetDocument = child;
complexObject = true;
} else if (this.nested){
Table table = (Table)column.getParent();
String messageName = ProtobufMetadataProcessor.getMessageName(table);
InfinispanDocument child = (InfinispanDocument)parentDocument.getChildDocuments(messageName).get(0);
targetDocument = child;
complexObject = true;
}
if (!ProtobufMetadataProcessor.isPseudo(column)) {
if (value instanceof List) {
List<Object> l = (List<Object>)value;
for(Object o : l) {
targetDocument.addArrayProperty(getName(column), o);
}
} else {
targetDocument.addProperty(getName(column), value);
}
String attrName = MarshallerBuilder.getDocumentAttributeName(column, complexObject, this.metadata);
this.updatePayload.put(attrName, value);
}
}
private InfinispanDocument buildTargetDocument(Table table, boolean addDefaults) throws TranslatorException {
TreeMap<Integer, TableWireFormat> wireMap = MarshallerBuilder.getWireMap(getParentTable(), metadata);
String messageName = ProtobufMetadataProcessor.getMessageName(getParentTable());
InfinispanDocument parentDocument = new InfinispanDocument(messageName, wireMap, null);
// if there are any one-2-one relation build them and add defaults
addDefaults(parentDocument, getParentTable(), addDefaults);
// now create the document at child node, this is one-2-many case
if (!table.equals(getParentTable())) {
messageName = ProtobufMetadataProcessor.getMessageName(table);
int parentTag = ProtobufMetadataProcessor.getParentTag(table);
TableWireFormat twf = wireMap.get(TableWireFormat.buildNestedTag(parentTag));
this.nested = true;
InfinispanDocument child = new InfinispanDocument(messageName, twf.getNestedWireMap(), parentDocument);
addDefaults(child, table, addDefaults);
parentDocument.addChildDocument(messageName, child);
}
return parentDocument;
}
private void addDefaults(InfinispanDocument parentDocument, Table table, boolean addDefaults)
throws TranslatorException {
for (Column column : table.getColumns()) {
int parentTag = ProtobufMetadataProcessor.getParentTag(column);
if (parentTag != -1) {
String messageName = ProtobufMetadataProcessor.getMessageName(column);
List<?> children = parentDocument.getChildDocuments(messageName);
InfinispanDocument child = null;
if (children == null || children.isEmpty()) {
TableWireFormat twf = parentDocument.getWireMap().get(TableWireFormat.buildNestedTag(parentTag));
child = new InfinispanDocument(messageName, twf.getNestedWireMap(), parentDocument);
parentDocument.addChildDocument(messageName, child);
} else {
child = (InfinispanDocument)children.get(0);
}
if (addDefaults && column.getDefaultValue() != null) {
child.addProperty(getName(column), column.getDefaultValue());
}
} else {
if (addDefaults && column.getDefaultValue() != null) {
parentDocument.addProperty(getName(column), column.getDefaultValue());
}
}
}
}
public Column getPrimaryKey() {
Column pkColumn = null;
if (getParentTable().getPrimaryKey() != null) {
pkColumn = getParentTable().getPrimaryKey().getColumns().get(0);
}
return pkColumn;
}
private Object resolveExpressionValue(Expression expr) {
Object value = null;
if (expr instanceof Literal) {
value = ((Literal)expr).getValue();
}
else if (expr instanceof org.teiid.language.Array) {
org.teiid.language.Array contents = (org.teiid.language.Array)expr;
List<Expression> arrayExprs = contents.getExpressions();
List<Object> values = new ArrayList<Object>();
for (Expression exp:arrayExprs) {
if (exp instanceof Literal) {
values.add(((Literal)exp).getValue());
}
else {
this.exceptions.add(new TranslatorException(InfinispanPlugin.Util.gs(InfinispanPlugin.Event.TEIID25003, expr.getClass())));
}
}
value = values;
}
else {
this.exceptions.add(new TranslatorException(InfinispanPlugin.Util.gs(InfinispanPlugin.Event.TEIID25003, expr.getClass())));
}
return value;
}
@Override
public void visit(Update obj) {
this.operationType = OperationType.UPDATE;
append(obj.getTable());
if (obj.getWhere() != null) {
buffer.append(Tokens.SPACE).append(SQLConstants.Reserved.WHERE).append(Tokens.SPACE);
append(obj.getWhere());
// Can't use the original where string because it is designed for the document model querying
this.whereClause = obj.getWhere();
}
// table that update issued for
Table table = obj.getTable().getMetadataObject();
if (!table.equals(getParentTable())) {
this.nested = true;
}
// read the properties
try {
InfinispanDocument targetDocument = buildTargetDocument(table, false);
int elementCount = obj.getChanges().size();
for (int i = 0; i < elementCount; i++) {
Column column = obj.getChanges().get(i).getSymbol().getMetadataObject();
if (isPartOfPrimaryKey(column.getName())) {
throw new TranslatorException(InfinispanPlugin.Event.TEIID25019,
InfinispanPlugin.Util.gs(InfinispanPlugin.Event.TEIID25019, column.getName()));
}
Expression expr = obj.getChanges().get(i).getValue();
Object value = resolveExpressionValue(expr);
//this.updatePayload.put(getName(column), value);
updateDocument(targetDocument, column, value);
}
this.insertPayload = targetDocument;
} catch (TranslatorException e) {
this.exceptions.add(e);
}
}
@Override
public void visit(Delete obj) {
this.operationType = OperationType.DELETE;
append(obj.getTable());
// table that update issued for
Table table = obj.getTable().getMetadataObject();
if (!table.equals(getParentTable())) {
this.nested = true;
}
if (obj.getWhere() != null) {
buffer.append(Tokens.SPACE).append(SQLConstants.Reserved.WHERE).append(Tokens.SPACE);
append(obj.getWhere());
this.whereClause = obj.getWhere();
}
}
public String getUpdateQuery() {
StringBuilder sb = new StringBuilder();
sb.append(SQLConstants.Reserved.FROM);
sb.append(Tokens.SPACE).append(super.toString());
return sb.toString();
}
public String getDeleteQuery() {
StringBuilder sb = new StringBuilder();
if (!isNestedOperation()) {
addSelectedColumns(sb);
sb.append(Tokens.SPACE);
}
sb.append(SQLConstants.Reserved.FROM);
sb.append(Tokens.SPACE).append(super.toString());
return sb.toString();
}
Condition getWhereClause() {
return whereClause;
}
}
| true |
fc746b919fbc0d352208edbd4bbfec4d5cf7fcc1 | Java | jhelpgg/JHelpWebsiteCreator | /src/jhelp/websitecreator/model/text/ElementImage.java | UTF-8 | 4,651 | 2.765625 | 3 | [] | no_license | /**
* <h1>License :</h1> <br>
* The following code is deliver as is. I take care that code compile and work, but I am not responsible about any
* damage it may
* cause.<br>
* You can use, modify, the code as your need for any usage. But you can't do any action that avoid me or other person use,
* modify this code. The code is free for usage and modification, you can't change that fact.<br>
* <br>
*
* @author JHelp
*/
package jhelp.websitecreator.model.text;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import jhelp.util.gui.JHelpImage;
import jhelp.util.io.ByteArray;
import jhelp.util.math.UtilMath;
import jhelp.websitecreator.model.Project;
/**
* Element of image
*/
public class ElementImage implements BlockElement
{
/**
* Image default name
*/
public static final String IMAGE_DEFAULT = "--IMAGE_DEFAULT---";
/**
* Image size (in {1, 2, ..., 12}
*/
private int size;
/**
* Image name
*/
private String imageName;
/**
* Create empty image
*/
public ElementImage()
{
this.size = 12;
this.imageName = IMAGE_DEFAULT;
}
/**
* Obtain size value
*
* @return size value
*/
public int getSize()
{
return this.size;
}
/**
* Modify size value
*
* @param size New size value
*/
public void setSize(int size)
{
if (size < 1 || size > 12)
{
throw new IllegalArgumentException("size MUST be in {1, 2, .., 12} not " + size);
}
this.size = size;
}
/**
* Obtain imageName value
*
* @return imageName value
*/
public String getImageName()
{
return this.imageName;
}
/**
* Modify imageName value
*
* @param imageName New imageName value
*/
public void setImageName(String imageName)
{
if (imageName == null)
{
throw new NullPointerException("imageName MUST NOT be null !");
}
this.imageName = imageName;
}
/**
* Write object in HTML
*
* @param project Project reference
* @param bufferedWriter Stream where write
* @throws IOException On writing issue
*/
@Override
public void writeInHTML(Project project, BufferedWriter bufferedWriter) throws IOException
{
int size = 12;
try
{
JHelpImage image = JHelpImage.loadImage(new File(project.imagesDirectory(), this.imageName));
size = UtilMath.limit((image.getWidth() * 12) >> 10, 1, 12);
}
catch (Exception ignored)
{
}
bufferedWriter.write("<image src=\"");
bufferedWriter.write(project.getImagesPath());
bufferedWriter.write(this.imageName);
bufferedWriter.write("\" class=\"col-");
bufferedWriter.write(String.valueOf(size));
bufferedWriter.write(" col-m-");
bufferedWriter.write(String.valueOf(size));
bufferedWriter.write("\"/>");
bufferedWriter.flush();
}
/**
* Parse the array for fill binarizable information.<br>
* See {@link #serializeBinary(ByteArray)} for fill information
*
* @param byteArray Byte array to parse
*/
@Override
public void parseBinary(ByteArray byteArray)
{
this.size = byteArray.readInteger();
this.imageName = byteArray.readString();
}
/**
* Write the binarizable information inside a byte array.<br>
* See {@link #parseBinary(ByteArray)} for read information
*
* @param byteArray Byte array where write
*/
@Override
public void serializeBinary(ByteArray byteArray)
{
byteArray.writeInteger(this.size);
byteArray.writeString(this.imageName);
}
/**
* String representation
*
* @return String representation
*/
@Override
public String toString()
{
return "IMAGE:" + this.imageName;
}
/**
* Indicates if compressible with given element
*
* @param blockElement Element to compress with
* @return {@code false} because can't compress image with anything
*/
@Override
public boolean compressibleWith(BlockElement blockElement)
{
return false;
}
/**
* Try compress with an other element
*
* @param blockElement Element to compress with
* @return {@code null} beacuse compress with image always failed
*/
@Override
public BlockElement compressWith(BlockElement blockElement)
{
return null;
}
}
| true |
76523d7b6d39e6e4d94045ddcdfc155be19ab03a | Java | kalindurajapaksha/Reminder | /app/src/main/java/com/rtlabs/application1/Reminder.java | UTF-8 | 1,479 | 2.40625 | 2 | [] | no_license | package com.rtlabs.application1;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
import java.io.Serializable;
@Entity(tableName = "reminder")
public class Reminder implements Serializable{
@ColumnInfo(name = "des")
private String description;
@ColumnInfo(name = "time")
private String time;
@ColumnInfo(name = "date")
private String date;
public int getAlarmid() {
return alarmid;
}
public void setAlarmid(int alarmid) {
this.alarmid = alarmid;
}
@ColumnInfo(name = "aid")
private int alarmid;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@PrimaryKey(autoGenerate = true)
private int id;
public Reminder(String description, String time, String date,int alarmid) {
this.description = description;
this.time = time;
this.date = date;
this.alarmid = alarmid;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
| true |
44a1c5d102bef2bba23347bb60497e5c5572f9b6 | Java | aheadlcx/analyzeApk | /budejie/sources/com/budejie/www/adapter/a/m$b.java | UTF-8 | 273 | 1.734375 | 2 | [] | no_license | package com.budejie.www.adapter.a;
import android.widget.ImageView;
import com.androidex.widget.asyncimage.AsyncImageView;
class m$b {
final /* synthetic */ m a;
private AsyncImageView b;
private ImageView c;
m$b(m mVar) {
this.a = mVar;
}
}
| true |
918bdc08c8b4c8714d7719e3a0e7a951afb135cb | Java | Andresninetyfour/TableLoad | /src/main/main.java | UTF-8 | 2,287 | 2.25 | 2 | [] | no_license | package main;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.commons.io.FileUtils;
import org.json.CDL;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;
import com.fasterxml.jackson.dataformat.csv.CsvSchema.Builder;
import com.google.gson.Gson;
import model.Model;
public class main {
public static void main(String[] args) throws Exception{
String file = "/export/home/alara/Desktop/TableLoad/contentdb_confirmation.json";
String json = readFileAsString(file);
String data = json.replace("} ] }", "} ] },");
String data1 = data.replace(" \"GENERAL\" }", "\"GENERAL\" },");
String finalstring = data1.substring(0, data1.length()-3);
StringBuilder add = new StringBuilder(finalstring);
add.insert(0, "[");
add.insert(finalstring.length()+1, "]");
//System.out.println(add);
PrintWriter writer = new PrintWriter("the-file-name.json", "UTF-8");
writer.println(add.toString());
writer.close();
/*JsonNode jsonTree = new ObjectMapper().readTree(new File("/export/home/alara/Desktop/TableLoad/the-file-name.txt"));
Builder csvSchemaBuilder = CsvSchema.builder();
JsonNode firstObject = jsonTree.elements().next();
firstObject.fieldNames().forEachRemaining(fieldName -> {csvSchemaBuilder.addColumn(fieldName);});
CsvSchema csvSchema = csvSchemaBuilder.build().withHeader();
CsvMapper csvMapper = new CsvMapper();
csvMapper.writerFor(JsonNode.class)
.with(csvSchema)
.writeValue(new File("/export/home/alara/Desktop/TableLoad/orderLines.csv"), jsonTree);*/
}
public static String readFileAsString(String file) throws Exception{
return new String(Files.readAllBytes(Paths.get(file)));
}
}
| true |
e9856fddb2ef77d3d507ce918bccfd36ee51114b | Java | apocalypeseed/antiFacebook | /src/main/java/com/thomas/final_project1/HomeController.java | UTF-8 | 2,728 | 2.234375 | 2 | [] | no_license | package com.thomas.final_project1;
import com.cloudinary.utils.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.validation.Valid;
import java.io.IOException;
import java.security.Principal;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
@Controller
public class HomeController
{
@Autowired
private UserService userService;
@Autowired
PostRepository postRepository;
@Autowired
CloudinaryConfig cloudc;
@GetMapping("/register")
public String showRegistrationPage(Model model)
{
model.addAttribute("user", new User());
return "registration";
}
@PostMapping("/register")
public String processRegistrationPage(@Valid @ModelAttribute("user") User user, BindingResult result, Model model)
{
model.addAttribute("user", user);
if(result.hasErrors())
{
return "registration";
}
else
{
userService.saveUser(user);
return "redirect:/login";
}
}
@RequestMapping("/login")
public String login()
{
return "login";
}
@GetMapping("/postReply")
public String postReply(Model model)
{
model.addAttribute("post", new Post());
return "postReply";
}
@PostMapping("/process")
public String loadReplies(@ModelAttribute Post post, Principal principal,
@RequestParam("imageReceive")MultipartFile file)
{
if(principal.getName().isEmpty())
return "redirect:/login";
if(file.isEmpty())
return "redirect:/postReply";
Set<Post> posts = new HashSet<Post>();
User currentUser = userService.findByUsername(principal.getName());
post.setUser(currentUser);
try {
Map uploadResult = cloudc.upload(file.getBytes(), ObjectUtils.asMap("resourcetype", "auto"));
post.setHeadshot(uploadResult.get("url").toString());
postRepository.save(post);
} catch (IOException e){
return "redirect:/postReply";
}
return "redirect:/";
}
@RequestMapping("/")
public String listOfPosts(Model model)
{
model.addAttribute("users", userService.findAll());
return "listPosts";
}
@RequestMapping("/signOut")
public String signOut()
{
//Remove user from active session
return "signOut";
}
}
| true |
421f9f71350493ec50f6257493605ef013b88d61 | Java | DembinskiD/mosura | /src/main/java/pl/mosura/entity/data_modules.java | UTF-8 | 545 | 1.6875 | 2 | [] | no_license | package pl.mosura.entity;
import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Data
@Entity
public class data_modules {
@Id
@GeneratedValue
private long id;
private long module_id;
private Integer pid;
private Boolean enabled;
private String timestamp;
private Integer mod_memory;
private Integer logs_memory;
private Integer logs_counter;
private String version;
private String start_time;
private String up_time;
}
| true |
7c4cc5d0465589e02953a0d7860c0ad6ab65307a | Java | jmcs811/CMSC350 | /Project4/src/com/jcaseydev/Main.java | UTF-8 | 6,903 | 2.875 | 3 | [] | no_license | package com.jcaseydev;
/////////////////////////////
// Filename: Main.java
// Author: Justin Casey
// Data: 10 Oct 2019
//
// This is the class the defines the GUI and handles
// the actions of the buttons
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.io.IOException;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class Main extends JFrame {
private String fileName;
private String className;
private DirectedGraph<String> directedGraph;
private Main() {
super("Class Dependency Graph");
// create gui panels
JPanel mainPanel = new JPanel();
JPanel labelPanel = new JPanel();
JPanel textPanel = new JPanel();
JPanel buttonPanel = new JPanel();
JPanel inputPanel = new JPanel();
JPanel outputPanel = new JPanel();
// set panel layouts
mainPanel.setLayout(new GridBagLayout());
labelPanel.setLayout(new GridBagLayout());
textPanel.setLayout(new GridBagLayout());
buttonPanel.setLayout(new GridBagLayout());
inputPanel.setLayout(new GridBagLayout());
outputPanel.setLayout(new BorderLayout());
// create all gui elements (buttons, fields, etc)
JButton graphButton = new JButton("Build Directed Graph");
JButton topologicalButton = new JButton("Topological Order");
JButton clearTextButton = new JButton("Clear Text");
JTextField fileTextField = new JTextField(null, 20);
JTextField classTextField = new JTextField(null, 20);
JLabel fileLabel = new JLabel("Input File Name:");
JLabel classLabel = new JLabel("Class to recompile:");
JTextArea outputText = new JTextArea();
JScrollPane scrollPane = new JScrollPane(outputText);
// add elements to panels
GridBagConstraints constraints = new GridBagConstraints();
constraints.insets = new Insets(5, 5, 5, 5);
constraints.gridx = 0;
constraints.gridy = 0;
constraints.weightx = 1;
constraints.weighty = .5;
labelPanel.add(fileLabel, constraints);
constraints.gridx = 0;
constraints.gridy = 1;
constraints.weightx = 1;
constraints.weighty = .5;
labelPanel.add(classLabel, constraints);
constraints.gridx = 0;
constraints.gridy = 0;
constraints.weightx = 1;
constraints.weighty = .5;
textPanel.add(fileTextField, constraints);
constraints.gridx = 0;
constraints.gridy = 1;
constraints.weightx = 1;
constraints.weighty = .5;
textPanel.add(classTextField, constraints);
constraints.gridx = 0;
constraints.gridy = 0;
constraints.weightx = 1;
constraints.weighty = .5;
buttonPanel.add(graphButton, constraints);
constraints.gridx = 0;
constraints.gridy = 1;
constraints.weightx = 1;
constraints.weighty = .5;
buttonPanel.add(topologicalButton, constraints);
constraints.gridx = 0;
constraints.gridy = 2;
constraints.weightx = 1;
constraints.weighty = 0.5;
buttonPanel.add(clearTextButton, constraints);
outputPanel.setBorder(BorderFactory.createTitledBorder("Recompilation Order"));
outputText.setLineWrap(true);
outputText.setWrapStyleWord(true);
outputText.setEditable(false);
outputPanel.add(scrollPane);
constraints.fill = GridBagConstraints.BOTH;
inputPanel.setBorder(BorderFactory.createTitledBorder(""));
constraints.gridx = 0;
constraints.gridy = 0;
constraints.weightx = 1;
constraints.weighty = 1;
inputPanel.add(labelPanel, constraints);
constraints.gridx = 1;
constraints.gridy = 0;
constraints.weightx = 1;
constraints.weighty = 1;
inputPanel.add(textPanel, constraints);
constraints.gridx = 2;
constraints.gridy = 0;
constraints.weightx = 1;
constraints.weighty = 1;
inputPanel.add(buttonPanel, constraints);
constraints.insets = new Insets(1, 2, 1, 2);
constraints.gridx = 0;
constraints.gridy = 0;
constraints.weightx = 1;
constraints.weighty = 0;
mainPanel.add(inputPanel, constraints);
constraints.gridx = 0;
constraints.gridy = 1;
constraints.weightx = 1;
constraints.weighty = 1;
mainPanel.add(outputPanel, constraints);
add(mainPanel);
// set jframe settings
setSize(650, 400);
setVisible(true);
setResizable(false);
// graph button listener
graphButton.addActionListener((ActionEvent e) -> {
directedGraph = new DirectedGraph<>();
fileName = fileTextField.getText();
try {
if (fileName.isEmpty()) {
throw new NullPointerException();
}
directedGraph.buildGraph(directedGraph.tokenize(fileName));
JOptionPane.showMessageDialog(
null,
"Graph Build Successfully",
"Message",
JOptionPane.INFORMATION_MESSAGE
);
fileTextField.setEditable(false);
graphButton.setEnabled(false);
} catch (NullPointerException npe) {
JOptionPane.showMessageDialog(
null,
"A file must be specified",
"Error",
JOptionPane.ERROR_MESSAGE
);
} catch (IOException ex) {
JOptionPane.showMessageDialog(
null,
"File did not open",
"Error",
JOptionPane.ERROR_MESSAGE
);
fileTextField.setText("");
}
});
// order button listener
topologicalButton.addActionListener((
ActionEvent e) ->
{
className = classTextField.getText();
try {
outputText.setText(directedGraph.orderGenerator(className));
} catch (InvalidClassNameException ex) {
JOptionPane.showMessageDialog(
null,
"Invalid Class Name: " + className,
"Error",
JOptionPane.ERROR_MESSAGE
);
} catch (ContainsCycleException ex) {
JOptionPane.showMessageDialog(
null,
"Graph contains a cycle",
"Message",
JOptionPane.INFORMATION_MESSAGE
);
} catch (NullPointerException npe) {
JOptionPane.showMessageDialog(
null,
"Build Graph First",
"Message",
JOptionPane.INFORMATION_MESSAGE
);
classTextField.setText("");
}
});
// clear text button listener
clearTextButton.addActionListener((
ActionEvent e) ->
{
classTextField.setText("");
fileTextField.setText("");
outputText.setText("");
fileTextField.setEditable(true);
graphButton.setEnabled(true);
});
}
public static void main(String[] args) {
new Main();
}
}
| true |
93872229c03ced224058db263c6d9b593b0fefca | Java | vikaas127/driverapplicationvikas | /app/src/main/java/com/jaats/agrovehicledriver/activity/ForgotPasswordActivity.java | UTF-8 | 3,464 | 2.140625 | 2 | [] | no_license | package com.jaats.agrovehicledriver.activity;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.view.HapticFeedbackConstants;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import org.json.JSONException;
import org.json.JSONObject;
import com.jaats.agrovehicledriver.R;
import com.jaats.agrovehicledriver.app.App;
import com.jaats.agrovehicledriver.listeners.BasicListener;
import com.jaats.agrovehicledriver.model.BasicBean;
import com.jaats.agrovehicledriver.net.DataManager;
import com.jaats.agrovehicledriver.util.AppConstants;
public class ForgotPasswordActivity extends BaseAppCompatNoDrawerActivity {
private Button btnReset;
private EditText etxtEmail;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forgot_password);
getSupportActionBar().hide();
swipeView.setPadding(0, 0, 0, 0);
initViews();
}
private void initViews() {
btnReset = (Button) findViewById(R.id.btn_forgot_password_reset);
etxtEmail = (EditText) findViewById(R.id.etxt_forgot_password_email);
etxtEmail.setTypeface(typeface);
btnReset.setTypeface(typeface);
}
public void onForgotPasswordResetClick(View view) {
view.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
// mVibrator.vibrate(25);
if (collectForgotPasswordData()) {
if (App.isNetworkAvailable()) {
performForgotPassword();
}else{
Snackbar.make(coordinatorLayout, AppConstants.NO_NETWORK_AVAILABLE, Snackbar.LENGTH_LONG)
.setAction(R.string.btn_dismiss, snackBarDismissOnClickListener).show();
}
}
}
private void performForgotPassword() {
JSONObject postData = getForgotPasswordJSObj();
DataManager.performForgotPassword(postData, new BasicListener() {
@Override
public void onLoadCompleted(BasicBean basicBean) {
finish();
}
@Override
public void onLoadFailed(String error) {
Snackbar.make(coordinatorLayout, error, Snackbar.LENGTH_LONG)
.setAction(R.string.btn_dismiss, snackBarDismissOnClickListener).show();
}
});
}
private JSONObject getForgotPasswordJSObj() {
JSONObject postData = new JSONObject();
try {
postData.put("email", etxtEmail.getText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
return postData;
}
private boolean collectForgotPasswordData() {
if (etxtEmail.getText().toString().equals("")) {
Snackbar.make(coordinatorLayout, R.string.message_enter_email_to_recover_password, Snackbar.LENGTH_LONG)
.setAction(R.string.btn_dismiss, snackBarDismissOnClickListener).show();
return false;
} else if (!android.util.Patterns.EMAIL_ADDRESS.matcher(etxtEmail.getText().toString()).matches()) {
Snackbar.make(coordinatorLayout, R.string.message_enter_a_valid_email_address, Snackbar.LENGTH_LONG)
.setAction(R.string.btn_dismiss, snackBarDismissOnClickListener).show();
return false;
}
return true;
}
}
| true |
84a6542ded37dd0a087f79c8686b7357e695dcec | Java | apache/storm | /storm-client/src/jvm/org/apache/storm/grouping/ShuffleGrouping.java | UTF-8 | 2,181 | 2.328125 | 2 | [
"BSD-3-Clause",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-2-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.1-only",
"EPL-1.0",
"MPL-1.1",
"W3C",
"Classpath-exception-2.0",
"MPL-2.0",
"EPL-2.0",
... | permissive | /**
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version
* 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package org.apache.storm.grouping;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.storm.generated.GlobalStreamId;
import org.apache.storm.task.WorkerTopologyContext;
public class ShuffleGrouping implements CustomStreamGrouping, Serializable {
private ArrayList<List<Integer>> choices;
private AtomicInteger current;
@Override
public void prepare(WorkerTopologyContext context, GlobalStreamId stream, List<Integer> targetTasks) {
choices = new ArrayList<List<Integer>>(targetTasks.size());
for (Integer i : targetTasks) {
choices.add(Arrays.asList(i));
}
current = new AtomicInteger(0);
Collections.shuffle(choices, new Random());
}
@Override
public List<Integer> chooseTasks(int taskId, List<Object> values) {
int rightNow;
int size = choices.size();
while (true) {
rightNow = current.incrementAndGet();
if (rightNow < size) {
return choices.get(rightNow);
} else if (rightNow == size) {
current.set(0);
return choices.get(0);
}
} // race condition with another thread, and we lost. try again
}
}
| true |
a1ac27e9a771a95f90a2ae3c4e95c8dac2263e28 | Java | HannibalCJH/Leetcode-Practice | /245. Shortest Word Distance III/Java: Solution.java | UTF-8 | 1,427 | 3.640625 | 4 | [] | no_license | public class Solution {
// 时间复杂度O(n),空间复杂度O(1)
public int shortestWordDistance(String[] words, String word1, String word2)
{
// 初始化最小长度为数组的长度
int minDist = words.length;
int idx1 = -1, idx2 = -1;
// 标记两个单词是否相等
boolean equal = word1.equals(word2);
// 唯一的不同之处在于当两个数相同,我们要保持idx1和idx2在一次循环以后是相等的,都指向上一次相同单词的位置,
// 这样我们只需要在判断word1的时候比较一下更新后的idx1和指向上一次相同单词的idx2之间的距离,然后再同步更新idx2和idx1一致,
// 但是跳过word2里的minDist的赋值就行
for(int i = 0; i < words.length; i++)
{
// 当前单词等于word1或者word2时,计算一下长度
if(words[i].equals(word1))
{
idx1 = i;
if(idx2 >= 0)
minDist = Math.min(minDist, idx1 - idx2);
}
if(words[i].equals(word2))
{
idx2 = i;
// 两个单词如果相等那就不用再次比较,不然会是0
if(idx1 >= 0 && !equal)
minDist = Math.min(minDist, idx2 - idx1);
}
}
return minDist;
}
}
| true |
daa67ed16eca2baff80daa76a0e1cc35874d52f4 | Java | lokmanugur/LibraryAtomationSystem | /src/com/ugurtech/library/view/student/StudentSearchForm.java | UTF-8 | 16,149 | 2.453125 | 2 | [] | no_license | package com.ugurtech.library.view.student;
import com.ugurtech.library.controller.StudentSearchFormController;
import com.ugurtech.library.generalclasses.TableToExcelImpl;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JInternalFrame;
/**
*
* @author lokman uğur
*
*/
public final class StudentSearchForm extends JInternalFrame {
private static StudentSearchForm studentSearchForm;
private final StudentSearchFormController studentSearchFormController;
private StudentSearchForm() {
initComponents();
studentSearchFormController = new StudentSearchFormController(this);
setLocation(getWidth()/10,getHeight()/10);
}
public static StudentSearchForm getInstance(){
if(studentSearchForm == null)
return studentSearchForm = new StudentSearchForm();
else
return studentSearchForm;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
panelToolBar = new javax.swing.JPanel();
panelGuncelleme = new javax.swing.JPanel();
updateButton = new javax.swing.JButton();
deleteButton = new javax.swing.JButton();
panelSearch = new javax.swing.JPanel();
studentNumberTextField = new javax.swing.JTextField();
labelID = new javax.swing.JLabel();
searchButton = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
studentNameTextField = new javax.swing.JTextField();
panelOut = new javax.swing.JPanel();
writeFlileButton = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
studentTable = new javax.swing.JTable();
setClosable(true);
setIconifiable(true);
setMaximizable(true);
setResizable(true);
setTitle("Öğrenci Bilgi Ayrıntı Tablosu");
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
panelGuncelleme.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))));
updateButton.setText("Güncelle");
updateButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
updateButtonActionPerformed(evt);
}
});
deleteButton.setText("Sil");
deleteButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
deleteButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout panelGuncellemeLayout = new javax.swing.GroupLayout(panelGuncelleme);
panelGuncelleme.setLayout(panelGuncellemeLayout);
panelGuncellemeLayout.setHorizontalGroup(
panelGuncellemeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelGuncellemeLayout.createSequentialGroup()
.addGap(7, 7, 7)
.addGroup(panelGuncellemeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(deleteButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(updateButton, javax.swing.GroupLayout.DEFAULT_SIZE, 86, Short.MAX_VALUE))
.addContainerGap())
);
panelGuncellemeLayout.setVerticalGroup(
panelGuncellemeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelGuncellemeLayout.createSequentialGroup()
.addContainerGap()
.addComponent(updateButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(deleteButton)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
panelSearch.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)), "Ara", javax.swing.border.TitledBorder.LEFT, javax.swing.border.TitledBorder.TOP));
studentNumberTextField.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
studentNumberTextFieldKeyReleased(evt);
}
});
labelID.setText("Öğrenci No:");
searchButton.setText("Ara");
searchButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
searchButtonActionPerformed(evt);
}
});
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel1.setText("Adı Soyadı:");
studentNameTextField.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
studentNameTextFieldKeyReleased(evt);
}
});
javax.swing.GroupLayout panelSearchLayout = new javax.swing.GroupLayout(panelSearch);
panelSearch.setLayout(panelSearchLayout);
panelSearchLayout.setHorizontalGroup(
panelSearchLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelSearchLayout.createSequentialGroup()
.addContainerGap(16, Short.MAX_VALUE)
.addComponent(labelID)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(studentNumberTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(7, 7, 7)
.addComponent(studentNameTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 156, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(searchButton, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(15, Short.MAX_VALUE))
);
panelSearchLayout.setVerticalGroup(
panelSearchLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelSearchLayout.createSequentialGroup()
.addContainerGap()
.addGroup(panelSearchLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(searchButton, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(panelSearchLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelSearchLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(studentNumberTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(labelID, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(panelSearchLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(studentNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
panelOut.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)), "Çıktı", javax.swing.border.TitledBorder.LEFT, javax.swing.border.TitledBorder.TOP));
writeFlileButton.setText("Excelle Yaz");
writeFlileButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
writeFlileButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout panelOutLayout = new javax.swing.GroupLayout(panelOut);
panelOut.setLayout(panelOutLayout);
panelOutLayout.setHorizontalGroup(
panelOutLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelOutLayout.createSequentialGroup()
.addGap(7, 7, 7)
.addComponent(writeFlileButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
panelOutLayout.setVerticalGroup(
panelOutLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelOutLayout.createSequentialGroup()
.addContainerGap()
.addComponent(writeFlileButton)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout panelToolBarLayout = new javax.swing.GroupLayout(panelToolBar);
panelToolBar.setLayout(panelToolBarLayout);
panelToolBarLayout.setHorizontalGroup(
panelToolBarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelToolBarLayout.createSequentialGroup()
.addContainerGap(22, Short.MAX_VALUE)
.addComponent(panelSearch, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(panelGuncelleme, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(panelOut, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(22, Short.MAX_VALUE))
);
panelToolBarLayout.setVerticalGroup(
panelToolBarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelToolBarLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(panelToolBarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(panelSearch, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(panelOut, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(panelGuncelleme, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
studentTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
}
)
{public boolean isCellEditable(int row, int column){return false;}}
);
jScrollPane1.setViewportView(studentTable);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(panelToolBar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(panelToolBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(11, 11, 11)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 419, Short.MAX_VALUE))
);
getAccessibleContext().setAccessibleName("Menu Hareket");
pack();
}// </editor-fold>//GEN-END:initComponents
private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchButtonActionPerformed
studentSearchFormController.fillAllStudents();
}//GEN-LAST:event_searchButtonActionPerformed
private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
studentSearchFormController.deleteStudent();
}//GEN-LAST:event_deleteButtonActionPerformed
private void updateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateButtonActionPerformed
studentSearchFormController.updateStudent();
}//GEN-LAST:event_updateButtonActionPerformed
private void writeFlileButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_writeFlileButtonActionPerformed
new TableToExcelImpl(studentTable, "Öğrenci Bilgi Tablosu").writeToTable();
}//GEN-LAST:event_writeFlileButtonActionPerformed
private void studentNumberTextFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_studentNumberTextFieldKeyReleased
studentSearchFormController.fillAllStudents();
}//GEN-LAST:event_studentNumberTextFieldKeyReleased
private void studentNameTextFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_studentNameTextFieldKeyReleased
studentSearchFormController.fillAllStudents();
}//GEN-LAST:event_studentNameTextFieldKeyReleased
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton deleteButton;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel labelID;
private javax.swing.JPanel panelGuncelleme;
private javax.swing.JPanel panelOut;
private javax.swing.JPanel panelSearch;
private javax.swing.JPanel panelToolBar;
private javax.swing.JButton searchButton;
private javax.swing.JTextField studentNameTextField;
private javax.swing.JTextField studentNumberTextField;
private javax.swing.JTable studentTable;
private javax.swing.JButton updateButton;
private javax.swing.JButton writeFlileButton;
// End of variables declaration//GEN-END:variables
public JTextField getStudentNameTextField() {
return studentNameTextField;
}
public void setStudentNameTextField(JTextField studentNameTextField) {
this.studentNameTextField = studentNameTextField;
}
public JTextField getStudentNumberTextField() {
return studentNumberTextField;
}
public void setStudentNumberTextField(JTextField studentNumberTextField) {
this.studentNumberTextField = studentNumberTextField;
}
public JTable getStudentTable() {
return studentTable;
}
public void setStudentTable(JTable studentTable) {
this.studentTable = studentTable;
}
}
| true |
cbea0207a15a3ea1b0c018381f2cbfe86d484668 | Java | SnowVolf/Gravity-Defied | /app/src/main/java/org/happysanta/gd/Levels/Reader.java | UTF-8 | 1,211 | 2.796875 | 3 | [] | no_license | package org.happysanta.gd.Levels;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import static org.happysanta.gd.Helpers.decodeCp1251;
public class Reader {
private static final int MAX_VALID_TRACKS = 16384;
public static LevelHeader readHeader(InputStream in) throws IOException {
LevelHeader header = new LevelHeader();
DataInputStream din = new DataInputStream(in);
byte buf[] = new byte[40];
String tmp;
for (int i = 0; i < 3; i++) {
int tCount = din.readInt();
if (tCount > MAX_VALID_TRACKS) {
din.close();
throw new IOException("Level file is not valid");
}
header.setCount(i, tCount);
label0:
for (int j = 0; j < header.getCount(i); j++) {
int trackPointer = din.readInt();
header.setPointer(i, j, trackPointer);
int nameLen = 0;
do {
if (nameLen >= 40)
continue label0;
buf[nameLen] = din.readByte();
if (buf[nameLen] == 0) {
// tmp = (new String(buf, 0, nameLen, "CP-1251"));
tmp = decodeCp1251(buf);
header.setName(i, j, tmp.replace('_', ' '));
continue label0;
}
nameLen++;
} while (true);
}
}
din.close();
return header;
}
}
| true |
c43afda613f6edea98a45ebe0694b28d6f15c2e3 | Java | laa/lsmtrie | /src/test/java/com/orientechnologies/lsmtrie/LSMTrieLoadTest.java | UTF-8 | 10,282 | 2.359375 | 2 | [] | no_license | package com.orientechnologies.lsmtrie;
import com.google.common.util.concurrent.Striped;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertNull;
public class LSMTrieLoadTest {
private static Path buildDirectory;
@BeforeClass
public static void beforeClass() {
buildDirectory = Paths.get(System.getProperty("buildDirectory", "target")).resolve("LSMTrieTest");
}
@Before
public void beforeMethod() throws Exception {
removeRecursively(buildDirectory);
}
@Test
public void mtTestOnlyFillAndUpdate() throws Exception {
OLSMTrie lsmTrie = new OLSMTrie("mtTestOnlyFillAndUpdate", buildDirectory);
lsmTrie.load();
final ExecutorService executorService = Executors.newCachedThreadPool();
final List<Future<Void>> futures = new ArrayList<>();
final ConcurrentSkipListMap<ByteHolder, ByteHolder> data = new ConcurrentSkipListMap<>();
final Striped<Lock> striped = Striped.lazyWeakLock(1024);
final AtomicBoolean stop = new AtomicBoolean();
final AtomicInteger sizeCounter = new AtomicInteger();
System.out.println("Start data handling threads");
for (int i = 0; i < 8; i++) {
futures.add(executorService.submit(new Modifier(500_000, 20_000_000, sizeCounter, data, striped, lsmTrie, stop)));
}
int sec = 10 * 60 * 60;
System.out.printf("Wait during %d second\n", sec);
Thread.sleep(sec * 1000);
stop.set(true);
System.out.println("Wait for data handling threads to stop");
for (Future<Void> future : futures) {
future.get();
}
System.out.printf("%d items were added, assert table\n", data.size());
for (int i = 0; i < 5; i++) {
System.out.printf("%d assert \n", i);
assertTable(data, Collections.emptySet(), lsmTrie);
}
System.out.println("Close table");
lsmTrie.close();
System.out.println("Load table");
lsmTrie = new OLSMTrie("mtTestOnlyFillAndUpdate", buildDirectory);
lsmTrie.load();
System.out.println("Assert table");
assertTable(data, Collections.emptySet(), lsmTrie);
lsmTrie.delete();
}
private void assertTable(Map<ByteHolder, ByteHolder> existingValues, Set<ByteHolder> absentValues, OLSMTrie table) {
for (Map.Entry<ByteHolder, ByteHolder> entry : existingValues.entrySet()) {
assertArrayEquals(entry.getValue().bytes, table.get(entry.getKey().bytes));
}
for (ByteHolder key : absentValues) {
assertNull(table.get(key.bytes));
}
}
private void removeRecursively(Path path) throws IOException {
if (Files.exists(path)) {
Files.list(path).forEach(p -> {
if (Files.isDirectory(p)) {
try {
removeRecursively(p);
} catch (IOException e) {
throw new IllegalStateException("Can not delete file", e);
}
} else {
try {
Files.delete(p);
} catch (IOException e) {
throw new IllegalStateException("Can not delete file", e);
}
}
});
}
}
private static class ByteHolder implements Comparable<ByteHolder> {
private final byte[] bytes;
private ByteHolder(byte[] bytes) {
this.bytes = bytes;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
ByteHolder that = (ByteHolder) o;
return Arrays.equals(bytes, that.bytes);
}
@Override
public int hashCode() {
return Arrays.hashCode(bytes);
}
@SuppressWarnings("NullableProblems")
@Override
public int compareTo(ByteHolder other) {
if (other.bytes.length == bytes.length) {
for (int i = 0; i < bytes.length; i++) {
final int cmp = Byte.compare(bytes[i], other.bytes[i]);
if (cmp != 0) {
return cmp;
}
}
} else if (bytes.length > other.bytes.length) {
return 1;
} else {
return -1;
}
return 0;
}
}
private static final class Modifier implements Callable<Void> {
private final int minSize;
private final int sizeLimit;
private final ConcurrentSkipListMap<ByteHolder, ByteHolder> data;
private final Striped<Lock> striped;
private final OLSMTrie lsmTrie;
private final ThreadLocalRandom random = ThreadLocalRandom.current();
private final AtomicBoolean stop;
private final AtomicInteger sizeCounter;
private Modifier(int minSize, int sizeLimit, AtomicInteger sizeCounter, ConcurrentSkipListMap<ByteHolder, ByteHolder> data,
Striped<Lock> striped, OLSMTrie lsmTrie, AtomicBoolean stop) {
this.minSize = minSize;
this.sizeLimit = sizeLimit;
this.data = data;
this.striped = striped;
this.lsmTrie = lsmTrie;
this.stop = stop;
this.sizeCounter = sizeCounter;
}
@Override
public Void call() {
try {
boolean sizeLimitReached = false;
long add = 0;
long read = 0;
long update = 0;
long ops = 0;
long start = System.nanoTime();
long end;
while (!stop.get()) {
if ((add + update + read) > 0 && (add + update + read) % 500_000 == 0) {
end = System.nanoTime();
long diff = (add + update + read) - ops;
long opsec = diff / ((end - start) / 1_000_000);
start = end;
ops += diff;
System.out.printf("Thread %d, %,d operations were performed (%,d reads, %,d updates, %,d additions), db size is %,d ,"
+ " speed is %,d op/ms\n", Thread.currentThread().getId(), (add + +update + read), read, update, add,
sizeCounter.get(), opsec);
}
if (!sizeLimitReached) {
final int size = sizeCounter.get();
sizeLimitReached = size >= sizeLimit;
if (sizeLimitReached) {
System.out.printf("Thread %d: size limit %d is reached\n", Thread.currentThread().getId(), size);
}
if (size < minSize) {
add();
add++;
continue;
}
}
final double operation = random.nextDouble();
if (!sizeLimitReached) {
if (operation < 0.3) {
read();
read++;
} else if (operation < 0.6) {
add();
add++;
} else {
update();
update++;
}
} else {
if (operation < 0.5) {
update();
update++;
} else {
read();
read++;
}
}
}
} catch (Exception | Error e) {
e.printStackTrace();
throw e;
}
return null;
}
private void read() {
ByteHolder existingKey = null;
while (!stop.get()) {
final ByteHolder key = new ByteHolder(generateKey(random));
existingKey = data.ceilingKey(key);
if (existingKey == null) {
existingKey = data.floorKey(key);
}
if (existingKey != null) {
break;
}
}
if (existingKey == null) {
return;
}
final Lock lock = striped.get(existingKey);
lock.lock();
try {
final ByteHolder value = data.get(existingKey);
Assert.assertNotNull(value);
final byte[] lsmValue = lsmTrie.get(existingKey.bytes);
Assert.assertNotNull(lsmValue);
Assert.assertEquals(value, new ByteHolder(lsmValue));
} finally {
lock.unlock();
}
}
private void add() {
final byte[] key = generateKey(random);
final byte[] value = generateValue(random);
final ByteHolder holderKey = new ByteHolder(key);
final Lock lock = striped.get(holderKey);
lock.lock();
try {
ByteHolder oldValue = data.put(holderKey, new ByteHolder(value));
lsmTrie.put(key, value);
if (oldValue == null) {
sizeCounter.getAndIncrement();
}
} finally {
lock.unlock();
}
}
private void update() {
ByteHolder existingKey = null;
while (!stop.get()) {
final ByteHolder key = new ByteHolder(generateKey(random));
existingKey = data.ceilingKey(key);
if (existingKey == null) {
existingKey = data.floorKey(key);
}
if (existingKey != null) {
break;
}
}
if (existingKey == null) {
return;
}
final Lock lock = striped.get(existingKey);
lock.lock();
try {
final byte[] value = generateValue(random);
final ByteHolder valueHolder = new ByteHolder(value);
data.put(existingKey, valueHolder);
lsmTrie.put(existingKey.bytes, value);
} finally {
lock.unlock();
}
}
}
private static byte[] generateValue(Random random) {
final int valueSize = random.nextInt(30) + 15;
final byte[] value = new byte[valueSize];
random.nextBytes(value);
return value;
}
private static byte[] generateKey(Random random) {
final int keySize = random.nextInt(17) + 8;
final byte[] key = new byte[keySize];
random.nextBytes(key);
return key;
}
}
| true |
6634fbbb52a145650c610490068e96f2c2bd974c | Java | gildasilvestrelopez09/tapukun-rest-api | /GetItProject/src/main/java/comgetit/questionary/QuestionaryRepository.java | UTF-8 | 381 | 1.742188 | 2 | [] | no_license | package comgetit.questionary;
import comgetit.workarea.WorkArea;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface QuestionaryRepository extends JpaRepository<Questionary, Long> {
Optional<Questionary> findByAccessCode(String code);
}
| true |
b18b0a2c5c863858c3549552c631402bfb5dc010 | Java | hamzajg/ProductsQuickTest | /src/Product/Product.WebApi/src/main/java/com/hamzajg/quickstart/product/webapi/endpoints/product/category/delete/DeleteProductCategoryEndpoint.java | UTF-8 | 885 | 2.171875 | 2 | [
"MIT"
] | permissive | package com.hamzajg.quickstart.product.webapi.endpoints.product.category.delete;
import com.hamzajg.quickstart.product.webapi.endpoints.product.category.ProductCategoryServicesFacade;
import javax.inject.Inject;
import javax.ws.rs.DELETE;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("/api/v1/product-categories")
public class DeleteProductCategoryEndpoint {
@Inject
ProductCategoryServicesFacade productCategoryServicesFacade;
@DELETE
@Path("/{productCategoryId}/delete")
@Produces(MediaType.APPLICATION_JSON)
public DeleteProductCategoryResponse delete(@PathParam("productCategoryId") String productCategoryId) {
var result = productCategoryServicesFacade.deleteProductCategory(productCategoryId);
return new DeleteProductCategoryResponse(result);
}
}
| true |
f848830fb359121f88843a21ed269c6b95e210d4 | Java | Owhab/Java-OOP-Simple-Projects | /TestReturningValue.java | UTF-8 | 337 | 3.546875 | 4 | [] | no_license |
class ReturnValue{
int ReturnValueTest(int value){
return value * value;
}
}
public class TestReturningValue{
public static void main(String [] args)
{
ReturnValue number1 = new ReturnValue();
System.out.println("Square of 56: "+number1.ReturnValueTest(56));
}
} | true |
26f9e05088a4b0cea803286451e6857329388c2f | Java | ChangjiangDong/Berkeley-cs61b | /discussion/Graph.java | UTF-8 | 181 | 2.390625 | 2 | [] | no_license | import java.util.Set;
public interface Graph{
void addEdge(int u, int v);
int V();
int E();
boolean connected(int u, int v);
Set<Integer> adj(int u);
Set<Edge> getEdges();
} | true |
115a7e9e7e0d02d382e31b40477b04165bab3e45 | Java | J0703/LYP-newCRM | /src/com/lanou/hrd/dao/impl/DepartmentDaoImpl.java | UTF-8 | 892 | 2.15625 | 2 | [] | no_license | package com.lanou.hrd.dao.impl;
import com.lanou.hrd.dao.DepartmentDao;
import com.lanou.hrd.domain.Crm_department;
/**
* Created by dllo on 17/10/25.
*/
public class DepartmentDaoImpl extends BaseDaoImpl<Crm_department> implements DepartmentDao {
// /**
// * 添加部门
// * @param crm_department 部门内容
// */
// public void add(Crm_department crm_department){
//
// getHibernateTemplate().save(crm_department);
//
// }
// public List<Crm_department> findAll(String hql){
//
// System.out.println("11");
//
// Session session = currentSession();
//
// Query query = session.createQuery("from Crm_department");
//
// List<Crm_department> list = query.list();
//
//// List<Crm_department> list = (List<Crm_department>) getHibernateTemplate().find("from Crm_department");
//
// return list;
//
// }
}
| true |
e5e1e4e8276c09e49afa4b4da8bc39bd8e2d3b22 | Java | Ibrahimhizeoui/wework | /src/iwork/dao/JobDao.java | UTF-8 | 4,618 | 2.234375 | 2 | [] | no_license | package iwork.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.mysql.jdbc.Statement;
import iwork.beans.Job;
public class JobDao implements Dao<Job> {
Connection connect =Db_Connect.getInstance();
@Override
public Job create(Job obj) {
String query="INSERT INTO `jobs` (`id`, `title`, `type`, `description`, `budget`, `state`, `duration`, `user_id`, `created_at`, `updated_at`)"
+ " VALUES (NULL, ?, ?,?, ?, ?, ?, ?, ?,?)";
try {
PreparedStatement prepdStmt = connect.prepareStatement(query);
prepdStmt.setString(1, obj.getTitle());
prepdStmt.setString(2, obj.getType());
prepdStmt.setString(3, obj.getDescription());
prepdStmt.setDouble(4, obj.getBudjet());
prepdStmt.setBoolean(5, obj.isState());
prepdStmt.setString(6, obj.getDuration());
prepdStmt.setInt(7, 1);
prepdStmt.setTimestamp(8, obj.getCreated_at());
prepdStmt.setTimestamp(9, obj.getUpdated_at());
prepdStmt.execute();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return obj;
}
@Override
public Job update(Job obj) {
// TODO Auto-generated method stubSt
String query="UPDATE `jobs` SET "
+ "`title` = ?, "
+ "`type` = ?, "
+ "`description` = ?, "
+ "`budget` = ?, "
+ "`state` = ?, "
+ "`duration` = ?, "
+ "`updated_at` = ? "
+ "WHERE `jobs`.`id` = ?";
try {
PreparedStatement prepdStmt = connect.prepareStatement(query);
prepdStmt.setString(1, obj.getTitle());
obj.setTitle(obj.getTitle());
prepdStmt.setString(2, obj.getType());
obj.setType(obj.getType());
prepdStmt.setString(3, obj.getDescription());
obj.setDescription( obj.getDescription());
prepdStmt.setDouble(4, obj.getBudjet());
obj.setBudjet( obj.getBudjet());
prepdStmt.setBoolean(5, obj.isState());
obj.setState(obj.isState());
prepdStmt.setString(6, obj.getDuration());
obj.setDuration(obj.getDuration());
prepdStmt.setTimestamp(7, obj.getUpdated_at());
obj.setUpdated_at( obj.getUpdated_at());
prepdStmt.setInt(8, obj.getId());
prepdStmt.execute();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return obj;
}
@Override
public List<Job> list() {
List<Job> list=new ArrayList();
String query = "SELECT * FROM `jobs`";
try {
Statement stmt=(Statement) connect.createStatement();
ResultSet rs = stmt.executeQuery(query);
while(rs.next()){
Job s =new Job();
s.setId(rs.getInt("id"));
s.setTitle(rs.getString("title"));
s.setType(rs.getString("type"));
s.setDescription(rs.getString("description"));
s.setBudjet(rs.getDouble("budget"));
s.setState(rs.getBoolean("state"));
s.setDuration(rs.getString("duration"));
s.setId_user_client(rs.getInt("user_id"));
s.setCreated_at(rs.getTimestamp("created_at"));
s.setUpdated_at(rs.getTimestamp("updated_at"));
System.out.println(s.toString());
list.add(s);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
@Override
public Job find(int id) {
Job s =new Job();
String query ="SELECT * FROM `jobs` WHERE `id`="+id;
try {
Statement stmt=(Statement) connect.createStatement();
ResultSet rs = stmt.executeQuery(query);
while(rs.next()){
s.setId(rs.getInt("id"));
s.setTitle(rs.getString("title"));
s.setType(rs.getString("type"));
s.setDescription(rs.getString("description"));
s.setBudjet(rs.getDouble("budget"));
s.setState(rs.getBoolean("state"));
s.setDuration(rs.getString("duration"));
s.setId_user_client(rs.getInt("user_id"));
s.setCreated_at(rs.getTimestamp("created_at"));
s.setUpdated_at(rs.getTimestamp("updated_at"));
System.out.println(s.toString());
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return s;
}
@Override
public boolean delete(int id) {
String query="DELETE FROM `jobs` WHERE `id`="+id;
try {
Statement stmt = (Statement) connect.createStatement();
stmt.executeUpdate(query);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
return true;
}
}
| true |
2f3472e9964fa25b0dfd5a49372318f4f660c935 | Java | manjulakollipara/manjula239 | /YelpMiner/src/com/sjsu/cmpe239/src/JSONReviewConverter.java | UTF-8 | 2,587 | 2.578125 | 3 | [] | no_license | package com.sjsu.cmpe239.src;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import com.sjsu.cmpe239.dao.ReviewDao;
import com.sjsu.cmpe239.dto.ReviewDto;
/**
* @author ManjulaKollipara
*
*/
public class JSONReviewConverter {
ReviewDto review = new ReviewDto();
public void convert(){
// TODO Auto-generated method stub
String jsonFilePath = "src/com/sjsu/cmpe239/data/review.json";
if( jsonFilePath == null || jsonFilePath.equals("")){
System.out.println("Input file is not reachable");
}
JSONParser parser = new JSONParser();
try {
Object objects = parser.parse(new FileReader(jsonFilePath));
JSONArray jsonObject = (JSONArray) objects;
Iterator<JSONObject> iterator = jsonObject.iterator();
while( iterator.hasNext()){
JSONObject json = iterator.next();
parseVotesArray((JSONObject) json.get("votes"));
String user_id = (String) json.get("user_id");
System.out.println(user_id);
review.setUser_id(user_id);
String review_id = (String) json.get("review_id");
System.out.println(review_id);
review.setReview_id(review_id);
String business_id = (String) json.get("business_id");
System.out.println(business_id);
review.setBusiness_id(business_id);
Long stars = (Long) json.get("stars");
System.out.println(stars.toString());
review.setStars(stars.toString());
String date = (String) json.get("date");
System.out.println(date);
review.setDate(date);
String reviewStr = (String) json.get("text");
System.out.println(reviewStr);
review.setReview(reviewStr);
ReviewDao rv = new ReviewDao();
rv.loadReview(review);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
public void parseVotesArray(JSONObject votesObj){
Long cool = (Long) votesObj.get("cool");
System.out.println(cool.toString());
review.setCool(cool.toString());
Long funny = (Long) votesObj.get("funny");
System.out.println(funny);
review.setFunny(funny.toString());
Long useful =(Long) votesObj.get("useful");
System.out.println(useful.toString());
review.setUseful(useful.toString());
}
}
| true |
460fbc0a45d4102b3f7c210c304100221c4ac740 | Java | bleachisback/LogiBlocks | /src/plugin/bleachisback/LogiBlocks/Listeners/LogiBlocksCraftListener.java | UTF-8 | 589 | 2.28125 | 2 | [] | no_license | package plugin.bleachisback.LogiBlocks.Listeners;
import org.bukkit.Material;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.CraftItemEvent;
import plugin.bleachisback.LogiBlocks.LogiBlocksMain;
public class LogiBlocksCraftListener implements Listener
{
public LogiBlocksCraftListener(LogiBlocksMain plugin)
{
}
@EventHandler
public void onPlayerCraftItem(CraftItemEvent e)
{
if(e.getRecipe().getResult().getType()==Material.COMMAND&&!e.getWhoClicked().hasPermission("c.craft"))
{
e.setCancelled(true);
}
}
}
| true |
497b1272a3c3ebd3b6e2266dd5c75814b510bbec | Java | brthao/lif13 | /lif13/src/View/GameView.java | UTF-8 | 23,347 | 2.34375 | 2 | [] | no_license | /*
* 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 View;
import Controller.CardController;
import Controller.GameController;
import Controller.MouseAction;
import Model.Card;
import Model.PartieDeDefJam;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;
import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
/**
*
* @author p1508674
*/
public class GameView extends javax.swing.JFrame implements Observer{
private ArrayList<JPanel> listPanel = new ArrayList<>();
private JPanel tabJPanel[][];
private PartieDeDefJam game ;
private GameController gc;
private JPanel gridContainer;
/**
* Creates new form GameView
*/
/**
* Creates new form GameView
* @return
*/
public JPanel[][] getTabPanels(){
return this.tabJPanel;
}
public ArrayList<JPanel> getListPanel() {
return listPanel;
}
public GameView(){
}
public GameView(GameController gc) {
this.gc=gc;
tabJPanel = new JPanel[6][4];
initComponents();
jPanel1.setLayout(new BorderLayout());
nextPhase.addActionListener((ActionEvent e) -> {
game.nextPhase();
});
GridLayout gl = new GridLayout(6,4);
gridContainer = new JPanel();
gridContainer.setVisible(true);
gridContainer.setLayout(gl);
int j=0;
int x=0;
for(int i = 0 ; i < 24 ; i++){
JPanel tmp = new JPanel();
tmp.setBorder(BorderFactory.createLineBorder(Color.black));
tmp.setLayout(new BorderLayout());
listPanel.add(tmp);
tabJPanel[x][j]=tmp;
if(j==3){
j=0;
x++;
}
else
j++;
}
for(JPanel jp : listPanel){
gridContainer.add(jp);
}
for (int i= 0 ; i<6 ; i++){
for (int z = 0 ; z<4 ; z++){
JLabel jl = new JLabel();
jl.setText(i+"-"+z);
//tabJPanel[i][z].add(jl);
}
}
for (int i =0 ; i<4; i++){
CardDisplay cd1 = gc.getMc().getVisuCard1().get(i);
tabJPanel[5][i].add(cd1);
cd1.setXpos(5);
cd1.setYpos(i);
cd1.getCard().setYDépart(cd1.getYpos());
cd1.getCard().setY(cd1.getYpos());
cd1.getCard().setX(5);
CardDisplay cd2 = gc.getMc().getVisuCard2().get(i);
tabJPanel[0][i].add(cd2);
cd2.setXpos(0);
cd2.setYpos(i);
cd2.getCard().setYDépart(cd2.getYpos());
cd2.getCard().setY(cd2.getYpos());
cd2.getCard().setX(0);
for(MouseListener m : cd2.getMouseListeners()){
if(m instanceof MouseAction){
continue;
}
cd2.removeMouseListener(m);
}
}
jPanel1.add(gridContainer,BorderLayout.CENTER);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
nbTour = new javax.swing.JLabel();
phase = new javax.swing.JLabel();
nextPhase = new javax.swing.JButton();
joueurLabel = new javax.swing.JLabel();
joueurAct = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
pdv = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
nbRessources = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setPreferredSize(new java.awt.Dimension(1100, 850));
jPanel1.setMinimumSize(new java.awt.Dimension(200, 200));
jPanel1.setPreferredSize(new java.awt.Dimension(600, 600));
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 750, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 714, Short.MAX_VALUE)
);
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel1.setText("TOUR :");
nbTour.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
nbTour.setText("jLabel2");
phase.setFont(new java.awt.Font("Calibri", 1, 24)); // NOI18N
phase.setText("Phase de défense");
nextPhase.setFont(new java.awt.Font("Calibri", 1, 18)); // NOI18N
nextPhase.setText("Phase suivante");
joueurLabel.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
joueurLabel.setText("Joueur Actuel :");
joueurAct.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
joueurAct.setForeground(new java.awt.Color(0, 0, 204));
joueurAct.setText("Joueur 1");
jLabel2.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel2.setText("Points de vie :");
pdv.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
pdv.setForeground(new java.awt.Color(255, 153, 153));
pdv.setText("pdv");
jLabel3.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel3.setText("Nombre de ressources");
nbRessources.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
nbRessources.setForeground(new java.awt.Color(153, 153, 255));
nbRessources.setText("jLabel4");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 750, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(144, 144, 144)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(nbTour))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 43, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(joueurLabel)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(phase, javax.swing.GroupLayout.DEFAULT_SIZE, 196, Short.MAX_VALUE)
.addComponent(nextPhase, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(joueurAct)
.addComponent(jLabel2)
.addComponent(pdv)
.addComponent(jLabel3)
.addComponent(nbRessources))
.addContainerGap())))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(47, 47, 47)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 714, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(55, 55, 55)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(nbTour)
.addGap(271, 271, 271)
.addComponent(phase, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(nextPhase, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(30, 30, 30)
.addComponent(joueurLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(joueurAct)
.addGap(18, 18, 18)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(pdv)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(nbRessources)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(GameView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(GameView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(GameView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GameView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(() -> {
new GameView().setVisible(true);
});
}
public JLabel getTour(){
return this.nbTour;
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JLabel joueurAct;
private javax.swing.JLabel joueurLabel;
private javax.swing.JLabel nbRessources;
private javax.swing.JLabel nbTour;
private javax.swing.JButton nextPhase;
private javax.swing.JLabel pdv;
private javax.swing.JLabel phase;
// End of variables declaration//GEN-END:variables
public void setGame(PartieDeDefJam game) {
this.game = game;
}
public PartieDeDefJam getGame() {
return game;
}
public JLabel getJoueurAct() {
return joueurAct;
}
public void setJoueurAct(JLabel joueurAct) {
this.joueurAct = joueurAct;
}
@Override
public void update(Observable o, Object arg) {
nbTour.setText(String.valueOf(game.getTour()));
updatePartie();
updatePhase();
updatePlayer();
if(game.getPhase()==0 && (String)arg=="Changement"){
reverseBoard();
}
updateAllCards();
}
public void updatePhase(){
switch(game.getPhase()){
case 0:
phase.setText("Phase de defense");
phase.setForeground(Color.black);
nextPhase.setText("Phase Suivante");
break;
case 1:
phase.setText("Phase d'invocation");
phase.setForeground(Color.green);
break;
case 2:
phase.setText("Phase d'attaque");
phase.setForeground(Color.red);
nextPhase.setText("Joueur suivant");
break;
}
}
public void updatePlayer(){
if(game.getActivePlayer()==game.getPlayers()[0]){
joueurAct.setText(game.getPlayers()[0].getNOM());
joueurAct.setForeground(Color.blue);
}
else{
joueurAct.setText(game.getPlayers()[1].getNOM());
joueurAct.setForeground(Color.red);
}
pdv.setText(String.valueOf(game.getActivePlayer().getPOINTS_DE_VIE()));
nbRessources.setText(String.valueOf(game.getActivePlayer().getNB_RESSOURCES()+"/"+game.getActivePlayer().getNB_RESSOURCES_MAX()));
}
public void reverseBoard(){
Card[][] tmp = new Card[6][4];
for(int i = 0 ; i < gc.getMc().getVisuCard1().size() ; i++){
CardDisplay current = gc.getMc().getVisuCard1().get(i);
if(current != null){
//gridContainer.getcompo
int xPos;
xPos = current.getXpos();
switch(xPos){
case 0 :
tabJPanel[5][current.getYpos()].add(current);
current.setXpos(5);
current.getCard().setX(5);
current.addMouseListener(new CardController(current.getCard()));
//game.getBoard().getCardTable()[5]
tmp[5][current.getYpos()]=current.getCard();
break;
case 1 :
tabJPanel[4][current.getYpos()].add(current);
current.setXpos(4);
current.getCard().setX(4);
current.addMouseListener(new CardController(current.getCard()));
tmp[4][current.getYpos()]=current.getCard();
break;
case 2 :
tabJPanel[3][current.getYpos()].add(current);
current.setXpos(3);
current.getCard().setX(3);
current.addMouseListener(new CardController(current.getCard()));
tmp[3][current.getYpos()]=current.getCard();
break;
case 3 :
tabJPanel[2][current.getYpos()].add(current);
current.setXpos(2);
current.getCard().setX(2);
for(MouseListener m : current.getMouseListeners()){
if(m instanceof MouseAction){
continue;
}
current.removeMouseListener(m);
}
tmp[2][current.getYpos()]=current.getCard();
break;
case 4 :
tabJPanel[1][current.getYpos()].add(current);
current.setXpos(1);
current.getCard().setX(1);
for(MouseListener m : current.getMouseListeners()){
if(m instanceof MouseAction){
continue;
}
current.removeMouseListener(m);
}
tmp[1][current.getYpos()]=current.getCard();
break;
case 5 :
tabJPanel[0][current.getYpos()].add(current);
current.setXpos(0);
current.getCard().setX(0);
for(MouseListener m : current.getMouseListeners()){
if(m instanceof MouseAction){
continue;
}
current.removeMouseListener(m);
}
tmp[0][current.getYpos()]=current.getCard();
break;
}
revalidate();
repaint();
}
}
for(int i = 0 ; i < gc.getMc().getVisuCard2().size() ; i++){
CardDisplay current = gc.getMc().getVisuCard2().get(i);
if(current != null){
//gridContainer.getcompo
int xPos;
xPos = current.getXpos();
switch(xPos){
case 0 :
tabJPanel[5][current.getYpos()].add(current);
current.setXpos(5);
current.getCard().setX(5);
current.addMouseListener(new CardController(current.getCard()));
tmp[5][current.getYpos()]=current.getCard();
break;
case 1 :
tabJPanel[4][current.getYpos()].add(current);
current.setXpos(4);
current.getCard().setX(4);
current.addMouseListener(new CardController(current.getCard()));
tmp[4][current.getYpos()]=current.getCard();
break;
case 2 :
tabJPanel[3][current.getYpos()].add(current);
current.setXpos(3);
current.getCard().setX(3);
current.addMouseListener(new CardController(current.getCard()));
tmp[3][current.getYpos()]=current.getCard();
break;
case 3 :
tabJPanel[2][current.getYpos()].add(current);
current.setXpos(2);
current.getCard().setX(2);
for(MouseListener m : current.getMouseListeners()){
if(m instanceof MouseAction){
continue;
}
current.removeMouseListener(m);
}
tmp[2][current.getYpos()]=current.getCard();
break;
case 4 :
tabJPanel[1][current.getYpos()].add(current);
current.setXpos(1);
current.getCard().setX(1);
for(MouseListener m : current.getMouseListeners()){
if(m instanceof MouseAction){
continue;
}
current.removeMouseListener(m);
}
tmp[1][current.getYpos()]=current.getCard();
break;
case 5 :
tabJPanel[0][current.getYpos()].add(current);
current.setXpos(0);
current.getCard().setX(0);
for(MouseListener m : current.getMouseListeners()){
if(m instanceof MouseAction){
continue;
}
current.removeMouseListener(m);
}
tmp[0][current.getYpos()]=current.getCard();
break;
}
revalidate();
repaint();
}
}
game.getBoard().setCardTable(tmp);
}
public void updateAllCards(){
for (int i=0; i<6;i++){
for (int j=0; j<4;j++){
if(tabJPanel[i][j].getComponentCount()== 0){
continue;
}
if(tabJPanel[i][j].getComponent(0) instanceof CardDisplay ) {
CardDisplay tmp = (CardDisplay)tabJPanel[i][j].getComponent(0);
if (tmp.getCard().isDestroyed()){
tabJPanel[i][j].remove(tmp);
//tabJPanel[i][j]=new JPanel();
revalidate();
repaint();
continue;
}
tmp.setXpos(tmp.getCard().getX());
tmp.setYpos(tmp.getCard().getY());
tabJPanel[tmp.getXpos()][tmp.getYpos()].add(tmp);
revalidate();
repaint();
}
}
}
}
public void updatePartie(){
if(game.isPartieTerminee()){
JOptionPane.showMessageDialog(this, "Fin de partie ! Joueur gagnant est " + getOpponent());
System.exit(0);
}
}
public String getOpponent(){
if(game.getActivePlayer()==game.getPlayers()[0])
return game.getPlayers()[1].getNOM();
else
return game.getPlayers()[0].getNOM();
}
public JLabel getNbRessources() {
return nbRessources;
}
public void setNbRessources(JLabel nbRessources) {
this.nbRessources = nbRessources;
}
public JLabel getPdv() {
return pdv;
}
public void setPdv(JLabel pdv) {
this.pdv = pdv;
}
}
| true |
afa69c98821a657da7cc039438bc7666f36c9df7 | Java | moutainhigh/btr-zd | /btr-zd-model/src/main/java/com/baturu/zd/request/business/UserQueryRequest.java | UTF-8 | 412 | 1.578125 | 2 | [] | no_license | package com.baturu.zd.request.business;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* created by ketao by 2019/03/22
**/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class UserQueryRequest extends BaseRequest{
/**服务网点id*/
private Integer servicePointId;
/**员工名称*/
private String name;
}
| true |
cd50ca04af6d15f3c1c9601530af7daf393f49d2 | Java | TianciGG/Milestone | /src/main/java/com/milestone/service/impl/MainPageServiceImpl.java | UTF-8 | 6,880 | 2.359375 | 2 | [] | no_license | package com.milestone.service.impl;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.milestone.db.dao.ObjectiveDAO;
import com.milestone.db.dao.UserDAO;
import com.milestone.db.entity.Objective;
import com.milestone.db.entity.User;
import com.milestone.service.MainPageService;
@Service
public class MainPageServiceImpl implements MainPageService {
@Resource
private ObjectiveDAO objectiveDao;
@Resource
private UserDAO userDao;
private List<Objective> validateOvertime(List<Objective> listObjective) {
Date nowDate = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
List<Objective> newListObjective = new ArrayList<Objective>();
for (Objective objective : listObjective) {
String finishTimeString = objective.getObjectiveFinishdatetime();
Date finishTime = null;
try {
finishTime = dateFormat.parse(finishTimeString);
} catch (ParseException e) {
e.printStackTrace();
}
if (nowDate.getTime() >= finishTime.getTime()) {
newListObjective.add(objective);
} else {
continue;
}
}
return newListObjective;
}
private List<Objective> validateNotOutTime(List<Objective> listObjective) {
Date nowDate = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
List<Objective> newListObjective = new ArrayList<Objective>();
for (Objective objective : listObjective) {
String finishTimeString = objective.getObjectiveFinishdatetime();
Date finishTime = null;
try {
finishTime = dateFormat.parse(finishTimeString);
} catch (ParseException e) {
e.printStackTrace();
}
if (nowDate.getTime() < finishTime.getTime()) {
newListObjective.add(objective);
} else {
continue;
}
}
return newListObjective;
}
private List<Objective> countDown(List<Objective> listObjective) {
Date nowDate = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
Date finishTime = null;
List<Objective> newListObjective = new ArrayList<Objective>();
for (Objective objective : listObjective) {
String finishTimeString = objective.getObjectiveFinishdatetime();
try {
finishTime = dateFormat.parse(finishTimeString);
} catch (ParseException e) {
e.printStackTrace();
}
long diff = finishTime.getTime() - nowDate.getTime();// 这样得到的差值是微秒级别
long days = diff / (1000 * 60 * 60 * 24);
long hours = (diff - days * (1000 * 60 * 60 * 24))
/ (1000 * 60 * 60);
long minutes = (diff - days * (1000 * 60 * 60 * 24) - hours
* (1000 * 60 * 60))
/ (1000 * 60);
// System.out.println("" + days + "天" + hours + "小时" + minutes +
// "分");
String daysString = Long.toString(days);
String hoursString = Long.toString(hours);
String minutesString = Long.toString(minutes);
objective.setDays(daysString);
objective.setHours(hoursString);
objective.setMinutes(minutesString);
newListObjective.add(objective);
}
return newListObjective;
}
@Override
public List<Objective> searchMyTarget(String userId, String mark) {
if ("1".equals(mark)) {
return countDown(objectiveDao.searchMyTargetByUid(userId));
} else if ("2".equals(mark)) {
List<Objective> listObjective = countDown(objectiveDao
.searchMyTargetByUid(userId));
return validateOvertime(listObjective);
} else if ("3".equals(mark)) {
List<Objective> listObjective = countDown(objectiveDao
.selectEmphasizeInfoByUid(userId));
return validateNotOutTime(listObjective);
} else if ("4".equals(mark)) {
List<Objective> listObjective = countDown(objectiveDao
.selectStandardInfoByUid(userId));
return validateNotOutTime(listObjective);
} else {
return null;
}
}
@Override
public User selectPersonalInfo(String userId) {
return userDao.selectByPrimaryKey(userId);
}
@Override
public boolean savePersonalInfo(User user) {
return userDao.updateByPrimaryKey(user) > 0 ? true : false;
}
@Override
public boolean createTarget(Objective objective) {
objective.setObjectiveStatus("0");
String finishTimeString = null;
if (objective.getObjectiveFinishdatetime() != null
&& objective.getObjectiveFinishdatetime().length() == 16) {
finishTimeString = objective.getObjectiveFinishdatetime() + ":00";
}
objective.setObjectiveFinishdatetime(finishTimeString);
Date nowDate = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
// Date finishTime = null;
try {
String emphasize = objective.getObjectiveEmphasize();
if (emphasize == null || "".equals(emphasize)) {
objective.setObjectiveEmphasize("0");
}
// finishTime = dateFormat.parse(finishTimeString);
} catch (NullPointerException e) {
objective.setObjectiveEmphasize("0");
}
/*
* long diff = finishTime.getTime() - nowDate.getTime();// 这样得到的差值是微秒级别
* long days = diff / (1000 * 60 * 60 * 24);
*
* long hours = (diff - days * (1000 * 60 * 60 * 24)) / (1000 * 60 *
* 60); long minutes = (diff - days * (1000 * 60 * 60 * 24) - hours
* (1000 * 60 * 60)) / (1000 * 60); System.out.println("" + days + "天" +
* hours + "小时" + minutes + "分");
*/
String nowDateString = dateFormat.format(nowDate);
objective.setObjectiveBegindatetime(nowDateString);
return objectiveDao.insertSelective(objective) > 0 ? true : false;
}
@Override
public boolean updateObjectiveTableInfo(Objective objective) {
if (objective.getObjectiveFinishdatetime() != null
&& objective.getObjectiveFinishdatetime().length() == 16) {
// System.out.println(objective.getObjectiveFinishdatetime().length());
String finishTimeString = objective.getObjectiveFinishdatetime()
+ ":00";
objective.setObjectiveFinishdatetime(finishTimeString);
}
if ("1".equals(objective.getObjectiveStatus())) {
Date nowDate = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
String nowDateString = dateFormat.format(nowDate);
objective.setObjectiveEnddatetime(nowDateString);
}
return objectiveDao.updateByPrimaryKeySelective(objective) > 0 ? true
: false;
}
@Override
public boolean deleteObjectiveTableInfo(Objective objective) {
return objectiveDao.deleteByPrimaryKey(objective.getObjectiveId()) > 0 ? true
: false;
}
@Override
public Objective selectObjectiveInfoById(String objectiveId) {
return objectiveDao.selectByPrimaryKey(objectiveId);
}
@Override
public List<Objective> searchMyMilestoneInfo(String userId,
String objectiveTitle) {
return objectiveDao.searchMyMilestoneByUidAndTitleContent(userId,
objectiveTitle);
}
}
| true |
050c7d6da9993c6d9723ffdc4aca62288e0d15c9 | Java | hwanggit/Connect-4 | /connect4/connect4.java | UTF-8 | 10,649 | 3.15625 | 3 | [] | no_license | package application;
import javafx.application.*;
import javafx.scene.control.*;
import javafx.scene.*;
import javafx.scene.paint.*;
import javafx.scene.shape.*;
import javafx.scene.layout.*;
import javafx.stage.*;
import javafx.event.*;
import javafx.scene.input.*;
import javafx.scene.text.*;
import javafx.geometry.*;
import java.util.*;
import java.io.*;
public class connect4 extends Application
{
@Override
public void start(Stage primaryStage)
{
this.gameboard = new connect4_functions();
// Create the pane that will hold all of the visual objects
pane = new GridPane();
pane.setPadding(new Insets(11.5, 12.5, 13.5, 14.5));
pane.setStyle("-fx-background-color: rgb(0, 0, 0)");
// Set the spacing between the Tiles
pane.setHgap(15);
pane.setVgap(15);
Label title = new Label("Connect4");
title.setFont(Font.font("Times New Roman", FontWeight.BOLD, 20));
title.setTextFill(Color.WHITE);
pane.add(title,0,0);
//create a stackpane and an overlay pane for game over function
parent=new StackPane();
root= new GridPane();
root.setPadding(new Insets(11.5, 12.5, 13.5, 14.5));
// make overlay transparent initially(238,228,218,0.73)
root.setStyle("-fx-background-color: rgb(238, 228, 218,0.73)");
Text gameStart=new Text("Press N to start a new game (clear the board)\n\nHint: Use keyboard numbers to place pieces in column");
root.getChildren().add(gameStart);
root.setAlignment(Pos.CENTER);
//add StackPane to scene, and add scene to state, set stage title
Scene scene= new Scene(parent,850,750);
parent.getChildren().addAll(pane,root);
primaryStage.setTitle("Connect4");
primaryStage.setScene(scene);
primaryStage.show();
// set the initial state of the board
update();
// whenever a key is presed, access meKeyHandler class and implement EventHandler
scene.setOnKeyPressed(new myKeyHandler());
}
// Class Header: myKeyHandler class uses the interface EventHandler to help the Gui react to
// key preses. It also contains the handle method for key preses
private class myKeyHandler implements EventHandler<KeyEvent> {
//Handle method calls move methods and update methods, checks game over if up down left or
//right key is presed
//Parameter: The key presed
@Override
public void handle(KeyEvent e) {
if (gameboard.check_win_or_tie()&&e.getCode()!=KeyCode.N) {
return;
}
// if key pressed is available column, move respectively
if (e.getCode()==KeyCode.DIGIT1&&!gameboard.is_column_full(1)) {
root.setStyle("-fx-background-color: rgb(187, 173, 160,0)");
root.getChildren().clear();
gameboard.update_board(gameboard.board,1,turn);
turn=3-turn;
pane.getChildren().clear();
// check game over then change transparency of overlay pane
update();
if (gameboard.check_win_or_tie()) {
Text gameOver=new Text("Game Over! Press N to start a new game");
root.getChildren().add(gameOver);
root.setAlignment(Pos.CENTER);
root.setStyle("-fx-background-color: rgb(238,228,218,0.73)");
return;
}
}
else if (e.getCode()==KeyCode.DIGIT2&&!gameboard.is_column_full(2)) {
root.setStyle("-fx-background-color: rgb(187, 173, 160,0)");
root.getChildren().clear();
gameboard.update_board(gameboard.board,2,turn);
turn=3-turn;
pane.getChildren().clear();
// check game over then change transparency of overlay pane
update();
if (gameboard.check_win_or_tie()) {
Text gameOver=new Text("Game Over! Press N to start a new game");
root.getChildren().add(gameOver);
root.setAlignment(Pos.CENTER);
root.setStyle("-fx-background-color: rgb(238,228,218,0.73)");
return;
}
}
else if (e.getCode()==KeyCode.DIGIT3&&!gameboard.is_column_full(3)) {
root.setStyle("-fx-background-color: rgb(187, 173, 160,0)");
root.getChildren().clear();
gameboard.update_board(gameboard.board,3,turn);
turn=3-turn;
pane.getChildren().clear();
// check game over then change transparency of overlay pane
update();
if (gameboard.check_win_or_tie()) {
Text gameOver=new Text("Game Over! Press N to start a new game");
root.getChildren().add(gameOver);
root.setAlignment(Pos.CENTER);
root.setStyle("-fx-background-color: rgb(238,228,218,0.73)");
return;
}
}
else if (e.getCode()==KeyCode.DIGIT4&&!gameboard.is_column_full(4)) {
root.setStyle("-fx-background-color: rgb(187, 173, 160,0)");
root.getChildren().clear();
gameboard.update_board(gameboard.board,4,turn);
turn=3-turn;
pane.getChildren().clear();
// check game over then change transparency of overlay pane
update();
if (gameboard.check_win_or_tie()) {
Text gameOver=new Text("Game Over! Press N to start a new game");
root.getChildren().add(gameOver);
root.setAlignment(Pos.CENTER);
root.setStyle("-fx-background-color: rgb(238,228,218,0.73)");
return;
}
}
else if (e.getCode()==KeyCode.DIGIT5&&!gameboard.is_column_full(5)) {
root.setStyle("-fx-background-color: rgb(187, 173, 160,0)");
root.getChildren().clear();
gameboard.update_board(gameboard.board,5,turn);
turn=3-turn;
pane.getChildren().clear();
// check game over then change transparency of overlay pane
update();
if (gameboard.check_win_or_tie()) {
Text gameOver=new Text("Game Over! Press N to start a new game");
root.getChildren().add(gameOver);
root.setAlignment(Pos.CENTER);
root.setStyle("-fx-background-color: rgb(238,228,218,0.73)");
return;
}
}
else if (e.getCode()==KeyCode.DIGIT6&&!gameboard.is_column_full(6)) {
root.setStyle("-fx-background-color: rgb(187, 173, 160,0)");
root.getChildren().clear();
gameboard.update_board(gameboard.board,6,turn);
turn=3-turn;
pane.getChildren().clear();
// check game over then change transparency of overlay pane
update();
if (gameboard.check_win_or_tie()) {
Text gameOver=new Text("Game Over! Press N to start a new game");
root.getChildren().add(gameOver);
root.setAlignment(Pos.CENTER);
root.setStyle("-fx-background-color: rgb(238,228,218,0.73)");
return;
}
}
else if (e.getCode()==KeyCode.DIGIT7&&!gameboard.is_column_full(7)) {
root.setStyle("-fx-background-color: rgb(187, 173, 160,0)");
root.getChildren().clear();
gameboard.update_board(gameboard.board,7,turn);
turn=3-turn;
pane.getChildren().clear();
// check game over then change transparency of overlay pane
update();
if (gameboard.check_win_or_tie()) {
Text gameOver=new Text("Game Over! Press N to start a new game");
root.getChildren().add(gameOver);
root.setAlignment(Pos.CENTER);
root.setStyle("-fx-background-color: rgb(238,228,218,0.73)");
return;
}
}
else if (e.getCode()==KeyCode.N) {
root.getChildren().clear();
root.setStyle("-fx-background-color: rgb(187,173,160,0)");
clearTiles();
return;
}
else {
return;
}
}
}
// Update Method: updates the tile values of the game grid after each move
private void update() {
// store the board array
boardGrid=gameboard.board;
// update the Gui each time
Label title = new Label("Connect4");
title.setFont(Font.font("Times New Roman", FontWeight.BOLD, 20));
title.setTextFill(Color.WHITE);
pane.add(title,0,0);
// loop through the board array and cahnge the rectangles to their respective
// features based on the number in the array
for (int i=0; i<gameboard.height;i++) {
for (int j=0; j<gameboard.width;j++) {
if (boardGrid[i][j]==0) {
Circle thisTile = new Circle ();
thisTile.setRadius(50);
thisTile.setFill(Color.WHITE);
pane.add(thisTile,j,i+1);
}
else if (boardGrid[i][j]==2) {
makeTile(i,j,Color.YELLOW);
}
else if (boardGrid[i][j]==1) {
makeTile(i,j,Color.RED);
}
}
}
}
// Helper method to update rectangles, makeTile method sets rectangle features
// Parameters: sets position of circle, color of tile
private void makeTile(int x, int y, Color tileColor) {
// Create new circle
Circle thisTile = new Circle ();
thisTile.setRadius(50);
thisTile.setFill(tileColor);
pane.add(thisTile,y,x+1);
}
// helper method to restart board
private void clearTiles() {
for (int i = 0; i < gameboard.height; i++) {
for (int j = 0; j < gameboard.width; j++) {
boardGrid[i][j] = 0;
Circle thisTile = new Circle();
thisTile.setRadius(50);
thisTile.setFill(Color.WHITE);
pane.add(thisTile, j, i + 1);
}
}
}
}
| true |
96b83578d8183b3abc18d68ebd647b782c0f1a2d | Java | Radu-Sebastian/POO2019-30223 | /Students/Trufin Radu Sebastian/Assignements/Streams & Lambda/javastreams2/RemoveOddLength.java | UTF-8 | 482 | 3.609375 | 4 | [] | no_license | package javastreams2;
import java.util.*;
public class RemoveOddLength
{
public static void main(String[] args)
{
List<String> myList = new ArrayList<>();
myList.add("Oriented");
myList.add("Object");
myList.add("Programming");
myList.forEach(x -> System.out.println(x));
myList.removeIf(x -> x.length() % 2 == 1);
System.out.println(" \nOdd removed \n");
myList.forEach(x -> System.out.println(x));
}
} | true |
f6d794f8f202e2a8348a3c209f4515e966db68e4 | Java | peizihui/Cfunding | /app/src/main/java/com/jdyy/cfunding/fragment/Record/MovieRecordFragment.java | UTF-8 | 2,827 | 1.984375 | 2 | [] | no_license | package com.jdyy.cfunding.fragment.Record;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import com.jdyy.cfunding.R;
import com.jdyy.cfunding.fragment.BaseFragment;
import com.jdyy.cfunding.recyclerView.EasyRecyclerView;
import com.jdyy.cfunding.recyclerView.adapter.RecyclerArrayAdapter;
import com.jdyy.cfunding.recyclerView.decoration.SpaceDecoration;
import com.jdyy.cfunding.utils.Util;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* Created by Administrator on 2016/12/9 0009.
*/
public class MovieRecordFragment extends BaseFragment implements RecyclerArrayAdapter.OnLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {
@Bind(R.id.easyRecyclerView)
EasyRecyclerView recyclerView;
@Override
protected int getLayoutId() {
return R.layout.fragment_movierecord;
}
@Override
protected void loadData() {
onRefresh();
}
@Override
protected void initView(View view) {
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
SpaceDecoration itemDecoration = new SpaceDecoration((int) Util.dip2px(getContext(), 6));
itemDecoration.setPaddingEdgeSide(true);
itemDecoration.setPaddingStart(true);
itemDecoration.setPaddingHeaderFooter(false);
recyclerView.addItemDecoration(itemDecoration);
// recyclerView.setAdapterWithProgress(adapter = new ProductAdapter(getContext()) {
// @Override
// public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
// return new ProductViewHolder(parent);
// }
// });
// //加载数据
// adapter.setMore(R.layout.view_more, this);
//
// adapter.setNoMore(R.layout.view_nomore, new RecyclerArrayAdapter.OnNoMoreListener() {
// @Override
// public void onNoMoreShow() {
// adapter.resumeMore();
// }
//
// @Override
// public void onNoMoreClick() {
// adapter.resumeMore();
// }
// });
// adapter.setError(R.layout.view_error, new RecyclerArrayAdapter.OnErrorListener() {
// @Override
// public void onErrorShow() {
// adapter.resumeMore();
// }
//
// @Override
// public void onErrorClick() {
// adapter.resumeMore();
// }
// });
recyclerView.setRefreshListener(this);
}
private void initView() {
}
@Override
public void onDestroyView() {
super.onDestroyView();
ButterKnife.unbind(this);
}
@Override
public void onRefresh() {
}
@Override
public void onLoadMore() {
}
}
| true |
b1df0897c464bd228e96cdae8004e00061c4a750 | Java | non-trace/SignUpSystem | /src/cn/edu/tstc/dao/UserDao.java | UTF-8 | 3,164 | 2.34375 | 2 | [] | no_license | /**
*
*/
package cn.edu.tstc.dao;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Repository;
import cn.edu.tstc.common.dao.BaseDao;
import cn.edu.tstc.entity.User;
@Repository
public class UserDao extends BaseDao implements IUserDao {
@Override
public User findUserByUserCode(String user_code) throws ParseException {
StringBuffer sqlbBuffer = new StringBuffer();
sqlbBuffer.append("select * from t_user u where u.user_code ='").append(user_code).append("'");
List<Map<String, Object>> l = this.queryForList(sqlbBuffer.toString());
if (l!=null&&!l.isEmpty()) {
Map<String, Object> userMap = l.get(0);
User user = new User();
user.setUser_id(Integer.parseInt(userMap.get("user_id").toString()));
user.setAge(userMap.get("age")==null?0:Integer.parseInt(userMap.get("age").toString()));
user.setBirthday(userMap.get("birthday")!=null?new SimpleDateFormat("yyyy-MM-dd").parse(userMap.get("birthday").toString()):new Date());
user.setIdcard(userMap.get("idcard")==null?"":userMap.get("idcard").toString());
user.setMd5Password(userMap.get("user_password").toString());
user.setMobile(userMap.get("mobile")==null?"":userMap.get("mobile").toString());
user.setSex(userMap.get("sex")==null?"":userMap.get("sex").toString());
user.setTel(userMap.get("tel")==null?"":userMap.get("tel").toString());
user.setUser_code(userMap.get("user_code")==null?"":userMap.get("user_code").toString());
user.setUser_name(userMap.get("user_name")==null?"":userMap.get("user_name").toString());
user.setEmail(userMap.get("Email")==null?"":userMap.get("Email").toString());
return user;
}
return null;
}
@Override
public void insertUser(User user) {
StringBuffer sqlbBuffer = new StringBuffer();
sqlbBuffer.append(" insert into t_user ( user_name , user_code , user_password , sex , birthday , Email , idcard , mobile , age ) values ('")
.append(user.getUser_name()).append("','")
.append(user.getUser_code()).append("','")
.append(user.getPassword()).append("','")
.append(user.getSex()).append("','")
.append(new SimpleDateFormat("yyyy-MM-dd").format(user.getBirthday())).append("','")
.append(user.getEmail()).append("','")
.append(user.getIdcard()).append("','")
.append(user.getMobile()).append("','")
.append(user.getAge()).append("')");
this.execute(sqlbBuffer.toString());
}
/* (non-Javadoc)
* @see cn.edu.tstc.dao.IUserDao#updateUser(cn.edu.tstc.entity.User)
*/
@Override
public void updateUser(User user) {
StringBuffer sqlbBuffer = new StringBuffer();
sqlbBuffer.append("update t_user set ");
sqlbBuffer.append("user_code = '").append(user.getUser_code()).append("',");
if (user.getUser_name()!=null&&!"".equals(user.getUser_name())) {
sqlbBuffer.append("user_name = '").append(user.getUser_name()).append("',");
}
if (user.getUser_name()!=null&&!"".equals(user.getUser_name())) {
sqlbBuffer.append("user_name = '").append(user.getUser_name()).append("',");
}
}
}
| true |
8e928ed50b5a27c3a185086fd72c7b7c740bb3c1 | Java | venkatram64/jaasLogin | /src/main/java/com/venkat/jaas/login1/MyCallbackHandler.java | UTF-8 | 1,409 | 2.671875 | 3 | [] | no_license | package com.venkat.jaas.login1;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.security.auth.callback.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Created by venkatram.veerareddy on 8/31/2017.
*/
public class MyCallbackHandler implements CallbackHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(MyCallbackHandler.class);
@Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
for(Callback cb: callbacks){
if(cb instanceof NameCallback){
NameCallback ncb = (NameCallback)cb;
//Display prompt
System.out.println(ncb.getPrompt());
//Read password
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
ncb.setName(bufferedReader.readLine());
}
else if(cb instanceof PasswordCallback){
PasswordCallback pcb = (PasswordCallback)cb;
//Display prompt
System.out.println(pcb.getPrompt());
//Read password
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
pcb.setPassword(bufferedReader.readLine().toCharArray());
}
}
}
}
| true |
639d21e16219e6179df56995d149ba25b321f099 | Java | smalltide/agent | /src/main/java/com/daxiang/action/appium/SwitchContext.java | UTF-8 | 1,416 | 2.515625 | 3 | [
"MIT"
] | permissive | package com.daxiang.action.appium;
import com.daxiang.core.MobileDevice;
import io.appium.java_client.AppiumDriver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import java.util.Set;
/**
* Created by jiangyitao.
*/
@Slf4j
public class SwitchContext {
private AppiumDriver appiumDriver;
public SwitchContext(AppiumDriver appiumDriver) {
this.appiumDriver = appiumDriver;
}
public void excute(Object context) {
Assert.notNull(context, "context不能为空");
String _context = (String) context;
if (MobileDevice.NATIVE_CONTEXT.equals(_context)) {
// 切换到原生
appiumDriver.context(_context);
} else {
Set<String> contexts = appiumDriver.getContextHandles();
log.info("contexts: {}", contexts);
for (String ctx : contexts) {
// webview 目前先这样处理,如果有多个webview可能会切换错
if (!MobileDevice.NATIVE_CONTEXT.equals(ctx)) {
appiumDriver.context(ctx);
break;
}
}
String curCtx = appiumDriver.getContext();
if (MobileDevice.NATIVE_CONTEXT.equals(curCtx)) {
throw new RuntimeException("未检测到webview,无法切换,当前contexts: " + contexts.toString());
}
}
}
}
| true |
4718ce85a848ca97f46492ddfc44b057cb08146a | Java | xiaofeixiadafeixia/yztz | /yztz/src/cxw/yztz/web/servlet/UIServlet.java | UTF-8 | 11,261 | 1.898438 | 2 | [] | no_license | package cxw.yztz.web.servlet;
import java.io.IOException;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.JsonObject;
import cxw.yztz.entity.BrowseHistory;
import cxw.yztz.entity.BrowseHistoryUionPKID;
import cxw.yztz.entity.Collect;
import cxw.yztz.entity.CollectUionPKID;
import cxw.yztz.entity.Product;
import cxw.yztz.entity.Type;
import cxw.yztz.entity.User;
import cxw.yztz.service.IAddressService;
import cxw.yztz.service.IBrowseHistoryService;
import cxw.yztz.service.ICollectService;
import cxw.yztz.service.IOrderService;
import cxw.yztz.service.IProductService;
import cxw.yztz.service.ITypeService;
import cxw.yztz.service.serviceImpl.AddressServiceImpl;
import cxw.yztz.service.serviceImpl.BrowseHistoryServiceImpl;
import cxw.yztz.service.serviceImpl.CollectServiceImpl;
import cxw.yztz.service.serviceImpl.OrderServiceImpl;
import cxw.yztz.service.serviceImpl.ProductServiceImpl;
import cxw.yztz.service.serviceImpl.TypeServiceImpl;
import cxw.yztz.utils.PageModel;
import cxw.yztz.web.base.BaseServlet;
/**
* 负责页面的跳转逻辑
* @author 24780
*
*/
public class UIServlet extends BaseServlet {
/**
*
*/
private static final long serialVersionUID = 5931535433021013268L;
private IAddressService iAddressService = new AddressServiceImpl();
private IProductService iProductService = new ProductServiceImpl();
private ICollectService iCollectService = new CollectServiceImpl();
private IBrowseHistoryService iBrowseHistoryService = new BrowseHistoryServiceImpl();
private IOrderService iOrderService = new OrderServiceImpl();
private ITypeService iTypeService = new TypeServiceImpl();
public UIServlet() {
// TODO Auto-generated constructor stub
}
public String loginUI(HttpServletRequest req,HttpServletResponse resp) {
return "/login.html";
}
public String registerUI(HttpServletRequest req,HttpServletResponse resp) {
return "/register.html";
}
public String findPasswordUI(HttpServletRequest req,HttpServletResponse resp) {
return "/findPass.html";
}
/**
* 回到上次要访问的地址
* @param req
* @param resp
* @return
*/
public String lastRequestUrl(HttpServletRequest req,HttpServletResponse resp) {
Object obj = req.getSession().getAttribute("lastRequestUrl");
return obj==null?mainUI(req,resp):"UIServlet?method="+obj.toString();
}
public String myCenterUI(HttpServletRequest req,HttpServletResponse resp) {
Object obj = req.getSession().getAttribute("user");
if(obj!=null) {
User user = (User)obj;
try {
req.setAttribute("colleges", this.iAddressService.getColleges());
req.setAttribute("browseHistorys", this.iBrowseHistoryService.getBrowseHistorysByCount(user, 0, 8));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "/jsp/my_center.jsp";
}
return this.skipUrl(false,req, resp, "/login.html","myCenterUI");
}
public String mainUI(HttpServletRequest req,HttpServletResponse resp) {
String currentNum = req.getParameter("currentPageNum");
if(currentNum==null)
currentNum="1";
try {
req.setAttribute("newProducts", iProductService.getProductsBySort(12, "time"));
PageModel pm = iProductService.getAllProductsByCurrentPageNum(Integer.valueOf(currentNum));
pm.setUrl("UIServlet?method=mainUI");
req.setAttribute("pm", pm);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "/jsp/index.jsp";
}
public String productListUI(HttpServletRequest req,HttpServletResponse resp) {
String num = req.getParameter("num");
String type_id = req.getParameter("type_id");
String str = req.getParameter("str");
PageModel pm =null;
try {
if(num==null)
num = "1";
if(type_id!=null) {
Type type = iTypeService.getType(new Type(Integer.valueOf(type_id), null));
req.setAttribute("type", type);
pm = iProductService.getProductsByCurrentPageNumWithType(Integer.parseInt(num), type);
pm.setUrl("UIServlet?method=productListUI&type_id="+type_id);
}else {
req.setAttribute("str", str);
pm = iProductService.getProductsByFuzzyQueryWhitCurrentPage(str, Integer.valueOf(num), 18);
pm.setUrl("UIServlet?method=productListUI&str="+str);
}
req.setAttribute("pm",pm );
}catch(Exception e) {
e.printStackTrace();
}
return "jsp/product_list.jsp";
}
/**
* 如果要访问A页面,需要跳转一个页面验证后,在返回A页面,则可用此方法。
* 但在验证页面验证完毕后调用本类的lastRequestUrl方法进行判断
*
* 例如: 所在页面为A ,要访问页面B ,验证页面为 C
* 则在 A -> B 过程中调用本方法,然后 到 C,C页面验证完毕后调用本类的lastRequestUrl()方法返回B页面
* @param req
* @param resp
* @param url 验证页面 的路径(一般为登录页面) (使用重定向 response)
* @param lastRequestUrl 需要访问的页面
* @param flag 如果为真则用客户端跳转,否则用服务端跳转
* @return 返回需要跳转路径(服务端跳转 request)
*/
private String skipUrl(boolean flag,HttpServletRequest req,HttpServletResponse resp,String url,String lastRequestUrl) {
if(flag) {
//设置上次要访问的路径为这个,登录后可以直接取出这个地址并访问
req.getSession().setAttribute("lastRequestUrl", lastRequestUrl);
try {
resp.sendRedirect(req.getContextPath()+url);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}else{
//禁止页面缓存
resp.setHeader("Pragma","No-cache");
resp.setHeader("Cache-Control","no-cache");
resp.setDateHeader("Expires", 0);
//设置上次要访问的路径为这个,登录后可以直接取出这个地址并访问
req.getSession().setAttribute("lastRequestUrl", lastRequestUrl);
return url;
}
}
/**
* 跳转到 “我的收藏”页面 如果有商品id顺带着添加收藏记录
* @param req
* @param resp
* @return
*/
public String myCollectionUI(HttpServletRequest req,HttpServletResponse resp) {
User user = (User)req.getSession().getAttribute("user");
if(user!=null) {
//取出用户所有的收藏记录
try {
req.setAttribute("collects", iCollectService.getCollectsByUser(user));
//取出所有学院的地址
req.setAttribute("colleges", iAddressService.getColleges());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "jsp/my_collection.jsp";
}
return this.skipUrl(false,req, resp, "/login.html","myCollectionUI");
}
public String myProductAddUI(HttpServletRequest req,HttpServletResponse resp){
if(req.getSession().getAttribute("user")!=null) {
return "jsp/my_product_add.jsp";
}
return this.skipUrl(false,req, resp, "/login.html","myProductAddUI");
}
public String myProductUI(HttpServletRequest req,HttpServletResponse resp) {
Object user = req.getSession().getAttribute("user");
if(user!=null) {
String currentPageNum = req.getParameter("currentPageNum");
if(currentPageNum==null)
currentPageNum="1";
try {
PageModel pm = iProductService.getProductsByCurrentPageNumWithUser((User)user, Integer.parseInt(currentPageNum));
pm.setUrl("UIServlet?method=myProductUI");
req.setAttribute("pm", pm);
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "jsp/my_product.jsp";
}
return this.skipUrl(false,req, resp, "/login.html","myProductUI");
}
/**
* 跳转到商品详情页
* @param req
* @param resp
* @return
*/
public String productInfoUI(HttpServletRequest req,HttpServletResponse resp) {
String product_id = req.getParameter("goods_id");
User user = (User)req.getSession().getAttribute("user");
if(product_id!=null) {
try {
//获取到 商品信息
Product product = iProductService.getProductById(Integer.parseInt(product_id));
req.setAttribute("product", product);
//获取收藏次数
int count = iCollectService.getCollectCountByProduct(product);
req.setAttribute("collectCount", count);
req.setAttribute("isCanCollect", "1");
Product p = iProductService.getProductById(Integer.parseInt(product_id));
if(p.getState()==4) {//为空说明用户已删除
req.setAttribute("isCanCollect", "4");
}else if(user!=null) {
//添加浏览记录
iBrowseHistoryService.saveBrowseHistory(new BrowseHistory(new BrowseHistoryUionPKID(user.getId(), product), new Date()));
//判断这个商品是否在收藏记录里
Collect collect = iCollectService.getCollectBycollectUnionPKID(
new Collect(new CollectUionPKID(user.getId(), product), null));
if(collect!=null) {
req.setAttribute("isCanCollect", "2");
}else {
//判断是否自己上传
if(p.getUser().getId()==user.getId()) {
req.setAttribute("isCanCollect", "3");
}
}
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "jsp/product_info.jsp";
}
public String collectProduct(HttpServletRequest req,HttpServletResponse resp) {
JsonObject json = new JsonObject();
json.addProperty("state", 0);
User user = (User)req.getSession().getAttribute("user");
String product_id = req.getParameter("product_id");
if(user!=null) {
if(product_id!=null) {
try {
Product p = new Product();
p.setGoods_id(Integer.parseInt(product_id));
Collect collect = new Collect(new CollectUionPKID(user.getId(),p), new Date());
iCollectService.saveCollect(collect);
json.addProperty("state", 1);
}catch(Exception e) {
e.printStackTrace();
}
}
try {
resp.getWriter().print(json.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else {
json.addProperty("errorMessage", "NoUser");
try {
resp.getWriter().print(json.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return this.skipUrl(false,req, resp, null,"productInfoUI&"+req.getQueryString().split("&")[1]);
}
return null;
}
public String orderUI(HttpServletRequest req, HttpServletResponse resp) {
Object obj = (User)req.getSession().getAttribute("user");
String currentPageNum = req.getParameter("currentPageNum");
if(currentPageNum==null)
currentPageNum = "1";
if(obj!=null) {
try {
User user = (User)obj;
PageModel pm = iOrderService.getOrders(user, Integer.parseInt(currentPageNum), 5);
pm.setUrl("UIServlet?method=orderUI");
req.setAttribute("pm",pm);
}catch(Exception e) {
e.printStackTrace();
return "UIServlet?method=mainUI";
}
return "jsp/my_order.jsp";
}
return this.skipUrl(false,req, resp, "/login.html","orderUI");
}
}
| true |
3c8be84e48a78e3c165829016ab2d460a2a79140 | Java | simonvandel/WI-mini-project | /web-crawler/src/main/java/RobotsTxtParser.java | UTF-8 | 460 | 2.125 | 2 | [] | no_license | import crawlercommons.robots.BaseRobotRules;
import crawlercommons.robots.BaseRobotsParser;
import crawlercommons.robots.SimpleRobotRulesParser;
/**
* Created by simon on 9/12/16.
*/
public class RobotsTxtParser {
public static BaseRobotRules parse(byte[] robotsTxtContent, String robotName) {
BaseRobotsParser parser = new SimpleRobotRulesParser();
return parser.parseContent("foo", robotsTxtContent, "text/plain", robotName);
}
}
| true |
c7cfe64123bcab6c2c50477339365a39d2c0745f | Java | gcarrot/BookListingApp | /app/src/main/java/si/gcarrot/booklistingapp/Book.java | UTF-8 | 639 | 2.59375 | 3 | [] | no_license | package si.gcarrot.booklistingapp;
/**
* Created by Urban on 7/5/17.
*/
public class Book {
/** Book author **/
private String mAuthor;
/** Book title **/
private String mTitle;
/** Book published date **/
private String mPublishedDate;
public Book(String author, String title, String publishedDate) {
mAuthor = author;
mTitle = title;
mPublishedDate = publishedDate;
}
public String getAuthor() {
return mAuthor;
}
public String getTitle() {
return mTitle;
}
public String getPublishedDate() {
return mPublishedDate;
}
}
| true |
257e99c8f1dc998f878ae59d30f1189ae423a4ca | Java | mksmanjit/Calculator-Challange | /src/main/java/com/challange/redmart_calculator/model/CellDetail.java | UTF-8 | 4,572 | 3.046875 | 3 | [] | no_license | package com.challange.redmart_calculator.model;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Pattern;
import com.challange.redmart_calculator.expression.Token;
import com.challange.redmart_calculator.expression.CellReferenceToken;
import com.challange.redmart_calculator.factory.TokenFactory;
/**
* This class holds the Detail of a Cell.
*
* @author manjkuma
*
*/
public class CellDetail {
/**
* Pattern of matching one or more spaces.
*/
private final Pattern splitRegex = Pattern.compile("\\s+");
/**
* row index of the cell.
*/
private final int rowIndex;
/**
* column index of the cell.
*/
private final int columnIndex;
/**
* List of Reference Cell on which this cell is depend.
*/
private final List<CellReferenceToken> cellReferencesTokens;
/**
* Holds the list of token value for this row.
*/
private final List<Token> cellTokens;
/**
* Holds the full content of this cell.
*/
private final String contents;
/**
* Holds the number of unresolved reference on which this cell is depend.
*/
private int unresolvedRefs;
/**
* true if Cell is evaluated successfully else false.
*/
private boolean evaluated;
/**
* Holds the evaluated value after applying operators.
*/
private double evaluatedValue;
/**
* Holds the reference of work book under which this cell is present.
*/
private WorkSheet workBook;
/**
* Constructor for setting CellDetail value.
*
* @param rowIndex row index of the cell.
* @param colIndex column index of the cell.
* @param contents full content of this cell.
* @param workBook reference of work book under which this cell is present.
*/
public CellDetail(int rowIndex, int colIndex, String contents, WorkSheet workBook) {
this.rowIndex = rowIndex;
this.columnIndex = colIndex;
this.contents = contents;
this.unresolvedRefs = 0;
this.cellReferencesTokens = new LinkedList<CellReferenceToken>();
this.cellTokens = new LinkedList<Token>();
this.workBook = workBook;
this.parse();
}
/**
* This method parse the full content of this cell and divide this into token.
*/
private void parse() {
String[] expressions = splitRegex.split(contents);
TokenFactory expressionFactory = new TokenFactory();
for (String expression : expressions) {
Token token = expressionFactory.createTokenObject(expression);
if (token instanceof CellReferenceToken) {
cellReferencesTokens.add(((CellReferenceToken) token));
unresolvedRefs++;
}
cellTokens.add(token);
}
}
/**
* @return the unresolvedRefs
*/
public int getUnresolvedRefs() {
return unresolvedRefs;
}
/**
* @param unresolvedRefs the unresolvedRefs to set
*/
public void setUnresolvedRefs(int unresolvedRefs) {
this.unresolvedRefs = unresolvedRefs;
}
/**
* @return the evaluated
*/
public boolean isEvaluated() {
return evaluated;
}
/**
* @param evaluated the evaluated to set
*/
public void setEvaluated(boolean evaluated) {
this.evaluated = evaluated;
}
/**
* @return the evaluatedValue
*/
public double getEvaluatedValue() {
return evaluatedValue;
}
/**
* @param evaluatedValue the evaluatedValue to set
*/
public void setEvaluatedValue(double evaluatedValue) {
this.evaluatedValue = evaluatedValue;
}
/**
* @return the workBook
*/
public WorkSheet getWorkBook() {
return workBook;
}
/**
* @param workBook the workBook to set
*/
public void setWorkBook(WorkSheet workBook) {
this.workBook = workBook;
}
/**
* @return the splitRegex
*/
public Pattern getSplitRegex() {
return splitRegex;
}
/**
* @return the row
*/
public int getRowIndex() {
return rowIndex;
}
/**
* @return the col
*/
public int getColumnIndex() {
return columnIndex;
}
/**
* @return the references
*/
public List<CellReferenceToken> getCellReferencesTokens() {
return cellReferencesTokens;
}
/**
* @return the tokenList
*/
public List<Token> getCellTokens() {
return cellTokens;
}
/**
* @return the contents
*/
public String getContents() {
return contents;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CellDetail cell = (CellDetail) o;
if (columnIndex != cell.columnIndex) return false;
if (rowIndex != cell.rowIndex) return false;
if (!contents.equals(cell.contents)) return false;
return true;
}
@Override
public int hashCode() {
return (String.valueOf(rowIndex) + String.valueOf(columnIndex)).hashCode();
}
}
| true |
554360d38ae9a81ef45fc66bf83db7ab9a7c145f | Java | alvarezfelipe/APS2021 | /src/main/java/com/mycompany/aps/TableConsultas.java | UTF-8 | 1,743 | 2.859375 | 3 | [] | no_license |
package com.mycompany.aps;
import javax.swing.table.AbstractTableModel;
import java.util.ArrayList;
public class TableConsultas extends AbstractTableModel{
private ArrayList<Model> linhas;
String[] coluna;
public TableConsultas(ArrayList<Model> linha, String[] coluna){
linhas = linha;
this.coluna = coluna;
}
//Apresenta o numero de linhas
@Override
public int getRowCount() {
return linhas.size();
}
//Conta qtde de colunas
@Override
public int getColumnCount() {
return coluna.length;
}
@Override
public String getColumnName(int colunaIndice){
return coluna[colunaIndice];
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Model dados = (Model) linhas.get(rowIndex);
switch (columnIndex){
case 0:
return dados.getEspecie();
case 1:
return dados.getNomeComum();
case 2:
return dados.getFaunaFlora();
case 3:
return dados.getGrupo();
case 4:
return dados.getFamilia();
case 5:
return dados.getCatAmeaca();
case 6:
return dados.getSiglaCatAmeaca();
default:
return null;
}
}
public void addLista(ArrayList<Model> dados) {
int listaAntiga = getRowCount();
//Adiciona linas
linhas.addAll(dados);
//Aqui reportamos a mudança para o JTable, assim ele pode se redesenhar, para visualizarmos a alteração
fireTableRowsInserted(listaAntiga, getRowCount() - 1);
}
}
| true |
0c1f707414ed9f9eb9254007a8d4394f80c95ac5 | Java | zhaolifeng/jiaowu | /shenlan-manager/shenlan-dao/src/main/java/com/shenlan/dao/jwManager/JwClassesDao.java | UTF-8 | 1,579 | 2.03125 | 2 | [] | no_license | package com.shenlan.dao.jwManager;
import com.shenlan.common.utils.page.PageBoundsProxy;
import com.shenlan.common.utils.page.PageParameter;
import com.shenlan.dao.BaseDao;
import com.shenlan.domain.bo.JwClasses;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* 积分规则兑换Dao层
* @author YANG
*
*/
@Repository
public class JwClassesDao extends BaseDao<JwClasses> {
public void addClasses(JwClasses classes){
this.getSqlSession().insert(this.namespace + ".addClasses", classes);
}
public List<JwClasses> findClasses(){
return this.getSqlSession().selectList(this.namespace + ".findClasses");
}
public PageParameter findClasses(PageParameter page,JwClasses classes){
PageBoundsProxy pbp = new PageBoundsProxy(page);
List<JwClasses> classeses=this.getSqlSession().selectList(this.namespace + ".findClasses", classes,pbp.getPageBounds());
pbp.setPageParameter(classeses);
return page;
}
public List<JwClasses> findClassesByCondtion(JwClasses classes){
return this.getSqlSession().selectList(this.namespace + ".findClassesByCondtion",classes);
}
public PageParameter findClassesByCondtion(PageParameter page,JwClasses classes){
PageBoundsProxy pbp = new PageBoundsProxy(page);
List<JwClasses> classeses=this.getSqlSession().selectList(this.namespace + ".findClassesByCondtion", classes,pbp.getPageBounds());
pbp.setPageParameter(classeses);
return page;
}
public JwClasses getClassesById(Integer classesId){
return this.getSqlSession().selectOne(this.namespace + ".getClasses", classesId);
}
}
| true |
c01e8b23b1bf7449fb94e7bf7b3fc4044655f482 | Java | imenBHamed/DesignPatterns | /Strategy_DP/src/Context.java | UTF-8 | 204 | 2.296875 | 2 | [] | no_license |
public class Context {
private Strategy strategy;
public void appliquerStrategy() {
strategy.methodStrategy();
}
public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}
}
| true |
0b002491f44db04b107d802690c8af530d0bc0b1 | Java | luissigal/Use-My-Comunity | /src/search/searchQueryBean.java | UTF-8 | 360 | 2.09375 | 2 | [] | no_license | package search;
public class searchQueryBean {
private String postcode;
private String category;
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
}
| true |
1222dfa8352b3959dd1ada6904feffee3c11c514 | Java | pkosta/LetsRemind2.0 | /app/src/main/java/palash/watermelon/letsremind/dependencyinjection/module/activitymodule/HomeActivityModule.java | UTF-8 | 766 | 1.96875 | 2 | [] | no_license | package palash.watermelon.letsremind.dependencyinjection.module.activitymodule;
import android.app.Activity;
import dagger.Binds;
import dagger.Module;
import dagger.android.ActivityKey;
import dagger.android.AndroidInjector;
import dagger.multibindings.IntoMap;
import palash.watermelon.letsremind.dependencyinjection.subcomponent.HomeActivitySubcomponent;
import palash.watermelon.letsremind.userinterface.HomeActivity;
/*
* Created by Palash on 27/09/17.
*/
@Module(subcomponents = HomeActivitySubcomponent.class)
public abstract class HomeActivityModule {
@Binds
@IntoMap
@ActivityKey(HomeActivity.class)
abstract AndroidInjector.Factory<? extends Activity>
bindYourActivityInjectorFactory(HomeActivitySubcomponent.Builder builder);
}
| true |
af46efae5ba8c887b360918caf668a940d73c4ed | Java | peakingTony/APITest | /HengWSQc/src/main/java/nh/automation/tools/serviceImpl/UserServiceImp.java | UTF-8 | 593 | 2.296875 | 2 | [] | no_license | package nh.automation.tools.serviceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import nh.automation.tools.dao.UserMapper;
import nh.automation.tools.entity.User;
@Service
public class UserServiceImp {
@Autowired
private UserMapper userMapper;
/**
* 根据用户名查询用户
* @param userName
* @return
*/
public User getUser(String userName){
User user=null;
try {
user = userMapper.getUser(userName);
} catch (Exception e) {
e.printStackTrace();
return user;
}
return user;
}
}
| true |
e0a47fbfd6bd1b759837efd4361bb6f3c3db25e5 | Java | hernanytec/pds | /pedra_papel_tesoura/src/com/pds/boundary/Output.java | UTF-8 | 1,192 | 3.421875 | 3 | [] | no_license | package com.pds.boundary;
import com.pds.entity.GameResult;
import com.pds.entity.ScoreBoard;
import java.util.ArrayList;
public class Output {
public void showOptions(){
System.out.println("Escolha uma opção:");
System.out.println("1 - Pedra");
System.out.println("2 - Papel");
System.out.println("3 - Tesoura");
System.out.println("4 - Parar o jogo");
}
public void showInvalidOptionMessage() {
System.out.println("Opção inválida! Tente novamente.");
}
public void showScore(ArrayList<ScoreBoard> array){
int vitorias = 0;
int derrotas = 0;
int empates = 0;
for (ScoreBoard scoreboard: array) {
GameResult result = scoreboard.getResult();
switch (result){
case VITORIA:
vitorias++;
break;
case DERROTA:
derrotas++;
break;
default:
empates++;
}
}
System.out.println("O resultado foi de: " + vitorias + " vitórias, " + derrotas + " derrotas e " + empates + " empates");
}
}
| true |
60d3f054c5f50daadcd0d5b4f07377ce2e40fedb | Java | HugoLuna5/Flappy-Bird | /src/Interfaz/Login.java | UTF-8 | 7,474 | 2.453125 | 2 | [
"Apache-2.0"
] | permissive | package Interfaz;
/**
*
* @author HugoLuna
* @email hugo@lunainc.org
*/
public class Login extends javax.swing.JPanel {
public javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
public javax.swing.JTextField jTextField1;
public Login() {
initComponents();
}
@SuppressWarnings("unchecked")
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jPanel1.setBackground(new java.awt.Color(255, 255, 153));
jPanel2.setBackground(new java.awt.Color(255, 255, 153));
jPanel2.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel1.setText("MI NOMBRE:");
jTextField1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jTextField1.setForeground(new java.awt.Color(0, 0, 255));
jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyReleased(java.awt.event.KeyEvent evt) {
jTextField1KeyReleased(evt);
}
@Override
public void keyTyped(java.awt.event.KeyEvent evt) {
jTextField1KeyTyped(evt);
}
});
jButton1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jButton1.setForeground(new java.awt.Color(255, 0, 0));
jButton1.setText("JUGAR");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jButton1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jLabel2.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel2.setText("Hacer click en la pantalla del juego para mantener en vuelo al personaje.");
jLabel3.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel3.setText("Pasar por el medio de los tubos, para obtener más puntos.");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 357, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 357, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel3)
.addContainerGap(13, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
}
private void jTextField1KeyReleased(java.awt.event.KeyEvent evt) {
}
private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) {
int tamaño = this.jTextField1.getText().length();
if (tamaño >= 12) {
evt.consume();
}
}
}
| true |
4c306c98dbf77411993772b616dfe44f4ec158c8 | Java | hhkopper/TiraLabra-Pacman | /Tiralabra/src/pacman/alusta/Peliruutu.java | UTF-8 | 3,994 | 2.9375 | 3 | [] | no_license | package pacman.alusta;
/**
* Peliruutu tietää kaiken tärkeän tiedon mitä ruudussa tapahtuu ja ketä ja mitä
* se sisältää.
*
* @author hhkopper
*/
public class Peliruutu implements Comparable<Peliruutu>{
/**
* Ruudun X koordinaatti.
*/
private int x;
/**
* Ruudun Y koordinaatti.
*/
private int y;
/**
* Kertoo ruudun tyypin, 0 jos seinä, 1 jos käytävä, 2 jos ekstrapallon paikka ja 3 jos vaikka jonne ei laiteta mitään.
*/
private int ruudunTyyppi;
/**
* Kertoo onko Man ruudussa, true, jos on ja false, jos ei.
*/
private boolean onkoMan;
/**
* Kertoo onko Haamu ruudussa, true, jos on ja false, jos ei.
*/
private boolean onkoHaamu;
/**
* Kertoo onko pistepallo ruudussa vai ei, true, jos on ja false, jos ei.
*/
private boolean onkoPallo;
/**
* Kertoo onko ekstra pistepallo ruudussa, true, jos on ja false, jos ei.
*/
private boolean onkoExtraPallo;
/**
* Kertoo etäisyyden alkuun.
*/
private int etaisyysAlkuun;
/**
* Kertoo etäisyyden maaliin.
*/
private int etaisyysMaaliin;
/**
* Kertoo edellisen peliruudun.
*/
private Peliruutu edellinen;
/**
* Konstruktorissa annetaan arvot koordinaateille.
*
* @param x koordinaatti X
* @param y koordinaatti Y
*/
public Peliruutu(int x, int y) {
this.x = x;
this.y = y;
}
public Peliruutu getEdellinen() {
return this.edellinen;
}
public void setEdellinen(Peliruutu ruutu) {
this.edellinen = ruutu;
}
public int getEtaisyysAlkuun() {
return this.etaisyysAlkuun;
}
public int getEtaisyysMaaliin() {
return this.etaisyysMaaliin;
}
public void setEtaisyysAlkuun(int luku) {
this.etaisyysAlkuun = luku;
}
public void setEtaisyysMaaliin(int luku) {
this.etaisyysMaaliin = luku;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
public void setRuudunTyyppi(int uusiTyyppi) {
this.ruudunTyyppi = uusiTyyppi;
}
public int getRuudunTyyppi() {
return this.ruudunTyyppi;
}
public void setOnkoMan(boolean arvo) {
this.onkoMan = arvo;
}
public boolean getOnkoMan() {
return this.onkoMan;
}
public void setOnkoHaamu(boolean arvo) {
this.onkoHaamu = arvo;
}
public boolean getOnkoHaamu() {
return this.onkoHaamu;
}
public void setOnkoPallo(boolean arvo) {
this.onkoPallo = arvo;
}
public boolean getOnkoPallo() {
return this.onkoPallo;
}
public void setOnkoExtraPallo(boolean arvo) {
this.onkoExtraPallo = arvo;
}
public boolean getOnkoExtraPallo() {
return this.onkoExtraPallo;
}
/**
* Equals metodi peliruuduille.
* @param olio
* @return
*/
@Override
public boolean equals(Object olio) {
if(olio == null) {
return false;
}
if(getClass() != olio.getClass()) {
return false;
}
Peliruutu verrattava = (Peliruutu) olio;
if(this.x != verrattava.getX() || this.y != verrattava.getY()) {
return false;
}
return true;
}
/**
* Peliruudulle lasketaan oman hajautusarvon.
* @return
*/
@Override
public int hashCode() {
int hash = 7;
if(this.x < 0 || this.y < 0) {
return hash;
}
return this.x*19+this.y;
}
@Override
public int compareTo(Peliruutu ruutu) {
return (this.etaisyysMaaliin+this.etaisyysAlkuun) - (ruutu.getEtaisyysMaaliin()+ruutu.getEtaisyysAlkuun());
}
@Override
public String toString() {
return "("+this.x+","+this.y+")";
}
}
| true |
d3687f7234e01baefa987db702955ed84a9beb89 | Java | hubo0508/jr | /jrplatform/src.java/com/jr/platform/member/service/RoleDocumentService.java | UTF-8 | 2,312 | 2.09375 | 2 | [] | no_license | package com.jr.platform.member.service;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import com.jr.core.IService;
import com.jr.core.Results;
import com.jr.platform.system.service.RoleService;
@Service("roleDocumentService")
public class RoleDocumentService extends IService {
protected static Log logger = LogFactory.getLog(RoleDocumentService.class);
@Autowired
private RoleService roleService;
@Autowired
private JdbcTemplate jdbcTemplate;
public Results roleDocumentIdList(String id) {
String sql = "select document_type_id,video_play From role_documenttype rd left join role r on r.id = rd.role_id where role_id = ?";
return new Results(jdbcTemplate.queryForList(sql, Integer.parseInt(id)));
}
@Transactional(isolation = Isolation.REPEATABLE_READ)
public Results save(final String video_play, final String role_id,
final int[] menu_ids) {
this.deleteByRoleid(Integer.parseInt(role_id));
this.roleService.updateByVideoplay(Integer.parseInt(video_play),
Integer.parseInt(role_id));
if (menu_ids != null) {
String insertSql = "INSERT INTO role_documenttype(role_id, document_type_id) VALUES (?,?)";
jdbcTemplate.batchUpdate(insertSql,
new BatchPreparedStatementSetter() {
public void setValues(PreparedStatement ps, int i)
throws SQLException {
ps.setInt(1, Integer.parseInt(role_id));
ps.setInt(2, menu_ids[i]);
}
public int getBatchSize() {
return menu_ids.length;
}
});
}
return Results.SUCCESS;
}
@Transactional(isolation = Isolation.REPEATABLE_READ)
public Results deleteByRoleid(int role_id) {
String deleteSql = "DELETE FROM role_documenttype WHERE role_id = ?";
jdbcTemplate.update(deleteSql, new Object[] { role_id });
return Results.SUCCESS;
}
}
| true |
2beee80feb16bc1eef63548082a7f4d8bc8e9d78 | Java | Ju-Young-Roh/j2 | /src/com/j2/command/undo/RemoteControlWithUndo.java | UTF-8 | 649 | 2.671875 | 3 | [] | no_license | package com.j2.command.undo;
public class RemoteControlWithUndo{
Command[] onCommands;
Command[] offCommands;
public RemoteControlWithUndo(){
onCommands=new Command[7];
offCommands=new Command[7];
Command noCommand = new NoCommand();
for(int i=0; i<7; i++){
onCommands[i]=noCommand;
offCommands[i]=noCommand;
}
}
public void setCommand(int slot, Command on, Command off){
onCommands[slot]=on;
offCommands[slot]=off;
}
public void onButtonWasPushed(int slot){
onCommands[slot].execute();
}
public void offButtonWasPushed(int slot){
offCommands[slot].execute();
}
} | true |
e68956fd065d5375bc9bb008fe2eb92c06b16561 | Java | 0n1dev/WebFlux | /Chap1-1/src/main/java/com/example/chap11/controller/ServerController.java | UTF-8 | 937 | 2.453125 | 2 | [] | no_license | package com.example.chap11.controller;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.chap11.domain.Dish;
import com.example.chap11.service.KitchenService;
import reactor.core.publisher.Flux;
@RestController
public class ServerController {
private final KitchenService kitchen;
public ServerController(KitchenService kitchen) {
this.kitchen = kitchen;
}
/**
* delivered 필드 false
* @return
*/
@GetMapping(value = "/server", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<Dish> serveDishes() {
return this.kitchen.getDishes();
}
/**
* delivered 필드 true
* @return
*/
@GetMapping(value = "/served/dishes", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<Dish> diliverDishes() {
return this.kitchen.getDishes()
.map(Dish::deliver);
}
}
| true |
88f3299edc373970dd5214134b27c8b6c8f4d56b | Java | willieny/Academic_Productivity_Management_System | /eclipse-workspace/Academic_Productivity_Management_System/src/model/entities/AcademicProduction.java | UTF-8 | 773 | 2.796875 | 3 | [] | no_license | package model.entities;
import java.util.ArrayList;
public abstract class AcademicProduction {
private String title;
private Project project;
private ArrayList<Collaborator> authors;
public AcademicProduction(String title) {
this.title = title;
this.authors = new ArrayList<Collaborator>();
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Project getProject() {
return project;
}
public void setProject(Project project) {
this.project = project;
}
public ArrayList<Collaborator> getAuthors() {
return authors;
}
public void addAuthor(Collaborator author) {
authors.add(author);
}
public void removeAuthor(Collaborator author) {
authors.remove(author);
}
}
| true |
f0be105e65fe87ee05652763444ab3269e1cecd3 | Java | EmamYounes/Android_Me-TFragments.00-StartingCode | /app/src/main/java/com/example/android/android_me/MainActivity.java | UTF-8 | 1,807 | 2.4375 | 2 | [] | no_license | package com.example.android.android_me;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.example.android.android_me.ui.AndroidMeActivity;
import com.example.android.android_me.ui.MyCustomFragment;
public class MainActivity extends AppCompatActivity implements MasterListFragment.onItemClick {
int headIndex, bodyIndex, legIndex;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public void onImageClick(int postion) {
int bodyPartNumber = postion / 12;
int lastIndex = postion - 12 * bodyPartNumber;
switch (bodyPartNumber) {
case 0:
headIndex = lastIndex;
break;
case 1:
bodyIndex = lastIndex;
break;
case 2:
legIndex = lastIndex;
break;
default:
break;
}
Bundle bundle=new Bundle();
bundle.putInt("headIndex",headIndex);
bundle.putInt("bodyIndex",bodyIndex);
bundle.putInt("legIndex",legIndex);
final Intent intent=new Intent(this, AndroidMeActivity.class);
intent.putExtras(bundle);
Button nextButton= (Button) findViewById(R.id.next_btn);
nextButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(intent);
}
});
Toast.makeText(getApplicationContext(), "Postion Clicked is" + postion, Toast.LENGTH_LONG).show();
}
}
| true |
24d8300cf5c3b68d9d691ecc3d2baec10a2a97a0 | Java | jnomada/AndroidStudioProjects | /CurrencyConverter/app/src/main/java/myapp/jsealey/currencyconverter/MainActivity.java | UTF-8 | 1,196 | 2.765625 | 3 | [] | no_license | package myapp.jsealey.currencyconverter;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
public void buttonClick(View view) {
try {
EditText currencyField = (EditText) findViewById(R.id.currencyTextField);
String amount = currencyField.getText().toString();
convert(amount);
}
catch (NumberFormatException e) {
Toast.makeText(this, "Please enter an amount", Toast.LENGTH_SHORT).show();
}
}
public void convert(String amount) {
double amountDouble = Double.parseDouble(amount);
double rate = 1.12;
double calculated = amountDouble*rate;
String conversion = String.format("%.2f", calculated);
Toast.makeText(this, "£"+amount+" is "+conversion+ " €", Toast.LENGTH_SHORT).show();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
| true |
4c6cddf9970c427dfad2958a21f7bd3d28f9cec6 | Java | liux001/design-mode | /design/src/main/java/com/liu/mode/action/mediator/User.java | UTF-8 | 424 | 2.46875 | 2 | [] | no_license | package com.liu.mode.action.mediator;
/**
* Created by simon.liu on 2017/1/16.
*/
public abstract class User {
private Mediator mediator;
public Mediator getMediator() {
return mediator;
}
/**
* construction
* @param mediator Mediator
*/
public User(Mediator mediator) {
this.mediator = mediator;
}
/**
* work
*/
public abstract void work();
}
| true |
aea625f65de2eac3e21d08dbb1d8ec443be99acf | Java | VamshiRajarikam/Financial_Inspirations | /src/MyProject/src/com/project/web/login.java | UTF-8 | 1,763 | 2.53125 | 3 | [] | no_license | package com.project.web;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class login extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("Username");
String password = req.getParameter("password");
String usernamedb;
String passworddb = null;
try {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
Class.forName("com.mysql.jdbc.Driver");
Connection connect = null;
connect = DriverManager.getConnection("jdbc:mysql://localhost:3309/myproject?" + "user=root&password=");
// Querying
PreparedStatement st = connect.prepareStatement("SELECT password FROM user WHERE user_name=?");
st.setString(1, username);
ResultSet rs = st.executeQuery();
while (rs.next()) {
passworddb = rs.getString("password");
}
if (passworddb.equals(password)) {
Cookie ck = new Cookie("username",username);
resp.addCookie(ck);
resp.sendRedirect("Home.jsp");
} else {
resp.sendRedirect("newlogin.html");
}
// ResultSet pass = st.executeQuery("SELECT password FROM user WHERE
// user_name=" + username);
// out.print(pass)
}
catch (
SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
| true |
42aaec93d8667b5637266814d213b5f2ecc8ad43 | Java | ulvij/android-mvp-example | /app/src/main/java/com/ulvijabbarli/android_mvp_note/BasePresenter.java | UTF-8 | 119 | 1.71875 | 2 | [] | no_license | package com.ulvijabbarli.android_mvp_note;
public interface BasePresenter<T> {
void setPresenter(T presenter);
}
| true |
461febe3bd5d23ad2f3c26d5c92772e738950aed | Java | chengentop/Microservices | /modules/system/src/main/java/com/rufeng/system/business/mapper/ISysOperLogDao.java | UTF-8 | 389 | 1.507813 | 2 | [] | no_license | package com.rufeng.system.business.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.rufeng.system.api.domain.SysOperLog;
import org.springframework.stereotype.Repository;
/**
* SysOperLogDao 数据访问对象
*
* @version v1.0.0
* @auther chengen
* @date 2020/12/26 20:26
*/
@Repository
public interface ISysOperLogDao extends BaseMapper<SysOperLog> {
}
| true |
39900aa921f2c6a2bfbea189c0e8c6baa1f719d0 | Java | fermadeiral/StyleErrors | /GourdErwa-MyNote/e1e122eab7729972a24be5c74b03d0e286611f85/1171/CEPProvider.java | UTF-8 | 5,737 | 2.09375 | 2 | [] | no_license | /**************************************************************************************
* Copyright (C) 2007 Esper Team. All rights reserved. *
* http://esper.codehaus.org *
* ---------------------------------------------------------------------------------- *
* The software in this package is published under the terms of the GPL license *
* a copy of which has been included with this distribution in the license.txt file. *
**************************************************************************************/
package esper.examples.benchmark.server;
import com.espertech.esper.client.*;
import esper.examples.benchmark.MarketData;
/**
* A factory and interface to wrap ESP/CEP engine dependency in a single space
*
* @author Alexandre Vasseur http://avasseur.blogspot.com
*/
public class CEPProvider {
public static ICEPProvider getCEPProvider() {
String className = System.getProperty("esper.benchmark.provider", EsperCEPProvider.class.getName());
try {
Class klass = Class.forName(className);
return (ICEPProvider) klass.newInstance();
} catch (Throwable t) {
t.printStackTrace();
throw new RuntimeException(t);
}
}
public static interface ICEPProvider {
public void init(int sleepListenerMillis);
public void registerStatement(String statement, String statementID);
public void sendEvent(Object theEvent);
}
public static class EsperCEPProvider implements ICEPProvider {
private static int sleepListenerMillis;
private EPAdministrator epAdministrator;
private EPRuntime epRuntime;
// only one of those 2 will be attached to statement depending on the -mode selected
private UpdateListener updateListener;
private MySubscriber subscriber;
public EsperCEPProvider() {
}
public void init(final int _sleepListenerMillis) {
sleepListenerMillis = _sleepListenerMillis;
Configuration configuration;
// EsperHA enablement - if available
try {
Class configurationHAClass = Class.forName("com.espertech.esperha.client.ConfigurationHA");
configuration = (Configuration) configurationHAClass.newInstance();
System.out.println("=== EsperHA is available, using ConfigurationHA ===");
} catch (ClassNotFoundException e) {
configuration = new Configuration();
} catch (Throwable t) {
System.err.println("Could not properly determine if EsperHA is available, default to Esper");
t.printStackTrace();
configuration = new Configuration();
}
configuration.addEventType("Market", MarketData.class);
// EsperJMX enablement - if available
try {
Class.forName("com.espertech.esper.jmx.client.EsperJMXPlugin");
configuration.addPluginLoader(
"EsperJMX",
"com.espertech.esper.jmx.client.EsperJMXPlugin",
null);// will use platform mbean - should enable platform mbean connector in startup command line
System.out.println("=== EsperJMX is available, using platform mbean ===");
} catch (ClassNotFoundException e) {
}
EPServiceProvider epService = EPServiceProviderManager.getProvider("benchmark", configuration);
epAdministrator = epService.getEPAdministrator();
updateListener = new MyUpdateListener();
subscriber = new MySubscriber();
epRuntime = epService.getEPRuntime();
}
public void registerStatement(String statement, String statementID) {
EPStatement stmt = epAdministrator.createEPL(statement, statementID);
if (System.getProperty("esper.benchmark.ul") != null) {
stmt.addListener(updateListener);
} else {
stmt.setSubscriber(subscriber);
}
}
public void sendEvent(Object theEvent) {
epRuntime.sendEvent(theEvent);
}
}
public static class MyUpdateListener implements UpdateListener {
public void update(EventBean[] newEvents, EventBean[] oldEvents) {
if (newEvents != null) {
if (EsperCEPProvider.sleepListenerMillis > 0) {
try {
Thread.sleep(EsperCEPProvider.sleepListenerMillis);
} catch (InterruptedException ie) {
}
}
}
}
}
public static class MySubscriber {
public void update(String ticker) {
if (EsperCEPProvider.sleepListenerMillis > 0) {
try {
Thread.sleep(EsperCEPProvider.sleepListenerMillis);
} catch (InterruptedException ie) {
}
}
}
public void update(MarketData marketData) {
if (EsperCEPProvider.sleepListenerMillis > 0) {
try {
Thread.sleep(EsperCEPProvider.sleepListenerMillis);
} catch (InterruptedException ie) {
}
}
}
public void update(String ticker, double avg, long count, double sum) {
if (EsperCEPProvider.sleepListenerMillis > 0) {
try {
Thread.sleep(EsperCEPProvider.sleepListenerMillis);
} catch (InterruptedException ie) {
}
}
}
}
}
| true |
794b178dd52a4d6bd5cf1910eabe1c7664f275de | Java | dblee0128/algorithm | /src/exwhile/Ex3.java | UTF-8 | 645 | 3.734375 | 4 | [] | no_license | package exwhile;
import java.util.Scanner;
public class Ex3 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int t = scan.nextInt(); // 테스트 케이스
int n = t; // 비교를 위해 처음 입력한 값 복사 (동일한 값이 들어가게 됨)
int count = 0;
while(true) {
// 48 = 4 + 8 = 12 -> 82
// 4 + 8의 8과 12의 2를 가져와서 더하는 연산
// 8*10 = 80 --> ((t%10) * 10)
// 2 --> (((t/10) + (t%10)) % 10)
t = ((t%10) * 10) + (((t/10) + (t%10)) % 10);
count++;
if(t == n) {
break;
}
}
System.out.println(count);
}
}
| true |
b7fc1ee3939cb9cd60fab476e1e0768a0ddebd33 | Java | osasg/library-management | /src/main/java/com/quangdat/validator/ShelfValidator.java | UTF-8 | 734 | 2.390625 | 2 | [] | no_license | package com.quangdat.validator;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.quangdat.entities.Shelf;
@Component
public class ShelfValidator implements Validator{
@Override
public boolean supports(Class<?> clazz) {
return Shelf.class.equals(clazz);
}
@Override
public void validate(Object obj, Errors err) {
ValidationUtils.rejectIfEmpty(err, "code", "shelf.code.empty");
ValidationUtils.rejectIfEmpty(err, "name", "shelf.name.empty");
ValidationUtils.rejectIfEmpty(err, "numberOfDrawer", "shelf.numberOfDrawer.empty");
}
}
| true |
62da0b91aba0aa598fb26fcd6ead0eb1eb5eaa8f | Java | shushu1234/LeetCode-Code | /279 numSquares/src/com/liuyao/Main.java | UTF-8 | 2,884 | 3.515625 | 4 | [] | no_license | package com.liuyao;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
/**
* 给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。
示例 1:
输入: n = 12
输出: 3
解释: 12 = 4 + 4 + 4.
示例 2:
输入: n = 13
输出: 2
解释: 13 = 4 + 9.
*/
public class Main {
public static void main(String[] args) {
// write your code here
System.out.println(new Solution().numSquares2(13));
}
static class Solution {
public static int numSquares(int n) {
//利用队列进行广度优先遍历
Queue<LinkedList<Integer>> queue=new LinkedList<>();
// 设置数组避免对重复的再次遍历
boolean[] arr=new boolean[n+1];
LinkedList<Integer> list=new LinkedList<>();
arr[n]=true;
list.add(n);
list.add(0);
queue.add(list);
while (!queue.isEmpty()){
int num=queue.peek().get(0);
int step=queue.peek().get(1);
queue.poll();
// if (num==0){
// return step;
// }
for (int i = 1; ; i++) {
int a=num-i*i;
if (a<0)
break;
if (a==0) //当a=0的时候表示找到了一条路径
return step+1;
if (!arr[a]){
LinkedList<Integer> list1=new LinkedList<>();
list1.add(a);
list1.add(step+1);
arr[a]=true;
queue.add(list1);
}
}
}
return 0;
}
private int memo[];
public int numSquaresHelp(int n){
if (n==0){
return 0;
}
if (memo[n]!=-1){
return memo[n];
}
int res=Integer.MAX_VALUE;
for (int i = 1; i*i <= n; i++) {
res=Math.min(res,numSquaresHelp(n-i*i)+1);
}
memo[n]=res;
return res;
}
public int numSquares2(int n){
memo=new int[n+1];
Arrays.fill(memo,-1);
return numSquaresHelp(n);
}
public static int numSquares3(int n){
if (n<=0){
return 0;
}
int[] memo=new int[n+1];
Arrays.fill(memo,Integer.MAX_VALUE);
memo[0]=0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j*j <=i ; j++) {
memo[i]=Math.min(memo[i],memo[i-j*j]+1);
}
}
return memo[n];
}
}
}
| true |
5b06f86bab0c84ddd05083f65ac84f5258018235 | Java | SalesforceRleaseManagement/MainBranch | /salesforceprod/src/main/java/com/util/sql/DeploymentSettingsSQLStmts.java | UTF-8 | 345 | 1.9375 | 2 | [] | no_license | package com.util.sql;
public class DeploymentSettingsSQLStmts {
public static String getOrgEnvQuery(String orgId){
String sql = "Select Id, ASA__BaseOrganizationId__c, ASA__TokenCode__c, ASA__Server_URL__c, ASA__RefreshTokenCode__c"
+ " FROM ASA__DeploymentSetting__c where ASA__BaseOrganizationId__c = '"+orgId+"'";
return sql;
}
}
| true |
b65fe35712cff23becf05b52f707cfa6961e7642 | Java | wuwtBeyond/algorithm | /src/main/java/com/github/algorithm/array/ContainerWithMostWater.java | UTF-8 | 697 | 3.75 | 4 | [] | no_license | package com.github.algorithm.array;
/**
* @author : wuwentao
* @date : 2020/5/31
*/
public class ContainerWithMostWater {
/**
* 移动两边中较小的那条边向里面挪,比较每次的最大值并更新
* @param height
* @return
*/
public int maxArea(int[] height) {
int left = 0, right = height.length-1;
int maxArea = Integer.MIN_VALUE;
while (left < right) {
maxArea = Math.max(maxArea, (right-left)*Math.min(height[left], height[right]));
if (height[left] < height[right]) {
left ++;
}else {
right --;
}
}
return maxArea;
}
}
| true |
f4a0206042e9ddf13ea56fb28801ab83202ad25e | Java | VKuz89/1 | /ProductAS/src/main/java/PEnter.java | UTF-8 | 2,910 | 2.765625 | 3 | [] | no_license | import asg.cliche.Command;
import java.math.BigDecimal;
// includes methods to enter product information in the system
public class PEnter<getEventStatusByValue> { // PEnter - product enter
private static Long count = 0L;
private String name;
private Long id;
private BigDecimal price;
private BigDecimal discount;
private String description;
private int value;
private String CAT;
public enum category {
FRUIT,
VEGETABLE,
DRINK,
BREAD,
MILK,
CHEMICALS,
CAR,
}
private void category (int value)
{
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
@Command
public String getEventStatusByValue (int value)
{
switch (value) {
case 1:
CAT = String.valueOf(category.BREAD);
case 2:
CAT = String.valueOf(category.DRINK);
case 3:
CAT = String.valueOf(category.FRUIT);
case 4:
CAT = String.valueOf(category.VEGETABLE);
case 5:
CAT = String.valueOf(category.CAR);
case 6:
CAT = String.valueOf(category.MILK);
case 7:
CAT = String.valueOf(category.CHEMICALS);
default:
break;
}
return CAT;
}
public PEnter() { //счетчик идентификаторов начиная с 0
id = count;
count++;
//System.out.println(id);
}
@Command
public Long getId() {
return id;
}
//Getter, Setter #name
@Command
public String getName() {
return name;
}
@Command
public void setName(String name) {
this.name = name;
}
//Getter, Setter #price
public BigDecimal getPrice() {
return price;
}
@Command
public void setPrice(BigDecimal price) {
this.price = price;
}
//Getter, Setter #Discount
@Command
public BigDecimal getDiscount() {
return discount;
}
@Command
public void setDiscount(BigDecimal discount) {
this.discount = discount;
}
//Getter, Setter #Discription
@Command
public String getDescription() {
return description;
}
@Command
public void setDescription(String description) {
this.description = description;
}
}
| true |
07ab247ae7d87b9956bb7184f95a75eabe9f55cc | Java | Boyquotes/godot-oppo | /oppo/android/GodotOppo.java | UTF-8 | 17,977 | 1.875 | 2 | [
"MIT"
] | permissive | package org.godotengine.godot;
import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.Toast;
import com.nearme.game.sdk.GameCenterSDK;
import com.nearme.game.sdk.callback.*;
import com.nearme.game.sdk.common.model.biz.PayInfo;
import com.nearme.game.sdk.common.util.AppUtil;
import com.oppo.mobad.api.InitParams;
import com.oppo.mobad.api.MobAdManager;
import com.oppo.mobad.api.ad.BannerAd;
import com.oppo.mobad.api.ad.InterstitialAd;
import com.oppo.mobad.api.ad.RewardVideoAd;
import com.oppo.mobad.api.listener.IBannerAdListener;
import com.oppo.mobad.api.listener.IInterstitialAdListener;
import com.oppo.mobad.api.listener.IRewardVideoAdListener;
import com.oppo.mobad.api.params.RewardVideoAdParams;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
/**
* chenlvtang
*/
public class GodotOppo extends Godot.SingletonBase{
private final String CALLBACK = "http://gamecenter.wanyol.com:8080/gamecenter/callback_test_url";
private Activity activity = null; // The main activity of the game
private boolean isReal = false;
private static final String TAG = "godot_oppo";
private static final String APP_TITLE = "APP_TITLE";
private static final String APP_DESC = "APP_TITLE";
public static int INSTANCE_ID = 0; //id 由Godot传入
/**
* 要支付的权限列表
*/
private List<String> mNeedRequestPMSList = new ArrayList<>();
private FrameLayout layout = null; // Store the layout
/**
* 从请求广告到广告展示出来最大耗时时间,只能在[3000,5000]ms之内。
*/
private static final int FETCH_TIME_OUT = 3000;
/**
* 插页广告列表
*/
private Map<String, InterstitialAd> interAdMap = new HashMap<>();
private Map<String, BannerAd> bannerAdMap = new HashMap<>();
private Map<String, RewardVideoAd> rewardVideoMap = new HashMap<>();
/**
* 打开游戏时候调用一次 初始化SDK
*
* @param appId 传入的广告应用ID
* @param payId
* @param isReal true真实环境 false测试
* @param instanceId GodotID
*/
public void init(String appId,String payId, boolean isReal, int instanceId) {
INSTANCE_ID = instanceId;
this.isReal = isReal;
// initAd(appId);
initPay(payId);
}
/**
* 初始化广告SDK
* @param appid
*/
private void initAd(String appid) {
InitParams initParams = new InitParams.Builder()
.setDebug(isReal)
//true打开SDK日志,当应用发布Release版本时,必须注释掉这行代码的调用,或者设为false
.build();
MobAdManager.getInstance().init(activity, appid, initParams);
Logi(TAG, "init oppo: appId:" + appid + " isReal" + isReal
+ " isSupportedMobile" + MobAdManager.getInstance().isSupportedMobile()
+ " VerCode:" + MobAdManager.getInstance().getSdkVerCode() + " VerName:" + MobAdManager.getInstance().getSdkVerName());
}
private void initPay(String payId) {
GameCenterSDK.init(payId, activity);
Logi(TAG,"init oppoPay:"+ payId);
}
/**
* 初始化插页广告
*
* @param id 广告位ID
*/
private void idInitInterstitial(final String id) {
InterstitialAd interstitialAd = new InterstitialAd(activity, id);
interstitialAd.setAdListener(new IInterstitialAdListener() {
@Override
public void onAdShow() {
idReutrnShowAdResult(0,id,"",0);
}
@Override
public void onAdFailed(String s) {
idReutrnShowAdResult(1,id,s,0);
}
@Override
public void onAdClick() {
}
@Override
public void onAdReady() {
}
@Override
public void onAdClose() {
}
});
interAdMap.put(id, interstitialAd);
}
public void idLoadInterstitial(final String id) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
if(!hasNecessaryPMSGranted()){
return;
}
if (interAdMap.get(id) == null) {
idInitInterstitial(id);
}
interAdMap.get(id).loadAd();
}
});
}
public void idShowInterstitial(final String id) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
if(!hasNecessaryPMSGranted()){
return;
}
if (interAdMap.get(id) == null) {
idInitInterstitial(id);
interAdMap.get(id).loadAd();
}
interAdMap.get(id).showAd();
}
});
}
private void idInitBanner(final String id) {
// layout = ((Godot) activity).layout;
/**
* new bannerAd
*/
BannerAd bannerAd = new BannerAd(activity, id);
/**
* set banner action listener.
*/
bannerAd.setAdListener(new IBannerAdListener() {
@Override
public void onAdShow() {
}
@Override
public void onAdFailed(String s) {
}
@Override
public void onAdClick() {
}
@Override
public void onAdReady() {
}
@Override
public void onAdClose() {
}
});
/**
* get banner view and add it to your window.
*
*/
View adView = bannerAd.getAdView();
/**
* adView maye be null.here must judge whether adView is null.
*/
if (null != adView) {
layout.addView(adView);
}
/**
* invoke loadAd() method to request ad.
*/
bannerAdMap.put(id, bannerAd);
}
public void idLoadBanner(final String id) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
if (bannerAdMap.get(id) == null) {
idInitBanner(id);
}
bannerAdMap.get(id).loadAd();
}
});
}
private void idInitRewardVideo(final String id) {
final RewardVideoAd rewardVideoAd = new RewardVideoAd(activity, id, new IRewardVideoAdListener() {
@Override
public void onAdSuccess() {
idUpAdloadStatus(id, true);
idReutrnShowAdResult(0,id,"",0);
rewardVideoMap.get(id).loadAd();
Logd(TAG, "RewardVideo onAdSuccess: id:" + id);
}
@Override
public void onAdFailed(String s) {
idReutrnShowAdResult(1,id,s,0);
Toast("RewardVideo onAdFailed s:" + s + " id:" + id);
}
@Override
public void onAdClick(long l) {
Logd(TAG, "RewardVideo onAdClick: id:" + id);
}
@Override
public void onVideoPlayStart() {
Logd(TAG, "RewardVideo onVideoPlayStart: id:" + id);
}
@Override
public void onVideoPlayComplete() {
rewardVideoMap.get(id).loadAd(getRewardVideoAdParams());
Logd(TAG, "RewardVideo onVideoPlayComplete: id:" + id);
}
@Override
public void onVideoPlayError(String s) {
Toast("RewardVideo onVideoPlayError s:" + s + " id:" + id);
}
@Override
public void onVideoPlayClose(long l) {
Logd(TAG, "RewardVideo onVideoPlayClose: id:" + id);
}
@Override
public void onLandingPageOpen() {
Logd(TAG, "RewardVideo onLandingPageOpen: id:" + id);
}
@Override
public void onLandingPageClose() {
Logd(TAG, "RewardVideo onLandingPageClose: id:" + id);
}
@Override
public void onReward(Object... objects) {
Logd(TAG, "RewardVideo onReward: id:" + id);
}
});
rewardVideoMap.put(id, rewardVideoAd);
}
public void idLoadRewardedVideo(final String id) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
if(!hasNecessaryPMSGranted()){
return;
}
if (rewardVideoMap.get(id) == null) {
idInitRewardVideo(id);
}
if (rewardVideoMap.get(id).isReady()) {
return;
}
RewardVideoAdParams rewardVideoAdParams = new RewardVideoAdParams.Builder()
.setFetchTimeout(3000)
.build();
rewardVideoMap.get(id).loadAd(rewardVideoAdParams);
}
});
}
public void idShowRewardedVideo(final String id) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
if(!hasNecessaryPMSGranted()){
return;
}
if (rewardVideoMap.get(id) == null) {
idInitRewardVideo(id);
}
if (!rewardVideoMap.get(id).isReady()) {
rewardVideoMap.get(id).loadAd(getRewardVideoAdParams());
} else {
rewardVideoMap.get(id).showAd();
}
idUpAdloadStatus(id, rewardVideoMap.get(id).isReady());
}
});
}
private RewardVideoAdParams getRewardVideoAdParams() {
RewardVideoAdParams rewardVideoAdParams = new RewardVideoAdParams.Builder()
.setFetchTimeout(3000)
.build();
return rewardVideoAdParams;
}
/**
* 判断是否已经获取必要的权限
*
* @return
*/
private boolean hasNecessaryPMSGranted() {
if (PackageManager.PERMISSION_GRANTED == ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_PHONE_STATE)) {
if (PackageManager.PERMISSION_GRANTED == ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
return true;
}
}
Toast("ERROR :缺少必要的权限");
Logw(TAG, "hasNecessaryPMSGranted: 申请权限未通过缺少必要的权限");
return false;
}
/**
* @param id
* @param amount 价格(分)
*/
public void pay(final int id, final int amount){
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
Logw(TAG, "Java Run pay");
if (!hasNecessaryPMSGranted()){
checkAndRequestPermissions();
return;
}
GameCenterSDK.getInstance().doSinglePay(activity, getOrder(id, amount), new SinglePayCallback() {
@Override
public void onCallCarrierPay(PayInfo payInfo, boolean b) {
Toast("运营商支付:"+payInfo.toString()+" result:"+b);
}
@Override
public void onSuccess(String s) {
Logd(TAG, "onSuccess: ");
Toast("支付成功");
idReutrnPayResult(0,id,s);
}
@Override
public void onFailure(String s, int i) {
Toast("支付失败:id:"+id+" i:"+i+"s");
idReutrnPayResult(1,id,s);
}
});
}
});
}
/**
* 生成订单
* @param id 产品号
* @param amount 价格(分)
*/
private PayInfo getOrder(int id, int amount){
PayInfo payInfo = new PayInfo(getOrderID(id),"Adflash",amount);
payInfo.setProductDesc("测试支OPPO付");
payInfo.setProductName("测试产品:"+id);
// payInfo.setCallbackUrl(CALLBACK);
Logd(TAG, "产生的订单: "+payInfo);
return payInfo;
}
/**
* 根据购买的产品号 生成订单号
*
* @param code 产品号
*/
private String getOrderID(int code) {
String order = "oppo" + code+System.currentTimeMillis() + new Random().nextInt(1000)+ Build.SERIAL;
Logd(TAG,"产生的订单号:"+order);
return order;
}
/**
* 退出游戏时候调用(释放资源)
*/
public void exit() {
// MobAdManager.getInstance().exit(activity);
payExit();
}
private void payExit(){
GameCenterSDK.getInstance().onExit(activity,
new GameExitCallback() {
@Override
public void exitGame() {
// CP 实现游戏退出操作,也可以直接调用
// AppUtil工具类里面的实现直接强杀进程~
AppUtil.exitGameProcess(activity);
}
});
}
/**
* 申请SDK运行需要的权限
* 注意:READ_PHONE_STATE、WRITE_EXTERNAL_STORAGE 两个权限是必须权限,没有这两个权限SDK无法正常获得广告。
* WRITE_CALENDAR、ACCESS_FINE_LOCATION 是两个可选权限;没有不影响SDK获取广告;但是如果应用申请到该权限,会显著提升应用的广告收益。
*/
private void checkAndRequestPermissions() {
/**
* READ_PHONE_STATE、WRITE_EXTERNAL_STORAGE 两个权限是必须权限,没有这两个权限SDK无法正常获得广告。
*/
if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_PHONE_STATE)) {
mNeedRequestPMSList.add(Manifest.permission.READ_PHONE_STATE);
}
if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
mNeedRequestPMSList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
/**
* WRITE_CALENDAR、ACCESS_FINE_LOCATION 是两个可选权限;没有不影响SDK获取广告;但是如果应用申请到该权限,会显著提升应用的广告收益。
*/
if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_CALENDAR)) {
mNeedRequestPMSList.add(Manifest.permission.WRITE_CALENDAR);
}
if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION)) {
mNeedRequestPMSList.add(Manifest.permission.ACCESS_FINE_LOCATION);
}
//
if (0 == mNeedRequestPMSList.size()) {
/**
* 权限都已经有了,那么直接调用SDK请求广告。
*/
// fetchSplashAd();
} else {
/**
* 有权限需要申请,主动申请。
*/
String[] temp = new String[mNeedRequestPMSList.size()];
mNeedRequestPMSList.toArray(temp);
ActivityCompat.requestPermissions(activity, temp, 100);
}
}
private void guidePermissions(){
}
/*
* ******************************************************************/
private void idUpAdloadStatus(final String id, boolean status) {
GodotLib.calldeferred(INSTANCE_ID, "_id_up_adload_status", new Object[]{id,status});
Logd(TAG, "更新广告加载情况列表 id:" + id + " bool:" + status);
}
/**
* @param code
* @param id
* @param reward
* @param number
*/
private void idReutrnShowAdResult(final int code, final String id, final String reward, final int number) {
GodotLib.calldeferred(INSTANCE_ID, "_id_showad_result", new Object[]{code,id,reward,number});
}
/**
* @param code 支付结果
* @param id 订单
* @param desc 描述
*/
private void idReutrnPayResult(final int code, final int id,final String desc) {
GodotLib.calldeferred(INSTANCE_ID, "_id_pay_result", new Object[]{code,id,desc});
}
/*Debug
* *************************************************************/
private void Toast(String string) {
if (!isReal) {
Toast.makeText(activity, string, Toast.LENGTH_SHORT).show();
}
}
private void Logi(final String TAG, final String log) {
if (!isReal) {
Log.i(TAG, log);
}
}
private void Logw(final String TAG, final String log) {
if (!isReal) {
Log.w(TAG, log);
}
}
private void Logd(final String TAG, final String log) {
if (!isReal) {
Log.d(TAG, log);
}
}
//----------------------------------------------------
static public Godot.SingletonBase initialize(Activity activity) {
return new GodotOppo(activity);
}
public GodotOppo(Activity p_activity) {
registerClass("Oppo", new String[]{
"init",
// banner
"idLoadBanner", "idShowBanner", "idHideBanner",
// Interstitial
"idLoadInterstitial", "idShowInterstitial",
// Rewarded video
"idLoadRewardedVideo", "idShowRewardedVideo", "exit","pay"
});
activity = p_activity;
}
}
| true |
19a4b88facde347e302ebe4d25c7b1b3abcaa654 | Java | ssarahlu/dreamation | /app/src/main/java/com/example/infs3605/ExploreFragment.java | UTF-8 | 7,309 | 1.9375 | 2 | [] | no_license | package com.example.infs3605;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.constraintlayout.widget.ConstraintSet;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.room.Room;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.example.infs3605.Entities.Event;
import com.example.infs3605.Entities.SavedEventData;
import com.example.infs3605.Entities.Social;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import java.util.ArrayList;
import java.util.List;
public class ExploreFragment extends Fragment {
private static final String TAG = "ExploreFragment";
//events
//saved
private RecyclerView savedEventRecyclerView;
private RecyclerView.Adapter savedEventAdapter;
private RecyclerView.LayoutManager savedEventLayoutManager;
private List<SavedEventData> savedEventList;
private ImageView ivSavedEventsTitle;
//not saved
private RecyclerView eventRecyclerView;
private RecyclerView.Adapter eventAdapter;
private RecyclerView.LayoutManager eventLayoutManager;
private ArrayList<Event> eventList;
public static SavedEventDatabase myDb;
private FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
private String email;
private TextView tvAllEvents;
private ImageView ivEventsTitle;
//social
private RecyclerView socialRecyclerView;
private RecyclerView.Adapter socialAdapter;
private RecyclerView.LayoutManager socialLayoutManager;
private TextView tvAllSocials;
private ArrayList<Social> socialList;
private ImageView ivSocialTitle;
public ExploreFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_explore, container, false);
((AppCompatActivity)getActivity()).getSupportActionBar().hide();
email = user.getEmail();
//saved events
myDb = Room.databaseBuilder(getActivity().getApplicationContext(), SavedEventDatabase.class, "myDb")
.allowMainThreadQueries()
.build();
Log.d(TAG, "doInBackground: " + email);
savedEventList = myDb.savedEventDataDao().getUserSavedEvents(email);
Log.d(TAG, "doInBackground: updating savedEventList | size = " + savedEventList.size());
for (SavedEventData event : savedEventList) {
System.out.println(event.getEmail() + " | " + event.getEventId());
}
ivSavedEventsTitle = view.findViewById(R.id.ivSavedEventsTitle);
ivEventsTitle = view.findViewById(R.id.ivEventsTitle);
savedEventRecyclerView = view.findViewById(R.id.rvSavedEvents);
savedEventRecyclerView.setHasFixedSize(true);
savedEventLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL,false);
savedEventRecyclerView.setLayoutManager(savedEventLayoutManager);
SavedEventAdapter.RecyclerViewClickListener savedEventListener = new SavedEventAdapter.RecyclerViewClickListener() {
@Override
public void onClick(View view, int eventId) {
launchEventActivity(eventId);
}
};
savedEventAdapter = new SavedEventAdapter(savedEventList,savedEventListener);
savedEventRecyclerView.setAdapter(savedEventAdapter);
if (savedEventList.isEmpty()) {
ivSavedEventsTitle.setVisibility(View.GONE);
ConstraintLayout constraintLayout = view.findViewById(R.id.constraintLayout);
ConstraintSet constraintSet = new ConstraintSet();
constraintSet.clone(constraintLayout);
constraintSet.connect(R.id.ivEventsTitle,ConstraintSet.TOP,R.id.constraintLayout,ConstraintSet.TOP);
constraintSet.applyTo(constraintLayout);
}
//not saved
tvAllEvents = view.findViewById(R.id.tvAllEvents);
ivEventsTitle = view.findViewById(R.id.ivEventsTitle);
tvAllEvents.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
launchAllEventsActivity();
}
});
eventList = Event.getEventList();
eventRecyclerView = view.findViewById(R.id.rvEvents);
eventRecyclerView.setHasFixedSize(true);
eventLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL,false);
eventRecyclerView.setLayoutManager(eventLayoutManager);
EventAdapter.RecyclerViewClickListener eventListener = new EventAdapter.RecyclerViewClickListener() {
@Override
public void onClick(View view, int eventId) {
launchEventActivity(eventId);
}
};
eventAdapter = new EventAdapter(eventList, eventListener);
eventRecyclerView.setAdapter(eventAdapter);
//social
socialList = Social.getSocialList();
tvAllSocials = view.findViewById(R.id.tvAllSocials);
ivSocialTitle = view.findViewById(R.id.ivSocialTitle);
tvAllSocials.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
launchAllSocialsActivity(0);
}
});
socialRecyclerView = view.findViewById(R.id.rvSocial);
socialRecyclerView.setHasFixedSize(true);
socialLayoutManager = new GridLayoutManager(getActivity(), 3, GridLayoutManager.HORIZONTAL, false);
socialRecyclerView.setLayoutManager(socialLayoutManager);
SocialAdapter.RecyclerViewClickListener socialListener = new SocialAdapter.RecyclerViewClickListener() {
@Override
public void onClick(View view, int socialId) {
launchAllSocialsActivity(socialId);
}
};
socialAdapter = new SocialAdapter(socialList, socialListener);
socialRecyclerView.setAdapter(socialAdapter);
return view;
}
private void launchAllEventsActivity() {
Intent intent = new Intent(getActivity().getApplicationContext(), AllEventsActivity.class);
startActivity(intent);
}
private void launchAllSocialsActivity(int socialId) {
Intent intent = new Intent(getActivity().getApplicationContext(), AllSocialsActivity.class);
intent.putExtra("socialId",socialId);
startActivity(intent);
}
private void launchEventActivity(int eventId) {
Intent intent = new Intent(getActivity(), EventActivity.class);
intent.putExtra("eventId",eventId);
startActivity(intent);
}
} | true |
0622c8b9fe21aa31953a0ace52581b275cd98638 | Java | serhat93/ProjectManagementSystem | /ProjectManagementSystem/src/service/ProjectService.java | UTF-8 | 908 | 2.28125 | 2 | [] | no_license | package service;
import java.util.List;
import dao.ProjectDAO;
import model.Project;
public class ProjectService {
private static ProjectDAO projectDAO = new ProjectDAO();
public static void addProject(Project project) {
projectDAO.addProject(project);
}
public static Project selectProject(int id) {
return projectDAO.selectProject(id);
}
public static Project selectProject(String name) {
return projectDAO.selectProject(name);
}
public static void updateProject(Project project) {
projectDAO.updateProject(project);
}
public static void deleteProject(int id) {
projectDAO.deleteProject(id);
}
public static int countProject() {
return projectDAO.countProject();
}
public static List<Project> getProjects() {
return projectDAO.getProjects();
}
public static List<Project> getProjectsByCourse(int courseId) {
return projectDAO.getProjectsByCourse(courseId);
}
}
| true |
08040ee955089435e638c9a674ee77141c1671a8 | Java | TaintBench/cajino_baidu | /src/main/java/org/apache/http/impl/entity/LaxContentLengthStrategy.java | UTF-8 | 3,520 | 2.390625 | 2 | [
"Apache-2.0"
] | permissive | package org.apache.http.impl.entity;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpException;
import org.apache.http.HttpMessage;
import org.apache.http.ParseException;
import org.apache.http.ProtocolException;
import org.apache.http.entity.ContentLengthStrategy;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.protocol.HTTP;
public class LaxContentLengthStrategy implements ContentLengthStrategy {
public long determineLength(HttpMessage message) throws HttpException {
if (message == null) {
throw new IllegalArgumentException("HTTP message may not be null");
}
boolean strict = message.getParams().isParameterTrue(CoreProtocolPNames.STRICT_TRANSFER_ENCODING);
Header transferEncodingHeader = message.getFirstHeader("Transfer-Encoding");
Header contentLengthHeader = message.getFirstHeader("Content-Length");
int i;
if (transferEncodingHeader != null) {
try {
HeaderElement[] encodings = transferEncodingHeader.getElements();
if (strict) {
i = 0;
while (i < encodings.length) {
String encoding = encodings[i].getName();
if (encoding == null || encoding.length() <= 0 || encoding.equalsIgnoreCase(HTTP.CHUNK_CODING) || encoding.equalsIgnoreCase(HTTP.IDENTITY_CODING)) {
i++;
} else {
throw new ProtocolException(new StringBuffer().append("Unsupported transfer encoding: ").append(encoding).toString());
}
}
}
int len = encodings.length;
if (HTTP.IDENTITY_CODING.equalsIgnoreCase(transferEncodingHeader.getValue())) {
return -1;
}
if (len > 0 && HTTP.CHUNK_CODING.equalsIgnoreCase(encodings[len - 1].getName())) {
return -2;
}
if (!strict) {
return -1;
}
throw new ProtocolException("Chunk-encoding must be the last one applied");
} catch (ParseException px) {
throw new ProtocolException(new StringBuffer().append("Invalid Transfer-Encoding header value: ").append(transferEncodingHeader).toString(), px);
}
} else if (contentLengthHeader == null) {
return -1;
} else {
long contentlen = -1;
Header[] headers = message.getHeaders("Content-Length");
if (!strict || headers.length <= 1) {
i = headers.length - 1;
while (i >= 0) {
Header header = headers[i];
try {
contentlen = Long.parseLong(header.getValue());
break;
} catch (NumberFormatException e) {
if (strict) {
throw new ProtocolException(new StringBuffer().append("Invalid content length: ").append(header.getValue()).toString());
}
i--;
}
}
if (contentlen < 0) {
return -1;
}
return contentlen;
}
throw new ProtocolException("Multiple content length headers");
}
}
}
| true |
bdb495ab453e5e8164e1b3eb59f3e0f01ac8d661 | Java | cc-ohayou/cc-boot-demo | /src/main/java/com/qunhe/toilet/facade/domain/common/util/bean/BizObjInitFactory.java | UTF-8 | 1,862 | 2.9375 | 3 | [] | no_license | package com.qunhe.toilet.facade.domain.common.util.bean;
import lombok.extern.slf4j.Slf4j;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.math.BigDecimal;
/**
* @AUTHOR ZFJ
* @DATE Created on 2018/12/7
*/
@Slf4j
public class BizObjInitFactory {
private BizObjInitFactory() { }
/**
* 此方法用作初始化值操作.利用内省获取方法时,必须给出<get><set>方法
*
* @param clazz
* @param <T>
* @return
*/
public static <T> T initValue(Class<T> clazz) {
try {
T obj = clazz.newInstance();
valueSet(obj);
return obj;
} catch (Exception e) {
log.info("BizObjInitFactory method initValue transform fail exception:" + e);
}
return null;
}
/**
* 此方法用作清空类的值.利用内省获取方法时,必须给出<get><set>方法
*
* @param obj
*/
public static <T> void clearValue(T obj) {
try {
valueSet(obj);
} catch (Exception e) {
log.info("BizObjInitFactory method clearValue transform fail exception:" + e);
}
}
private static <T> void valueSet(T obj) throws Exception {
BeanInfo beaninfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beaninfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
if (BigDecimal.class.equals(property.getPropertyType())) {
property.getWriteMethod().invoke(obj, BigDecimal.ZERO);
}
if (Long.class.equals(property.getPropertyType())) {
property.getWriteMethod().invoke(obj, 0L);
}
}
}
public static void main(String[] args) {
}
}
| true |
8f8f8e321ef9340db7b77e6d157c117ddb1c4921 | Java | AlanGarduno/POO | /Citas/src/Fuentes/Datos.java | UTF-8 | 14,357 | 2.359375 | 2 | [] | no_license | package Fuentes;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Datos extends javax.swing.JFrame {
/**
* Creates new form Datos
*/
public Datos() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
txtTelefono = new javax.swing.JTextField();
txtNombre = new javax.swing.JTextField();
txtMail = new javax.swing.JTextField();
txtPlacas = new javax.swing.JTextField();
cbMarcas = new javax.swing.JComboBox<>();
cbModelo = new javax.swing.JComboBox<>();
btnAgendar = new javax.swing.JButton();
jDateChooser1 = new com.toedter.calendar.JDateChooser();
jLabel10 = new javax.swing.JLabel();
btnRegresar = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Datos Cliente");
jLabel2.setText("Datos Automovil");
jLabel3.setText("Nombre");
jLabel4.setText("Telefono");
jLabel5.setText("e-Mail");
jLabel6.setText("Marca");
jLabel7.setText("Modelo");
jLabel8.setText("Placas");
cbMarcas.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "NIssan", "Toyota", "Ford", "Chevrolet", "Lotus;Ferrari", "Lamborghini", "Lexus", "BMW", "MINI", "Porsche", "Audi" }));
cbModelo.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "1990", "1991", "1992", "1993", "1994", "1995", "1996", "1997", "1998", "1999", "2000", "2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015", "2016" }));
btnAgendar.setText("Agendar");
btnAgendar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAgendarActionPerformed(evt);
}
});
jLabel10.setText("Fecha");
btnRegresar.setText("Regresar");
btnRegresar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRegresarActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(27, 27, 27)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(570, 716, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel8)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txtPlacas, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txtMail, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel4)
.addGap(28, 28, 28)
.addComponent(txtTelefono, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel6)
.addComponent(jLabel7))
.addGap(44, 44, 44)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(cbMarcas, 0, 120, Short.MAX_VALUE)
.addComponent(cbModelo, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jDateChooser1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(107, 107, 107))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel10)
.addGap(152, 152, 152))))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(71, 71, 71)
.addComponent(btnRegresar)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnAgendar)
.addGap(258, 258, 258))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(26, 26, 26)
.addComponent(jLabel1)
.addGap(6, 6, 6)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(28, 28, 28)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(txtTelefono, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(25, 25, 25)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(txtMail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(23, 23, 23)
.addComponent(jLabel2)
.addGap(27, 27, 27)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(cbMarcas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(22, 22, 22)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(cbModelo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel8)
.addComponent(txtPlacas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jLabel10)
.addGap(18, 18, 18)
.addComponent(jDateChooser1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(105, 105, 105)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 48, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnAgendar)
.addComponent(btnRegresar))
.addGap(17, 17, 17))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnAgendarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgendarActionPerformed
// TODO add your handling code here:
Cliente c = new Cliente();
Auto a = new Auto();
Date d = jDateChooser1.getDate();
SimpleDateFormat formato = new SimpleDateFormat("dd/mm/yyyy");
String format = formato.format(d);
c.setNombre(txtNombre.getText());
c.setTelefono(txtTelefono.getText());
c.setEmail(txtMail.getText());
a.setMarca(cbMarcas.getSelectedItem().toString());
a.setModelo(cbModelo.getSelectedItem().toString());
a.setPlacas(txtPlacas.getText());
Cita cita = new Cita(c,a,format);
}//GEN-LAST:event_btnAgendarActionPerformed
private void btnRegresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRegresarActionPerformed
// TODO add your handling code here:
Menu m = new Menu();
m.setVisible(true);
dispose();
}//GEN-LAST:event_btnRegresarActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Datos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Datos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Datos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Datos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Datos().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnAgendar;
private javax.swing.JButton btnRegresar;
private javax.swing.JComboBox<String> cbMarcas;
private javax.swing.JComboBox<String> cbModelo;
private com.toedter.calendar.JDateChooser jDateChooser1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JTextField txtMail;
private javax.swing.JTextField txtNombre;
private javax.swing.JTextField txtPlacas;
private javax.swing.JTextField txtTelefono;
// End of variables declaration//GEN-END:variables
}
| true |
955e1ebfc487a8794f4cafe56436cf0dc947f69b | Java | hechuan01/ep_system | /ep_system/src/main/java/com/zx/common/utils/HttpClientUtils.java | UTF-8 | 12,513 | 2.25 | 2 | [] | no_license | package com.zx.common.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.multipart.MultipartFile;
/**
* HttpClient 工具类
*
* @author liguorui
*/
public class HttpClientUtils {
/**
* 用户代理类型
*/
private static final String USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0";
/**
* http客户短
*/
private static HttpClient httpClient;
/**
* 单个主机最大连接数
*/
private static final int CONNS_PER_HOST = 100;
/**
* 读取超时
*/
private static final int CONN_READ_TIMEOUT = 30000;
/**
* 连接超时
*/
private static final int CONN_TIMEOUT = 30000;
/**
* 连接管理池的超时时长
*/
private static final int CONN_FETCH_TIMEOUT = 30000;
/**
* 基础配置
*/
static {
HttpConnectionManager httpConnectionManager = new MultiThreadedHttpConnectionManager();
HttpConnectionManagerParams params = httpConnectionManager.getParams();
params.setDefaultMaxConnectionsPerHost(CONNS_PER_HOST);
params.setMaxTotalConnections(Integer.MAX_VALUE);
params.setConnectionTimeout(CONN_TIMEOUT);
params.setSoTimeout(CONN_READ_TIMEOUT);
httpClient = new HttpClient(httpConnectionManager);
httpClient.getParams().setConnectionManagerTimeout(CONN_FETCH_TIMEOUT);
}
/**
* 接受参数的get请求
*
* @param url 请求地址
* @param map 参数map
* @return 返回请求结果
*/
public static String doGet(String url, Map<String, String> map){
if(map != null && map.size() > 0) {
Set<Entry<String, String>> set = map.entrySet();
if (map != null && map.size() > 0) {
StringBuilder sb = new StringBuilder("?");
for (Entry<String, String> entry : set) {
sb.append(entry.getKey());
sb.append("=");
sb.append(entry.getValue());
sb.append("&");
}
sb.deleteCharAt(sb.length() - 1);
url += sb;
}
}
GetMethod get = getGettMethod(url);
get.addRequestHeader("Accept", "text/html");
String response = null;
try {
if (HttpServletResponse.SC_OK == httpClient.executeMethod(get)) {
response = get.getResponseBodyAsString();
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
get.releaseConnection();
}
return response;
}
/**
* 接受参数的get请求
*
* @param url 请求地址
* @param map 参数map
* @return 返回请求结果
*/
public static String doGet(String url, Map<String, String> map, String jsessionId){
if(map != null && map.size() > 0) {
Set<Entry<String, String>> set = map.entrySet();
if (map != null && map.size() > 0) {
StringBuilder sb = new StringBuilder("?");
for (Entry<String, String> entry : set) {
sb.append(entry.getKey());
sb.append("=");
sb.append(entry.getValue());
sb.append("&");
}
sb.deleteCharAt(sb.length() - 1);
url += sb;
}
}
GetMethod get = getGettMethod(url);
get.addRequestHeader("Cookie", "JSESSIONID="+jsessionId);
get.addRequestHeader("Accept", "text/html");
String response = null;
try {
if (HttpServletResponse.SC_OK == httpClient.executeMethod(get)) {
response = get.getResponseBodyAsString();
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
get.releaseConnection();
}
return response;
}
/**
* 发送get请求
*
* @param url 请求地址
* @return 返回byte[]
*/
public static byte[] doGet(String url){
GetMethod get = getGettMethod(url);
// get.addRequestHeader("Accept-Encoding", "gzip,deflate");
// get.addRequestHeader("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
// get.addRequestHeader("Connection", "keep-alive");
byte[] response = null;
try {
if (HttpServletResponse.SC_OK == httpClient.executeMethod(get)) {
response = get.getResponseBody();
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
get.releaseConnection();
}
return response;
}
/**
* 发送带参数的post请求
*
* @param url 请求地址
* @param params 参数map
* @return 响应结果
*/
public static String doPost(String url, Map<String, String> params){
HttpClient client = getClient(url);
PostMethod post = getPostMethod(url);
post.setRequestHeader("Accept", "application/json");
if(params != null && params.size() > 0) {
Set<Entry<String, String>> set = params.entrySet();
for (Entry<String, String> entry : set) {
post.addParameter(entry.getKey(), entry.getValue());
}
}
String response = null;
try {
client.executeMethod(post);
response = post.getResponseBodyAsString();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
post.releaseConnection();
}
return response;
}
/**
* 发送携带json参数的post请求
*
* @param url 请求地址
* @param jsonStr json数据
* @return 响应结果
*/
public static String doPostByJson(String url, String jsonStr){
PostMethod post = new PostMethod(url);
String response = null;
try {
RequestEntity requestEntity = new StringRequestEntity(jsonStr, "text/xml", "UTF-8");
post.setRequestEntity(requestEntity);
post.setRequestHeader("Accept", "application/json");
if (HttpServletResponse.SC_OK == httpClient.executeMethod(post)) {
response = post.getResponseBodyAsString();
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
post.releaseConnection();
}
return response;
}
/**
* 获取http客户端
* @param url 请求地址
* @return Http客户端
* @see
* @since 1.0
*/
private static HttpClient getClient(String url) {
HttpClient client = httpClient;
client.getHostConfiguration().setHost(url);
return client;
}
/**
* 获取get方法
*
* @param url 请求地址
* @return get方法
* @see
* @since 1.0
*/
private static GetMethod getGettMethod(String url) {
GetMethod get = new GetMethod(url);
get.setRequestHeader("User-Agent", USER_AGENT);
return get;
}
/**
* 获取post方法
*
* @param url 请求地址
* @return post方法
* @see
* @since 1.0
*/
private static PostMethod getPostMethod(String url) {
PostMethod post = new PostMethod(url);
post.setRequestHeader("User-Agent", USER_AGENT);
return post;
}
/**
* post发送文件
*
* @param url 请求地址
* @param file 文件
* @return 响应结果
*/
public static String postFile(String url, File file) {
try {
if (file.exists()) {
PostMethod post = getPostMethod(url);
FilePart part = new FilePart("file", file);
Part[] pts = {part};
post.setRequestEntity(new MultipartRequestEntity(pts, new HttpMethodParams()));
String response = null;
if (HttpServletResponse.SC_OK == httpClient.executeMethod(post)) {
response = post.getResponseBodyAsString();
}
return response;
}
else {
throw new Exception("file does not exist");
}
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 云存储上传入口
* @author wuzhangshan
* @date 2017-11-6
* @param uplaodhost 上传接口
* @param file 文件
* @param filename 服务器文件名
* @return
* @throws IOException
*/
public static String postFile(String uplaodhost, String filename, MultipartFile file) throws IOException {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody("file", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, filename);// 文件流
HttpEntity entity = builder.build();
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(uplaodhost);
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);// 执行提交
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
// 将响应内容转换为字符串
String result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
return result;
}
return null;
}
/**
* 云存储上传入口
* @author wuzhangshan
* @date 2017-11-6
* @param uplaodhost 上传接口
* @param file 文件
* @param filename 服务器文件名
* @return
* @throws IOException
*/
public static String postFile(String uplaodhost, String filename, File file) throws IOException {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody("file", new FileInputStream(file), ContentType.MULTIPART_FORM_DATA, filename);// 文件流
HttpEntity entity = builder.build();
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(uplaodhost);
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);// 执行提交
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
// 将响应内容转换为字符串
String result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
return result;
}
return null;
}
} | true |
1206bbc84c56a2ed21dfa24089894e9a4197faa9 | Java | sergehuber/graphql-tmdb-provider | /src/main/java/org/jahia/modules/tmdbprovider/graphql/api/GqlMovie.java | UTF-8 | 1,020 | 2.609375 | 3 | [] | no_license | package org.jahia.modules.tmdbprovider.graphql.api;
import com.uwetrottmann.tmdb2.entities.BaseMovie;
import graphql.annotations.annotationTypes.GraphQLDescription;
import graphql.annotations.annotationTypes.GraphQLField;
import graphql.annotations.annotationTypes.GraphQLName;
/**
* The Movie representation for the GraphQL API
*/
@GraphQLName("Movie")
public class GqlMovie {
private BaseMovie tmdbMovie;
public GqlMovie(BaseMovie tmdbMovie) {
this.tmdbMovie = tmdbMovie;
}
public BaseMovie getTmdbMovie() {
return tmdbMovie;
}
@GraphQLField
@GraphQLDescription("Retrieve the TMDB id of the Movie")
public Integer getId() {
return tmdbMovie.id;
}
@GraphQLField
@GraphQLDescription("Retrieve the name of the Movie")
public String getTitle() {
return tmdbMovie.title;
}
@GraphQLField
@GraphQLDescription("Retrieve the overview of the movie")
public String getOverview() {
return tmdbMovie.overview;
}
}
| true |
19e53c4de43cd4bd9e18ad014ddcd339c3b7d15a | Java | orhaneng/Java | /DataStructureAndAlgoritm/ArrayAndStrings/ToeplitzMatrix.java | UTF-8 | 1,185 | 3.90625 | 4 | [] | no_license | /*
* A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same
* element.
Now given an M x N matrix, return True if and only if the matrix is Toeplitz.
Example 1:
Input:
matrix = [
[1,2,3,4],
[5,1,2,3],
[9,5,1,2]
]
Output: True
Explanation:
In the above grid, the diagonals are:
"[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]".
In each diagonal all elements are the same, so the answer is True.
Example 2:
Input:
matrix = [
[1,2],
[2,2]
]
Output: False
Explanation:
The diagonal "[1, 2]" has different elements.
*/
public class ToeplitzMatrix {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[][] matrix = {
{1,2,3,4},
{5,1,2,3},
{9,5,1,2}
};
System.out.println(isToeplitzMatrix(matrix));
}
public static boolean isToeplitzMatrix(int[][] matrix) {
for(int i=1;i<matrix.length;i++){
for(int j=1;j<matrix[0].length;j++){
if(matrix[i][j]!=matrix[i-1][j-1]){
return false;
}
}
}
return true;
}
}
| true |
495b8ff7f6f1649623333ff3cd48589feeca2e30 | Java | Suyog47/CRM-Android-Project | /app/src/main/java/com/example/demoapp/SqlliteDBClasses/EventSqlliteDbService.java | UTF-8 | 3,865 | 2.625 | 3 | [] | no_license | package com.example.demoapp.SqlliteDBClasses;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;
import static android.content.ContentValues.TAG;
public class EventSqlliteDbService extends SQLiteOpenHelper {
SQLiteDatabase db;
public final static String DATABASE_NAME = "Memory.db";
public final static String TABLE_NAME = "Event_table";
public final static String COL_1 = "Year";
public final static String COL_2 = "Date";
public final static String COL_3 = "Subject";
public final static String COL_4 = "Event";
public final static String COL_5 = "Favourite";
public final static String COL_6 = "MonthNum";
public EventSqlliteDbService(Context context){
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + "(Year Integer, Date Text, Subject Text, Event Text, Favourite Boolean, MonthNum Integer)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { }
//Function for Inserting data
public String insertData(int Year, String Date, String Subject, String Event, boolean Favourite, Integer monthNum){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL_1, Year);
values.put(COL_2, Date);
values.put(COL_3, Subject);
values.put(COL_4, Event);
values.put(COL_5, Favourite);
values.put(COL_6, monthNum);
long result = db.insert(TABLE_NAME,null, values);
if(result == -1) {
return "Something Went Wrong Bro!";
}
else
return "Data Inserted!";
}
//Function to get all Years
public Cursor getYear(){
db = this.getReadableDatabase();
Cursor years = db.rawQuery("select distinct(Year) from Event_table Order By Year asc",null);
return years;
}
//Function to get Dates of selected Year
public Cursor getDates(int Year){
db = this.getReadableDatabase();
Cursor dates = db.rawQuery("select * from Event_table where Year = " + Year + " Order By MonthNum asc ",null);
return dates;
}
//Function to get sweet-mem Years
public Cursor getSweetYears() {
db = this.getReadableDatabase();
Cursor dates = db.rawQuery("select distinct(Year) from Event_table where Favourite = 1 Order By Year asc",null);
return dates;
}
//Function to get Dates of selected sweet-mem Year
public Cursor getSweetDates(int Year){
db = this.getReadableDatabase();
Cursor dates = db.rawQuery("select * from Event_table where Favourite = 1 and Year = '" + Year + "' Order By MonthNum asc",null);
return dates;
}
//Function to get Events
public Cursor getEvent(String Date){
db = this.getReadableDatabase();
Cursor Data = db.rawQuery("select * from Event_table where Date = '"+Date+"'" ,null);
return Data;
}
//Function for Updating the Event
public boolean updateEvent(String Date, String Subject, String Event, Boolean Fav){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL_3, Subject);
values.put(COL_4, Event);
values.put(COL_5, Fav);
db.update(TABLE_NAME,values,"Date = ?", new String[] {Date});
return true;
}
//Function for Deleting the Event
public Integer deleteEvent(String Date){
db = this.getWritableDatabase();
return db.delete(TABLE_NAME,"Date = ?",new String[] {Date});
}
}
| true |
9780b0d9b7a4679780ed441b4dcabeebb9883aa4 | Java | fossabot/alphaflow_dev | /sys-src/hydra/src/main/java/org/hydra/persistence/ContainerDAO.java | UTF-8 | 4,167 | 2.25 | 2 | [
"Apache-2.0"
] | permissive | /**************************************************************************
* Hydra: multi-headed version control system
* (originally for the alpha-Flow project)
* ==============================================
* Copyright (C) 2009-2012 by
* - Christoph P. Neumann (http://www.chr15t0ph.de)
* - Scott Hady
**************************************************************************
* 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.
**************************************************************************
* $Id$
*************************************************************************/
package org.hydra.persistence;
import java.io.File;
import java.io.FileInputStream;
import java.util.Scanner;
import org.hydra.core.Artifact;
import org.hydra.core.Container;
import org.hydra.core.FingerprintedElement;
import org.hydra.core.InvalidElementException;
/**
* DAO implementation for the Container element.
*
* @author Scott A. Hady
* @version 0.2
* @since 0.2
*/
public class ContainerDAO extends DataAccessObject {
/** The container. */
private final Container container;
/**
* Specialized Constructor that takes the Container on which the DAO will
* operate.
*
* @param container
* Container.
*/
public ContainerDAO(final Container container) {
this.container = container;
}
/**
* {@inheritDoc}
*
* Load the container's sub-element references from the repository.
*/
@Override
public boolean load() throws InvalidElementException {
Scanner scanner = null;
final File target = this.container.cloneRepositoryFile();
try {
scanner = new Scanner(new FileInputStream(target), "UTF-8");
while (scanner.hasNextLine()) {
final String[] splitLine = scanner.nextLine().split(
DataAccessObject.SEP_TOKEN);
if (splitLine[0].equals(Container.TOKEN)) {
this.container.addElement(new Container(new File(
this.container.cloneWorkspaceFile(), splitLine[1]),
splitLine[2]));
} else if (splitLine[0].equals(Artifact.TOKEN)) {
this.container.addElement(new Artifact(new File(
this.container.cloneWorkspaceFile(), splitLine[1]),
splitLine[2]));
}
}
return true;
} catch (final Exception e) {
this.logger.exception("Unable to Load Container [" + target + "].",
e);
return false;
} finally {
if (scanner != null) {
try {
scanner.close();
} catch (final Exception e) {
this.logger.exception("Unable to Close Scanner.", e);
}
}
}
}
/**
* {@inheritDoc}
*
* Record the current references to the repository.
*/
@Override
public boolean record() {
return this.storeContents(this.container.describe(),
this.container.cloneRepositoryFile());
}
/**
* {@inheritDoc}
*
* Retrieve a persisted state of the container from the repository and
* restore it to the workspace. No operation, not relevant for the DAO, the
* Container holds references to the artifact's which must be retrieved.
*/
@Override
public boolean retrieve() {
boolean success = true;
this.container.cloneWorkspaceFile().mkdir();
for (final FingerprintedElement e : this.container.listElements()) {
if (!e.retrieve()) {
success = false;
}
}
return success;
}
/**
* {@inheritDoc}
*
* Store the current workspace state of the container into the repository.
*/
@Override
public boolean store() {
if (this.container.cloneRepositoryFile().exists())
return true;
else {
boolean success = true;
for (final FingerprintedElement subElement : this.container
.listElements()) {
if (!subElement.store()) {
success = false;
}
}
return this.record() && success;
}
}
}
| true |
7c380c3e96f2f646897598c71f7e030b6a0064a3 | Java | Nonsouris/Chatbot-v1 | /chatter/src/muse.java | UTF-8 | 1,838 | 2.546875 | 3 | [] | no_license | import javax.swing.*;
import javax.sound.sampled.*;
import java.io.*;
import javax.swing.*;
import java.util.*;
class muse{
//music will be available to main method
static Thread music ;
// this plays music files
Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread music, Throwable ex) {
System.out.println("Uncaught exception: " + ex);
}
};
static int dialogButton;
static void mate(String dian) throws InterruptedException{
music = new Thread(dian){
//removed argument so it can run when you call start();
@Override
public void run(){
try{
/*
JFrame frame = new JFrame("Muse");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add("hello",.CENTER);
frame.pack();
frame.setVisible(true);
*/
Clip clip= null;
File in = new File(dian);
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(in);
clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
dialogButton = JOptionPane.showConfirmDialog(null, "Click Yes to stop music",
("Muse: "+dian), JOptionPane.YES_OPTION);
if(dialogButton == JOptionPane.YES_OPTION)
{
System.out.println("exiting");
clip.stop();
}
if (Client.sl.equalsIgnoreCase("stop")){
clip.stop();
}
clip.drain();
} catch (UnsupportedAudioFileException | IOException | LineUnavailableException ex) {
ex.printStackTrace();
}
}
};
music.start();
};
}
| true |
0d63980931f858e5ee0397185a38a97d5271fe31 | Java | miniufo/PhD | /src/Package/StatFactors.java | WINDOWS-1252 | 10,504 | 2.046875 | 2 | [] | no_license | package Package;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import miniufo.application.advanced.CoordinateTransformation;
import miniufo.application.basic.DynamicMethodsInCC;
import miniufo.basic.ArrayUtil;
import miniufo.database.AccessBestTrack;
import miniufo.database.AccessBestTrack.DataSets;
import miniufo.descriptor.CsmDescriptor;
import miniufo.descriptor.CtlDescriptor;
import miniufo.diagnosis.CylindricalSpatialModel;
import miniufo.diagnosis.DiagnosisFactory;
import miniufo.diagnosis.Range;
import miniufo.diagnosis.SphericalSpatialModel;
import miniufo.diagnosis.Variable;
import miniufo.diagnosis.Variable.Dimension;
import miniufo.lagrangian.Typhoon;
//
public class StatFactors{
//
private static int effectiveCount=0;
private static int effectiveTC =0;
private static float minLat= 90;
private static float minLon=360;
private static float maxLat=-90;
private static float maxLon= 0;
private static final boolean noDepress=false; // wind > 17.2 m/s
private static final boolean noLanding=false; // no land within 200 km
private static final boolean withinWNP=false; // 100 <= longitudes <= 190
private static final boolean forwardDf=true; // using forward difference to get deltaP
private static final DataSets dsets=DataSets.JMA;
private static final String respath="d:/Data/PhD/Statistics/"+dsets+"/";
private static final String tranges="time=1Jan1987-31Dec2011";
//
public static void main(String[] args){
List<Typhoon> ls=AccessBestTrack.getTyphoons(IntensityModel.getPath(dsets),tranges,dsets);
CtlDescriptor ctl=(CtlDescriptor)DiagnosisFactory.getDataDescriptor("D:/Data/ERAInterim/Data.ctl");
DiagnosisFactory df2=DiagnosisFactory.parseFile("d:/Data/ERAInterim/lsm.ctl");
CtlDescriptor ctl2=(CtlDescriptor)df2.getDataDescriptor();
Variable lsm=df2.getVariables(new Range("z(1,1)",ctl2),false,"lsm")[0];
Stat vwsstat =new Stat(new float[]{0,5,10,15, Float.MAX_VALUE},"VWS" ,respath);
Stat sststat =new Stat(new float[]{25.5f,26.5f,27.5f,28.5f,29.5f,Float.MAX_VALUE},"SST" ,respath);
Stat mpistat =new Stat(new float[]{0,10,20,30,40,50,60,70,80,90, Float.MAX_VALUE},"MPI" ,respath);
Stat efclstat=new Stat(new float[]{-20,-10,0,10,20, Float.MAX_VALUE},"EFCL",respath);
Stat efcsstat=new Stat(new float[]{-20,-10,0,10,20, Float.MAX_VALUE},"EFCS",respath);
for(Typhoon tr:ls){
DiagnosisFactory df=DiagnosisFactory.parseContent(tr.toCSMString("d:/ctl.ctl",36,28,2,0.3f,-650,850));
CsmDescriptor dd=(CsmDescriptor)df.getDataDescriptor();
float tmp;
tmp=ArrayUtil.getMin(dd.getLat()); if(tmp<minLat) minLat=tmp;
tmp=ArrayUtil.getMax(dd.getLat()); if(tmp>maxLat) maxLat=tmp;
tmp=ArrayUtil.getMin(dd.getLon()); if(tmp<minLon) minLon=tmp;
tmp=ArrayUtil.getMax(dd.getLon()); if(tmp>maxLon) maxLon=tmp;
dd.setCtlDescriptor(ctl); df.setPrinting(false);
CylindricalSpatialModel csm=new CylindricalSpatialModel(dd);
DynamicMethodsInCC dm=new DynamicMethodsInCC(csm);
CoordinateTransformation ct=new CoordinateTransformation(new SphericalSpatialModel(ctl),csm);
Variable[] vars=df.getVariables(new Range("",dd),false,"u","v","sst");
Variable[] shrs=dm.cVerticalWindShear(vars[0],vars[1]);
Variable shrsum=dm.cRadialAverage(shrs[0],1,15).anomalizeX();
Variable shrsvm=dm.cRadialAverage(shrs[1],1,15).anomalizeX();
Variable vwsm=shrsum.hypotenuse(shrsvm);
Variable sstm=dm.cRadialAverage(vars[2],1,15).anomalizeX().minusEq(273.15f);
Variable[] utvr=ct.reprojectToCylindrical(vars[0],vars[1]);
dm.cStormRelativeAziRadVelocity(tr.getUVel(),tr.getVVel(),utvr[0],utvr[1]);
utvr[0].anomalizeX(); utvr[1].anomalizeX();
Variable efclm=dm.cREFC(utvr[0],utvr[1]).averageAlong(Dimension.Y,15,24); // 500-800 km
Variable efcsm=dm.cREFC(utvr[0],utvr[1]).averageAlong(Dimension.Y, 9,18); // 300-600 km
ct=new CoordinateTransformation(new SphericalSpatialModel(ctl2),csm);
Variable lsmm=dm.cRadialAverage(ct.transToCylindricalInvariantly(lsm),1,6).anomalizeX();
boolean[] wind=noDepress? // wind >= 17.2 m/s
IntensityModel.greaterEqualThan(tr.getWinds(),17.2f):IntensityModel.newBooleans(tr.getTCount());
boolean[] lsmb=noLanding? // no land within 200 km
IntensityModel.lessThan(lsmm.getData()[0][0][0],1e-9f):IntensityModel.newBooleans(tr.getTCount());
boolean[] llon=withinWNP? // lons >= 100E
IntensityModel.greaterEqualThan(tr.getXPositions(),100):IntensityModel.newBooleans(tr.getTCount());
boolean[] rlon=withinWNP? // lons <= 190E
IntensityModel.lessEqualThan(tr.getXPositions(),190):IntensityModel.newBooleans(tr.getTCount());
boolean[] vali=IntensityModel.combination(wind,lsmb,llon,rlon);
int cc=IntensityModel.getValidCount(vali);
effectiveCount+=cc;
if(cc>0){
effectiveTC++;
if(effectiveTC%20==0) System.out.print(".");
}
float[] potential=IntensityModel.cPotential(sstm.getData()[0][0][0],tr.getWinds());
vwsstat.compileByPressure(tr, vwsm.getData()[0][0][0],vali);
sststat.compileByPressure(tr, sstm.getData()[0][0][0],vali);
mpistat.compileByPressure(tr,potential,vali);
efclstat.compileByPressure(tr,efclm.getData()[1][0][0],vali);
efcsstat.compileByPressure(tr,efcsm.getData()[1][0][0],vali);
}
printResult(vwsstat,sststat,mpistat,efclstat,efcsstat);
}
static void printResult(Stat... s){
System.out.println("\n\nwithin the region:\nlat["+
String.format("%6.2f",minLat)+" N, "+
String.format("%6.2f",maxLat)+" N]\nlon["+
String.format("%6.2f",minLon)+" E, "+
String.format("%6.2f",maxLon)+" E]\n"
);
System.out.println();
System.out.println("excluding depression : "+noDepress);
System.out.println("excluding landing : "+noLanding);
System.out.println("excluding outside WNP: "+withinWNP);
System.out.println("forward diff for delP: "+forwardDf);
System.out.println("effective TCs :"+effectiveTC);
System.out.println("effective count:"+effectiveCount);
for(int i=0,I=s.length;i<I;i++){
System.out.println(s[i]+"\n");
s[i].release();
}
}
/**
* class for statistics
*/
static final class Stat{
//
int N=0;
float[] splitor=null;
int[][] count=null; // [0] is intensify, [1] is no change and [2] is weaken
String name=null;
String path=null;
FileWriter[][] fw=null;
// contructor
public Stat(float[] sep,String vname,String fpath){
N=sep.length;
path =fpath;
name =vname;
splitor=sep;
count =new int[3][N];
fw =new FileWriter[3][N];
try{
for(int i=0;i<N;i++){
fw[0][i]=new FileWriter(path+"TXT/"+name+i+"S.txt");
fw[1][i]=new FileWriter(path+"TXT/"+name+i+"M.txt");
fw[2][i]=new FileWriter(path+"TXT/"+name+i+"W.txt");
}
}catch(IOException e){ e.printStackTrace(); System.exit(0);}
}
// add up data
public void compileByPressure(Typhoon tr,float[] data,boolean[] valid){
int len=tr.getTCount();
if(len!=data.length||len!=valid.length)
throw new IllegalArgumentException("lengths not equal");
float[] dpr=forwardDf?
IntensityModel.getChangesByForwardDiff(tr.getPressures(),1):
IntensityModel.getChangesByCentralDiff(tr.getPressures());
float[] lon=tr.getXPositions();
float[] lat=tr.getYPositions();
try{
for(int l=0;l<len;l++)
if(valid[l])
for(int i=0;i<N;i++)
if(data[l]-splitor[i]<0)
if(dpr[l]<0){
count[0][i]++;
fw[0][i].write(lon[l]+" "+lat[l]+"\n");
break;
}else if(dpr[l]==0){
count[1][i]++;
fw[1][i].write(lon[l]+" "+lat[l]+"\n");
break;
}else{
count[2][i]++;
fw[2][i].write(lon[l]+" "+lat[l]+"\n");
break;
}
}catch(IOException e){ e.printStackTrace(); System.exit(0);}
}
public void compileByWind(Typhoon tr,float[] data,boolean[] valid){
int len=tr.getTCount();
if(len!=data.length||len!=valid.length)
throw new IllegalArgumentException("lengths not equal");
float[] dwd=IntensityModel.getChangesByCentralDiff(tr.getWinds());
float[] lon=tr.getXPositions();
float[] lat=tr.getYPositions();
try{
for(int l=0;l<len;l++)
if(valid[l])
for(int i=0;i<N;i++)
if(data[l]-splitor[i]<0)
if(dwd[l]>0){
count[0][i]++;
fw[0][i].write(lon[l]+" "+lat[l]+"\n");
break;
}else if(dwd[l]==0){
count[1][i]++;
fw[1][i].write(lon[l]+" "+lat[l]+"\n");
break;
}else{
count[2][i]++;
fw[2][i].write(lon[l]+" "+lat[l]+"\n");
break;
}
}catch(IOException e){ e.printStackTrace(); System.exit(0);}
}
// close all files
public void release(){
try{
for(int i=0;i<N;i++){
fw[0][i].close();
fw[1][i].close();
fw[2][i].close();
}
}catch(IOException e){ e.printStackTrace(); System.exit(0);}
}
// print results
public String toString(){
StringBuilder sb=new StringBuilder();
sb.append("----------------statistics of "+name+"----------------\n");
sb.append(" ranging total deepen remain fill\n");
sb.append("( -, "+String.format("%5.1f",splitor[0])+"):"+
String.format("%8d",count[0][0]+count[1][0]+count[2][0])+
String.format("%9d",count[0][0])+
String.format("%9d",count[1][0])+
String.format("%8d",count[2][0])+"\n"
);
for(int i=1;i<N-1;i++)
sb.append(
"["+
String.format("%5.1f",splitor[i-1])+
", "+
String.format("%5.1f",splitor[i])+
"):"+
String.format("%8d",count[0][i]+count[1][i]+count[2][i])+
String.format("%9d",count[0][i])+
String.format("%9d",count[1][i])+
String.format("%8d",count[2][i])+"\n"
);
sb.append("["+String.format("%5.1f",splitor[N-2])+", +):"+
String.format("%8d",count[0][N-1]+count[1][N-1]+count[2][N-1])+
String.format("%9d",count[0][N-1])+
String.format("%9d",count[1][N-1])+
String.format("%8d",count[2][N-1])+"\n"
);
sb.append("-------------------------------------------------\n");
return sb.toString();
}
}
}
| true |
be8e1a37b9a8536b52b61e0cf92e0efbf2b66289 | Java | Rajarajeswari-Addanki28/java | /NewClass2.java | UTF-8 | 1,587 | 2.703125 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author SRI RAM
*/
public class matrix1 {
public static void main(String[]ar){
float a[][]={{4,7,8},{2,-1,1},{0,2,1}};
float [][]b={{1,0,0},{0,1,0},{0,0,1}};
int n=3;
for(int j=0;j<n;j++){
for(int k=0;k<n;k++){
if(k!=j){
float t=a[k][j],t1=a[j][j];
for(int i=0;i<n;i++){
a[k][i]=(t*a[j][i])-(t1*a[k][i]);
b[k][i]=t*b[j][i]-t1*b[k][i];
}
}
}
}
for(int i=0;i<n;i++){
float t=a[i][i];
for(int j=0;j<n;j++){
a[i][j]=a[i][j]/t;
b[i][j]=b[i][j]/t;
}
}
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
System.out.print(a[i][j]+" ");
}
System.out.println();
}
System.out.println("\n\n");
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
System.out.print(b[i][j]+" ");
}
System.out.println();
}
}
} | true |
80be96b62033c5a8b037bb8d0e423aa7ad019735 | Java | Hexagon-ohtu2017/ohtu-miniprojekti | /src/main/java/hextex/io/commands/FilterCommand.java | UTF-8 | 1,139 | 2.65625 | 3 | [] | no_license | /*
* 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 hextex.io.commands;
import hextex.inmemory.InMemoryReferenceDao;
import hextex.io.IO;
import hextex.matcher.QueryBuilder;
import hextex.references.Reference;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author aleksisvuoksenmaa
*/
public class FilterCommand implements Command {
private InMemoryReferenceDao dao;
private IO io;
public FilterCommand(IO io, InMemoryReferenceDao dao) {
this.io = io;
this.dao = dao;
}
@Override
public void run() {
String filterString = io.readLineAcceptEmpty("Please enter a string you want to use to filter the references: ");
if (filterString.isEmpty()) {
return;
}
dao.addFilter(filterString);
List<Reference> matches = dao.listFiltered();
io.print("References matching the filter:");
for (Reference r : matches) {
io.print("\t" + r.getEasyName());
}
}
}
| true |
cb286cfbae16a024e2eda1e5173238f0bac0e8a2 | Java | nhatnpa2508/NhatModule02 | /16. Database and ORM/BlogManager/src/main/java/com/codegym/repository/IRepository.java | UTF-8 | 457 | 1.898438 | 2 | [] | no_license | /*
*************************************
* Created by IntelliJ IDEA *
* User: Nhat *
* Email: nhatnpa2508@gmail.com *
* Date: 7/20/2019 *
* Time: 9:34 AM *
*************************************
*/
package com.codegym.repository;
import java.util.List;
public interface IRepository<T> {
List<T> findAll();
T findById(Long id);
void save(T model);
void remove(Long id);
}
| true |
adbfeb546e636da2efab890897a934b55241649d | Java | AkashDhanwani/NewsFeed | /app/src/main/java/com/akash/newsfeed/data/preferences/PreferencesHelper.java | UTF-8 | 293 | 1.71875 | 2 | [] | no_license | package com.akash.newsfeed.data.preferences;
import com.akash.newsfeed.data.network.model_classes.ApiResponse;
import java.util.List;
public interface PreferencesHelper {
void setList(String key, List<ApiResponse.Article> list);
List<ApiResponse.Article> getList(String key);
}
| true |
d7ec0ed02aa1f9665e2e2a75a5cdb8ad1aa62692 | Java | fedka27/rw-core-lient | /core/src/main/java/me/rocketwash/client/data/dto/OrderStats.java | UTF-8 | 1,068 | 2.015625 | 2 | [] | no_license | package me.rocketwash.client.data.dto;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
public class OrderStats implements Serializable {
@SerializedName("total_count")
private int total_count;
@SerializedName("total_paid_with_bonuses")
private float total_paid_with_bonuses;
@SerializedName("total_discount_received")
private float total_discount_received;
public int getTotal_count() {
return total_count;
}
public void setTotal_count(int total_count) {
this.total_count = total_count;
}
public float getTotal_paid_with_bonuses() {
return total_paid_with_bonuses;
}
public void setTotal_paid_with_bonuses(float total_paid_with_bonuses) {
this.total_paid_with_bonuses = total_paid_with_bonuses;
}
public float getTotal_discount_received() {
return total_discount_received;
}
public void setTotal_discount_received(float total_discount_received) {
this.total_discount_received = total_discount_received;
}
}
| true |
978b158de9e6eaba859d84d83aa6a0235b91e338 | Java | VaishnaviKadukar/Covid-19-HospitalManagementSystem | /po/BedmanagePo.java | UTF-8 | 368 | 1.820313 | 2 | [] | no_license |
package mgmtsys.po;
public class BedmanagePo {
String tGeneral;
String tIcu;
public String gettIcu() {
return tIcu;
}
public void settIcu(String tIcu) {
this.tIcu = tIcu;
}
public String gettGeneral() {
return tGeneral;
}
public void settGeneral(String tGeneral) {
this.tGeneral = tGeneral;
}
}
| true |
985beb8c466853e54d364a5b1a911f9f3f3252c5 | Java | pankaite/Design-pattern | /FactoryPattern/FactoryPatternDemo.java | UTF-8 | 378 | 3.078125 | 3 | [] | no_license | package com.kate.FactoryPattern;
public class FactoryPatternDemo {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
Shape cShape = shapeFactory.getShape("circle");
cShape.draw();
Shape sShape = shapeFactory.getShape("square");
sShape.draw();
Shape rShape = shapeFactory.getShape("rectangle");
rShape.draw();
}
}
| true |
773dd26097418b59722e70dc06709e76ca49ac58 | Java | kmeng01/csa-labs | /Unit_07/SportsScores/SportsReport.java | UTF-8 | 2,537 | 3.703125 | 4 | [] | no_license | /**
* The SportsReport Class provides functionality to parse the winner,
* loser, winning score, and losing score from a natural text string
* and display it in an aligned format.
*
* @author Kevin Meng
* Collaborators: None
* Teacher Name: Mrs. Ishman
* Period: 7
* Due Date: 12/03/2018
*/
public class SportsReport
{
/** Names of the winning and losing teams */
private String winner;
private String loser;
/** the winning and losing scores */
private int winningScore;
private int losingScore;
/** Constructs a SportsReport using the information in score
* @param score contains winner, loser, and scores in the format:
* <winner> beat <loser> by a score of <winning score> to <losing score>
*/
public SportsReport(String score)
{
extractInformation(score);
}
/** Changes the sports scoring information
* @param score contains winner, loser, and scores in the format:
* <winner> beat <loser> by a score of <winning score> to <losing score>
*/
public void changeScoringInfo(String score)
{
extractInformation(score);
}
/**
* Returns name of winner
* @return name of winner
*/
public String getWinner()
{
return winner;
}
/**
* Returns name of loser
* @return name of loser
*/
public String getLoser()
{
return loser;
}
/**
* Returns score of winner
* @return score of winner
*/
public int getWinningScore()
{
return winningScore;
}
/**
* Returns score of loser
* @return score of loser
*/
public int getLosingScore()
{
return losingScore;
}
/**
* Returns difference of winning and losing scores
* @return difference of scores
*/
public int getScoreDifference()
{
return winningScore - losingScore;
}
@Override
public String toString()
{
return String.format("%-25s %4d, %-25s %4d", winner, winningScore, loser, losingScore);
}
/**
* Extracts winner, loser, winningScore, losingScore from a natural text string
* @param score natural text string
*/
private void extractInformation(String score)
{
String[] tokens = score.split(" beat ");
winner = tokens[0];
tokens = tokens[1].split(" by a score of ");
loser = tokens[0];
winningScore = Integer.parseInt(tokens[1].split(" to ")[0]);
losingScore = Integer.parseInt(tokens[1].split(" to ")[1]);
}
} | true |
94e2cc63d71f4279b282f9c8074429f3d7863fee | Java | Ruidaimeng/spring-cloud-mult | /client/src/main/java/com/imooc/cloud/client/message/SinkReceiver.java | UTF-8 | 567 | 2.359375 | 2 | [] | no_license | package com.imooc.cloud.client.message;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.cloud.stream.messaging.Sink;
/**
* 采用Sink作为默认的消息订阅通道
*
* @author ruimeng
* @create 2018-10-10 20:14
**/
@EnableBinding(value = {Sink.class})
public class SinkReceiver {
@StreamListener(Sink.INPUT)
public void receive(Object payload) {
System.out.println("Received from default channel :"+ payload.toString());
}
}
| true |
3536bfde1e2308b526916d639492de1ab9f89e81 | Java | Taras-910/topjava_graduation | /src/main/java/ru/javawebinar/topjava/web/RootController.java | UTF-8 | 504 | 1.78125 | 2 | [] | no_license | package ru.javawebinar.topjava.web;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import springfox.documentation.annotations.ApiIgnore;
@ApiIgnore
@Controller
public class RootController {
public final Logger log = LoggerFactory.getLogger(getClass());
@GetMapping("/")
public String root() {
log.info("root");
return "redirect:swagger-ui.html";
}
}
| true |
133330d26bafaa79aca1c77d20869014333d6685 | Java | zhongxingyu/Seer | /Diff-Raw-Data/21/21_28654fbd5d119abae90049bb81c421dec4d9eacb/Lcom4BlocksBridge/21_28654fbd5d119abae90049bb81c421dec4d9eacb_Lcom4BlocksBridge_s.java | UTF-8 | 4,652 | 1.898438 | 2 | [] | no_license | /*
* Sonar, open source software quality management tool.
* Copyright (C) 2009 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* Sonar is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* Sonar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Sonar; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.plugins.squid.bridges;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.api.measures.Measure;
import org.sonar.api.measures.PersistenceMode;
import org.sonar.api.resources.Resource;
import org.sonar.java.bytecode.asm.AsmField;
import org.sonar.java.bytecode.asm.AsmMethod;
import org.sonar.java.bytecode.asm.AsmResource;
import org.sonar.squid.api.SourceFile;
import org.sonar.squid.measures.Metric;
import java.util.*;
public class Lcom4BlocksBridge extends Bridge {
protected Lcom4BlocksBridge() {
super(true);
}
@Override
public void onFile(SourceFile squidFile, Resource sonarFile) {
List<Set<AsmResource>> blocks = (List<Set<AsmResource>>) squidFile.getData(Metric.LCOM4_BLOCKS);
// This measure includes AsmResource objects and it is used only by this bridge, so
// it can be removed from memory.
squidFile.removeMeasure(Metric.LCOM4_BLOCKS);
if (blocks != null && blocks.size() > 0) {
Measure measure = new Measure(CoreMetrics.LCOM4_BLOCKS, serialize(blocks));
measure.setPersistenceMode(PersistenceMode.DATABASE);
context.saveMeasure(sonarFile, measure);
}
}
protected void sortBlocks(List<Set<AsmResource>> blocks) {
Collections.sort(blocks, new Comparator<Set>() {
public int compare(Set set1, Set set2) {
return set1.size() - set2.size();
}
});
}
protected String serialize(List<Set<AsmResource>> blocks) {
sortBlocks(blocks);
StringBuilder sb = new StringBuilder();
sb.append('[');
for (int indexBlock = 0; indexBlock < blocks.size(); indexBlock++) {
blocks.get(indexBlock);
Set<AsmResource> block = blocks.get(indexBlock);
if (block.size() > 0) {
if (indexBlock > 0) {
sb.append(',');
}
sb.append('[');
serializeBlock(block, sb);
sb.append(']');
}
}
sb.append(']');
return sb.toString();
}
private void serializeBlock(Set<AsmResource> block, StringBuilder sb) {
List<AsmResource> sortedResources = sortResourcesInBlock(block);
int indexResource = 0;
for (AsmResource resource : sortedResources) {
if (indexResource++ > 0) {
sb.append(',');
}
serializeResource(resource, sb);
}
}
private void serializeResource(AsmResource resource, StringBuilder sb) {
sb.append("{\"q\":\"");
sb.append(toQualifier(resource));
sb.append("\",\"n\":\"");
sb.append(resource.toString());
sb.append("\"}");
}
protected List<AsmResource> sortResourcesInBlock(Set<AsmResource> block) {
List<AsmResource> result = new ArrayList<AsmResource>();
result.addAll(block);
Collections.sort(result, new Comparator<AsmResource>() {
public int compare(AsmResource asmResource1, AsmResource asmResource2) {
int result = compareType(asmResource1, asmResource2);
if (result == 0) {
result = asmResource1.toString().compareTo(asmResource2.toString());
}
return result;
}
private int compareType(AsmResource asmResource1, AsmResource asmResource2) {
if (asmResource1 instanceof AsmField) {
return (asmResource2 instanceof AsmField ? 0 : -1);
}
return (asmResource2 instanceof AsmMethod ? 0 : 1);
}
});
return result;
}
private static String toQualifier(AsmResource asmResource) {
if (asmResource instanceof AsmField) {
return Resource.QUALIFIER_FIELD;
}
if (asmResource instanceof AsmMethod) {
return Resource.QUALIFIER_METHOD;
}
throw new IllegalArgumentException("Wrong ASM resource: " + asmResource.getClass());
}
}
| true |
97a9b3576656d5af233c46b1a9a6dcc1498f5687 | Java | JavaMrYang/lambda | /src/com/company/Main.java | UTF-8 | 946 | 3.5625 | 4 | [] | no_license | package com.company;
import java.util.*;
public class Main {
public static void main(String[] args) {
// write your code here
List<String> list = new ArrayList<>();
list.add("jack");
list.add("mack");
list.add("facker");
list.forEach(item -> System.out.println(item));
Map map = new HashMap<>();
map.put("a", "abc");
map.put("b", "fsg");
map.forEach((k, v) -> System.out.println("key:" + k + " value:" + v));
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
numbers.stream().filter(e -> e % 2 == 0).forEach(System.out::println);
List<String> listStr = Arrays.asList(new String[]{"c", "b", "a", "g", "e"});
Collections.sort(listStr, (str1, str2) -> str1.compareTo(str2));
listStr.forEach((str) -> System.out.print(str + ","));
System.out.println(String.format("event%06d", 1));
}
}
| true |
f04da22eab61e43d10a1cfd059e157890b22601f | Java | swarkad/share | /Elshare-Android/app/src/main/java/datamodel/commertial_voltage.java | UTF-8 | 550 | 2.25 | 2 | [] | no_license | package datamodel;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class commertial_voltage
{
@SerializedName("voltage")
@Expose
private String voltage;
public String getVoltageComSocketCommertial() {
return voltage;
}
public void setVoltageComSocketCommertial(String voltage) {
this.voltage = voltage;
}
public commertial_voltage withVoltageComSocketCommertial(String voltage) {
this.voltage = voltage;
return this;
}
}
| true |
eb3c806fa3ff61d5fab974969acf6e7c317bd11b | Java | Rexru101/CheeseburgerNoCheese | /app/src/main/java/com/rexru/cheeseburgernocheese/IngredientCategory.java | UTF-8 | 3,091 | 2.609375 | 3 | [] | no_license | package com.rexru.cheeseburgernocheese;
import java.util.List;
/*
* Created by Rexru101 on 5/2/2015.
*/
public enum IngredientCategory
{
// OIL (IngredientDetails.TRUFFLE_OIL, IngredientDetails.BUTTER, IngredientDetails.OLIVE_OIL, IngredientDetails.GRAPESEED_OIL),
// DAIRY (IngredientDetails.CHEESE, IngredientDetails.EGGS, IngredientDetails.MILK),
// MEAT (IngredientDetails.BACON, IngredientDetails.CHICKEN, IngredientDetails.STEAK, IngredientDetails.TOFURKY),
// GRAIN (IngredientDetails.CORN, IngredientDetails.LENTILS, IngredientDetails.OATS, IngredientDetails.PASTA, IngredientDetails.QUINOA,
// IngredientDetails.RICE, IngredientDetails.WHOLE_WHEAT_PASTA),
// FRUIT (IngredientDetails.ORANGE, IngredientDetails.POMEGRANATE, IngredientDetails.STRAWBERRY, IngredientDetails.TOMATO,
// IngredientDetails.APPLE, IngredientDetails.AVOCADO, IngredientDetails.BANANA, IngredientDetails.BLUEBERRY, IngredientDetails.GRAPES,
// IngredientDetails.LEMON, IngredientDetails.LIME),
// VEGETABLE (IngredientDetails.ASPARAGUS, IngredientDetails.BROCCOLI, IngredientDetails.CARROTS, IngredientDetails.LETTUCE,
// IngredientDetails.MUSHROOM, IngredientDetails.SPINACH, IngredientDetails.VEGGIE_PATTY),
// ALL;
OIL,
DAIRY,
MEAT,
GRAIN,
FRUIT,
VEGETABLE,
ALL;
//List<IngredientDetails> categoryContains;
IngredientCategory()
{
}
/*
IngredientCategory(IngredientDetails id1, IngredientDetails id2, IngredientDetails id3, IngredientDetails id4)
{
categoryContains.add(id1);
categoryContains.add(id2);
categoryContains.add(id3);
categoryContains.add(id4);
}
IngredientCategory(IngredientDetails id1, IngredientDetails id2, IngredientDetails id3)
{
categoryContains.add(id1);
categoryContains.add(id2);
categoryContains.add(id3);
}
IngredientCategory(IngredientDetails id1, IngredientDetails id2, IngredientDetails id3, IngredientDetails id4,
IngredientDetails id5, IngredientDetails id6, IngredientDetails id7)
{
categoryContains.add(id1);
categoryContains.add(id2);
categoryContains.add(id3);
categoryContains.add(id4);
categoryContains.add(id5);
categoryContains.add(id6);
categoryContains.add(id7);
}
IngredientCategory(IngredientDetails id1, IngredientDetails id2, IngredientDetails id3, IngredientDetails id4,
IngredientDetails id5, IngredientDetails id6, IngredientDetails id7, IngredientDetails id8,
IngredientDetails id9, IngredientDetails id10, IngredientDetails id11)
{
categoryContains.add(id1);
categoryContains.add(id2);
categoryContains.add(id3);
categoryContains.add(id4);
categoryContains.add(id5);
categoryContains.add(id6);
categoryContains.add(id7);
categoryContains.add(id8);
categoryContains.add(id9);
categoryContains.add(id10);
categoryContains.add(id11);
}*/
} | true |
59465461cf452fe6526157c1ea28a2d360f44e9c | Java | lw193593/KnowWeather | /app/src/main/java/com/silencedut/knowweather/repository/db/Weather.java | UTF-8 | 345 | 1.84375 | 2 | [] | no_license | package com.silencedut.knowweather.repository.db;
import android.arch.persistence.room.Entity;
import android.support.annotation.NonNull;
/**
* Created by SilenceDut on 2018/1/15 .
*/
@Entity(tableName = "weather",primaryKeys = {"cityId"})
public class Weather {
@NonNull
public String cityId ="";
public String weatherJson;
}
| true |
6cd7212e26477a83b6e3da16a2af4ce10d89436d | Java | inalireza/rusefi | /java_console/ui/src/main/java/com/rusefi/ui/widgets/test/AnyCommandTest.java | UTF-8 | 1,364 | 2.46875 | 2 | [] | no_license | package com.rusefi.ui.widgets.test;
import com.rusefi.ui.widgets.AnyCommand;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Andrey Belomutskiy, (c) 2013-2020
* 3/9/2017.
*/
public class AnyCommandTest {
private static String prepareCommand(String rawCommand) {
return AnyCommand.prepareCommand(rawCommand, null);
}
@Test
public void testNoExceptionIsThrown() {
assertEquals("eval \"2 2 +\"", AnyCommand.prepareEvalCommand("eval \"2 2 +\""));
}
@Test
public void testUnquote() {
assertEquals("1 2 3", AnyCommand.unquote(" \"1 2 3\" "));
}
@Test
public void testPrepareEvalCommand() {
assertEquals("rpn_eval \"2 3 +\"", prepareCommand("eval \"2 + 3\" "));
}
@Test
public void testSetFSIOexpression() {
// todo: parameter order needs to be in postfix form
assertEquals("set_rpn_expression 1 \"rpm fsio_setting 0 >\"", prepareCommand("set_fsio_expression 1 \"rpm > fsio_setting 0\""));
}
@Test
public void testSetFSIOexpressionWithFunnyQuotes() {
assertEquals("tps > 10", AnyCommand.unquote("\"tps > 10\""));
assertEquals("tps > 10", AnyCommand.unquote("\u201Ctps > 10\u201D"));
assertEquals("set_rpn_expression 1 \"tps 10 >\"", prepareCommand("Set_fsio_expression 1 \u201Ctps > 10\u201D"));
}
}
| true |
da43ebf11351ae3e19a23840cad9e6d27249e95c | Java | Frozenhel/fitbitHealthModules | /fitbitmodule/src/main/java/com/anext/fitbitmodule/model/food/NutritionalValues.java | UTF-8 | 1,271 | 2.75 | 3 | [] | no_license | package com.anext.fitbitmodule.model.food;
/**
* Created by Jiri on 02/08/17.
*/
public class NutritionalValues {
private float calories;
private float carbs;
private float fat;
private float fiber;
private float protein;
private float sodium;
public float getCalories() {
return calories;
}
public float getCarbs() {
return carbs;
}
public float getFat() {
return fat;
}
public float getFiber() {
return fiber;
}
public float getProtein() {
return protein;
}
public float getSodium() {
return sodium;
}
public NutritionalValues(float calories, float carbs, float fat, float fiber, float protein, float sodium) {
this.calories = calories;
this.carbs = carbs;
this.fat = fat;
this.fiber = fiber;
this.protein = protein;
this.sodium = sodium;
}
@Override
public String toString() {
return "NutritionalValues{" +
"calories=" + calories +
", carbs=" + carbs +
", fat=" + fat +
", fiber=" + fiber +
", protein=" + protein +
", sodium=" + sodium +
'}';
}
}
| true |
17138b03a74f950d8bd7738165b51042f67c8474 | Java | BioKNIME/plantcell | /Web Services/src/compbio/data/msa/_01/_12/_2010/SequenceAnnotation.java | UTF-8 | 8,891 | 1.578125 | 2 | [
"Apache-2.0"
] | permissive |
package compbio.data.msa._01._12._2010;
import java.util.List;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;
/**
* This class was generated by the JAX-WS RI.
* JAX-WS RI 2.1.6 in JDK 6
* Generated source version: 2.1
*
*/
@WebService(name = "SequenceAnnotation", targetNamespace = "http://msa.data.compbio/01/12/2010/")
@XmlSeeAlso({
ObjectFactory.class
})
public interface SequenceAnnotation {
/**
*
* @param jobId
* @return
* returns compbio.data.msa._01._12._2010.ScoreManager
* @throws ResultNotAvailableException_Exception
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "getAnnotation", targetNamespace = "http://msa.data.compbio/01/12/2010/", className = "compbio.data.msa._01._12._2010.GetAnnotation")
@ResponseWrapper(localName = "getAnnotationResponse", targetNamespace = "http://msa.data.compbio/01/12/2010/", className = "compbio.data.msa._01._12._2010.GetAnnotationResponse")
public ScoreManager getAnnotation(
@WebParam(name = "jobId", targetNamespace = "")
String jobId)
throws ResultNotAvailableException_Exception
;
/**
*
* @param fastaSequences
* @return
* returns java.lang.String
* @throws JobSubmissionException_Exception
* @throws UnsupportedRuntimeException_Exception
* @throws LimitExceededException_Exception
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "analize", targetNamespace = "http://msa.data.compbio/01/12/2010/", className = "compbio.data.msa._01._12._2010.Analize")
@ResponseWrapper(localName = "analizeResponse", targetNamespace = "http://msa.data.compbio/01/12/2010/", className = "compbio.data.msa._01._12._2010.AnalizeResponse")
public String analize(
@WebParam(name = "fastaSequences", targetNamespace = "")
List<FastaSequence> fastaSequences)
throws JobSubmissionException_Exception, LimitExceededException_Exception, UnsupportedRuntimeException_Exception
;
/**
*
* @param fastaSequences
* @param options
* @return
* returns java.lang.String
* @throws JobSubmissionException_Exception
* @throws WrongParameterException_Exception
* @throws UnsupportedRuntimeException_Exception
* @throws LimitExceededException_Exception
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "customAnalize", targetNamespace = "http://msa.data.compbio/01/12/2010/", className = "compbio.data.msa._01._12._2010.CustomAnalize")
@ResponseWrapper(localName = "customAnalizeResponse", targetNamespace = "http://msa.data.compbio/01/12/2010/", className = "compbio.data.msa._01._12._2010.CustomAnalizeResponse")
public String customAnalize(
@WebParam(name = "fastaSequences", targetNamespace = "")
List<FastaSequence> fastaSequences,
@WebParam(name = "options", targetNamespace = "")
List<Option> options)
throws JobSubmissionException_Exception, LimitExceededException_Exception, UnsupportedRuntimeException_Exception, WrongParameterException_Exception
;
/**
*
* @param fastaSequences
* @param preset
* @return
* returns java.lang.String
* @throws WrongParameterException_Exception
* @throws JobSubmissionException_Exception
* @throws UnsupportedRuntimeException_Exception
* @throws LimitExceededException_Exception
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "presetAnalize", targetNamespace = "http://msa.data.compbio/01/12/2010/", className = "compbio.data.msa._01._12._2010.PresetAnalize")
@ResponseWrapper(localName = "presetAnalizeResponse", targetNamespace = "http://msa.data.compbio/01/12/2010/", className = "compbio.data.msa._01._12._2010.PresetAnalizeResponse")
public String presetAnalize(
@WebParam(name = "fastaSequences", targetNamespace = "")
List<FastaSequence> fastaSequences,
@WebParam(name = "preset", targetNamespace = "")
Preset preset)
throws JobSubmissionException_Exception, LimitExceededException_Exception, UnsupportedRuntimeException_Exception, WrongParameterException_Exception
;
/**
*
* @param jobId
* @return
* returns compbio.data.msa._01._12._2010.JobStatus
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "getJobStatus", targetNamespace = "http://msa.data.compbio/01/12/2010/", className = "compbio.data.msa._01._12._2010.GetJobStatus")
@ResponseWrapper(localName = "getJobStatusResponse", targetNamespace = "http://msa.data.compbio/01/12/2010/", className = "compbio.data.msa._01._12._2010.GetJobStatusResponse")
public JobStatus getJobStatus(
@WebParam(name = "jobId", targetNamespace = "")
String jobId);
/**
*
* @param jobId
* @return
* returns boolean
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "cancelJob", targetNamespace = "http://msa.data.compbio/01/12/2010/", className = "compbio.data.msa._01._12._2010.CancelJob")
@ResponseWrapper(localName = "cancelJobResponse", targetNamespace = "http://msa.data.compbio/01/12/2010/", className = "compbio.data.msa._01._12._2010.CancelJobResponse")
public boolean cancelJob(
@WebParam(name = "jobId", targetNamespace = "")
String jobId);
/**
*
* @param position
* @param jobId
* @return
* returns compbio.data.msa._01._12._2010.ChunkHolder
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "pullExecStatistics", targetNamespace = "http://msa.data.compbio/01/12/2010/", className = "compbio.data.msa._01._12._2010.PullExecStatistics")
@ResponseWrapper(localName = "pullExecStatisticsResponse", targetNamespace = "http://msa.data.compbio/01/12/2010/", className = "compbio.data.msa._01._12._2010.PullExecStatisticsResponse")
public ChunkHolder pullExecStatistics(
@WebParam(name = "jobId", targetNamespace = "")
String jobId,
@WebParam(name = "position", targetNamespace = "")
long position);
/**
*
* @return
* returns compbio.data.msa._01._12._2010.LimitsManager
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "getLimits", targetNamespace = "http://msa.data.compbio/01/12/2010/", className = "compbio.data.msa._01._12._2010.GetLimits")
@ResponseWrapper(localName = "getLimitsResponse", targetNamespace = "http://msa.data.compbio/01/12/2010/", className = "compbio.data.msa._01._12._2010.GetLimitsResponse")
public LimitsManager getLimits();
/**
*
* @param presetName
* @return
* returns compbio.data.msa._01._12._2010.Limit
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "getLimit", targetNamespace = "http://msa.data.compbio/01/12/2010/", className = "compbio.data.msa._01._12._2010.GetLimit")
@ResponseWrapper(localName = "getLimitResponse", targetNamespace = "http://msa.data.compbio/01/12/2010/", className = "compbio.data.msa._01._12._2010.GetLimitResponse")
public Limit getLimit(
@WebParam(name = "presetName", targetNamespace = "")
String presetName);
/**
*
* @return
* returns compbio.data.msa._01._12._2010.RunnerConfig
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "getRunnerOptions", targetNamespace = "http://msa.data.compbio/01/12/2010/", className = "compbio.data.msa._01._12._2010.GetRunnerOptions")
@ResponseWrapper(localName = "getRunnerOptionsResponse", targetNamespace = "http://msa.data.compbio/01/12/2010/", className = "compbio.data.msa._01._12._2010.GetRunnerOptionsResponse")
public RunnerConfig getRunnerOptions();
/**
*
* @return
* returns compbio.data.msa._01._12._2010.PresetManager
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "getPresets", targetNamespace = "http://msa.data.compbio/01/12/2010/", className = "compbio.data.msa._01._12._2010.GetPresets")
@ResponseWrapper(localName = "getPresetsResponse", targetNamespace = "http://msa.data.compbio/01/12/2010/", className = "compbio.data.msa._01._12._2010.GetPresetsResponse")
public PresetManager getPresets();
}
| true |
48b02956e771776727f01c2bdee997b77ba78e21 | Java | zp253908058/course | /Course/app/src/main/java/com/zp/course/util/ObjectUtils.java | UTF-8 | 2,113 | 2.953125 | 3 | [] | no_license | package com.zp.course.util;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Class description:
*
* @author zp
* @version 1.0
* @see ObjectUtils
* @since 2019/3/12
*/
public class ObjectUtils {
public static List<Field> getDeclaredFields(Object object) {
return Arrays.asList(object.getClass().getDeclaredFields());
}
public static List<Field> getAllDeclaredFields(Object object) {
List<Field> list = new ArrayList<>();
Class clz = object.getClass();
if (clz == Object.class) {
throw new IllegalArgumentException("object can not be instance of Object.class");
}
Field[] fields = clz.getDeclaredFields();
do {
if (Validator.isNotEmpty(fields)) {
addToList(list, fields);
}
clz = clz.getSuperclass();
if (clz == null) {
break;
}
} while (clz != Object.class);
return list;
}
private static <T> void addToList(List<T> list, T[] ts) {
Collections.addAll(list, ts);
}
public static String toString(Object o) {
return Validator.isNull(o) ? "null" : o.toString();
}
public static boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}
public static boolean contains(String a, String b) {
if (Validator.isEmpty(b)) {
return true;
}
return Validator.isNotNull(a) && a.toLowerCase().contains(b.toLowerCase());
}
public static String getString(Object o) {
if (o == null) {
return "";
}
return o.toString();
}
public static String concat(Object... objects) {
String result = "";
if (Validator.isNotEmpty(objects)) {
for (Object object : objects) {
String value = object == null ? "" : object.toString();
result = result.concat(value);
}
}
return result;
}
}
| true |