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
fac0e9881e3dfd604e35ef40086b20563ee9f6e7
Java
Aniket0903/ProjectAutomation
/qsp/src/HybridFramework/Actitimevalidlogin.java
UTF-8
532
1.992188
2
[]
no_license
package HybridFramework; import java.io.IOException; public class Actitimevalidlogin extends BaseTest { public static void main(String[] args) throws IOException, InterruptedException { BaseTest bt = new BaseTest(); bt.openBrowser(); Flib flib = new Flib(); pomClass pom = new pomClass(driver); String username = flib.getproperties(PROPERTIES_PATH,"un"); String password = flib.getproperties(PROPERTIES_PATH,"psw"); pom.loginprocess(username, password); bt.closebrowser(); } }
true
da414a9cc159bc43758dc94caf8c230b249cfbb4
Java
dzmaj/FinalProject
/JPADoggieMeetup/src/main/java/com/skilldistillery/doggiemeetup/entities/Location.java
UTF-8
2,158
2.421875
2
[]
no_license
package com.skilldistillery.doggiemeetup.entities; import java.time.LocalDateTime; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @Entity public class Location { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private Double lat; private Double lng; @Column(name = "point_time") private LocalDateTime pointTime; @JsonIgnore @OneToOne @JoinColumn(name = "user_id") private User user; @JsonIgnoreProperties({"locations"}) @ManyToOne @JoinColumn(name = "route_id") private Route route; public Location() { super(); } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public Route getRoute() { return route; } public void setRoute(Route route) { this.route = route; } public int getId() { return id; } public void setId(int id) { this.id = id; } public Double getLat() { return lat; } public void setLat(Double lat) { this.lat = lat; } public Double getLng() { return lng; } public void setLng(Double lng) { this.lng = lng; } public LocalDateTime getPointTime() { return pointTime; } public void setPointTime(LocalDateTime pointTime) { this.pointTime = pointTime; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + id; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Location other = (Location) obj; if (id != other.id) return false; return true; } @Override public String toString() { return "Location [id=" + id + ", lat=" + lat + ", lng=" + lng + ", pointTime=" + pointTime + ", user=" + user + ", route=" + route + "]"; } }
true
796eeb105d51dd1db6d28de0db0e76dc82170a0c
Java
kenvifire/java8demo
/src/main/java/com.kenvifire/LazyStreams.java
UTF-8
894
3.4375
3
[]
no_license
package com.kenvifire; import java.util.Arrays; import java.util.List; /** * Created by hannahzhang on 15/5/31. */ public class LazyStreams { public static void main(String[] args){ List<String> names = Arrays.asList("Brad","Kate", "Kim","Jack","Joe","Mike","Susan","George", "Robert","Julia","Parker","Benson"); final String firstNameWith3Letters = names.stream() .filter( name -> length(name) == 3) .map(name -> toUpper(name)) .findFirst() .get(); } private static int length(final String name){ System.out.println("getting length for " + name); return name.length(); } private static String toUpper(final String name){ System.out.println("converting to uppercase" + name); return name.toUpperCase(); } }
true
a4fdb5ac0159e7275ea1c4a6f232dc9be869d162
Java
pnthang01/j-common-util
/oracle-util/src/main/java/com/etybeno/oracle/config/OracleConfiguration.java
UTF-8
3,220
2.3125
2
[]
no_license
package com.etybeno.oracle.config; import com.etybeno.common.config.BaseConfiguration; import org.apache.commons.configuration2.Configuration; import org.apache.commons.configuration2.FileBasedConfiguration; import org.apache.commons.configuration2.PropertiesConfiguration; import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder; import org.apache.commons.configuration2.builder.fluent.Parameters; import org.apache.commons.configuration2.convert.DefaultListDelimiterHandler; import org.apache.commons.configuration2.ex.ConfigurationException; import java.io.Serializable; import java.sql.Connection; import java.sql.SQLException; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * Created by thangpham on 29/12/2017. */ public class OracleConfiguration implements Serializable { private static OracleConfiguration _instance = null; public synchronized static OracleConfiguration _load() throws ConfigurationException { if (null == _instance) _instance = new OracleConfiguration(); return _instance; } private Configuration config = null; private ConcurrentMap<String, DatabasePoolConnectionSource> connectionMap; public OracleConfiguration() throws ConfigurationException { Parameters params = new Parameters(); FileBasedConfigurationBuilder<FileBasedConfiguration> builder = new FileBasedConfigurationBuilder<FileBasedConfiguration>(PropertiesConfiguration.class) .configure(params.properties() .setFileName(BaseConfiguration.getDatabaseConfigFile()) .setListDelimiterHandler(new DefaultListDelimiterHandler(','))); config = builder.getConfiguration(); connectionMap = new ConcurrentHashMap(); } public Connection getConnection(String sourceName) throws SQLException { DatabasePoolConnectionSource dataSource = connectionMap.get(sourceName); if (null == dataSource) { String sourceProp = "data.database." + sourceName; dataSource = new DatabasePoolConnectionSource(); dataSource.setHost(config.get(String.class, sourceProp + ".host")); dataSource.setPort(config.get(Integer.class, sourceProp + ".port")); dataSource.setDbdriverclasspath(config.get(String.class, sourceProp + ".dbdriverClasspath")); dataSource.setDatabase(config.get(String.class, sourceProp + ".database")); dataSource.setUsername(config.get(String.class, sourceProp + ".username")); dataSource.setPassword(config.get(String.class, sourceProp + ".password")); dataSource.setMinLimit(config.get(String.class, sourceProp + ".MinLimit")); dataSource.setMaxLimit(config.get(String.class, sourceProp + ".MaxLimit")); dataSource.setInactiveTimeout(config.get(String.class, sourceProp + ".InactivityTimeout")); dataSource.setAbandoneTimeout(config.get(String.class, sourceProp + ".AbandonedConnectionTimeout")); dataSource.init(); connectionMap.put(sourceName, dataSource); } return dataSource.getConnection(); } }
true
9791e4690f49f140948c2a54dcc1790e1e51b082
Java
devMonkey87/oracleDBExerciseAndJWT_TSC
/src/main/java/com/example/implementacionApiRest/entity/Funcion.java
UTF-8
1,466
1.8125
2
[]
no_license
package com.example.implementacionApiRest.entity; import java.io.Serializable; import java.sql.Date; import java.util.ArrayList; import java.util.List; import javax.persistence.Column; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonManagedReference; import lombok.Data; @Data @Entity @Table(name = "COM_FUNCIONES") public class Funcion implements Serializable { /** * */ private static final long serialVersionUID = 1L; @EmbeddedId private FuncionId id; @ManyToOne @JoinColumn(name = "menu",insertable = false, updatable = false) @JsonIgnoreProperties("permisos") private Menu menu; @OneToMany(mappedBy = "funcion") @JsonManagedReference private List<Permiso> permisos = new ArrayList<>(); @Column(length = 1) private String tipo; @Column(name = "DES_FUNCION", length = 100) private String functionDescription; // @Column(length = 30) // private String usuins; // // private Date tmsins; // // @Column(length = 30, nullable = true) // private String usumod; // @Column(length = 1, nullable = true) // // private Date tmsmod; }
true
2d6f21fe4da9c7b19e24800e93099e00c457545d
Java
rlabduke/javadev
/molikin/src/molikin/crayons/AltConfCrayon.java
UTF-8
2,180
2.21875
2
[]
no_license
// (jEdit options) :folding=explicit:collapseFolds=1: //{{{ Package, imports package molikin.crayons; import molikin.*; //import java.awt.*; //import java.awt.event.*; import java.io.*; import java.net.URL; import java.text.DecimalFormat; import java.util.*; //import java.util.regex.*; //import javax.swing.*; import driftwood.moldb2.*; //}}} /** * <code>AltConfCrayon</code> puts in pointmasters for atoms with alt confs. * * <p>Copyright (C) 2005 by Ian W. Davis. All rights reserved. * <br>Begun on Thu Nov 10 10:50:17 EST 2005 */ public class AltConfCrayon extends AbstractCrayon implements AtomCrayon, BondCrayon { //{{{ Constants //}}} //{{{ Variable definitions //############################################################################## String altconf = null; //}}} //{{{ Constructor(s) //############################################################################## public AltConfCrayon() { super(); } //}}} //{{{ forAtom, forBond, getPointmasters //############################################################################## public void forAtom(AtomState as) { String alt = as.getAltConf(); if(alt.equals(" ")) altconf = null; else altconf = String.valueOf(Character.toLowerCase(alt.charAt(0))); } public void forBond(AtomState from, AtomState toward) { String altf = from.getAltConf(); String altt = toward.getAltConf(); if(altf.equals(" ")) { if(altt.equals(" ")) altconf = null; else altconf = String.valueOf(Character.toLowerCase(altt.charAt(0))); } else // altf != " " { if(altt.equals(" ")) altconf = String.valueOf(Character.toLowerCase(altf.charAt(0))); // From and Toward should never belong to two different, non-blank alts. // But just in case: else altconf = ""+Character.toLowerCase(altf.charAt(0))+Character.toLowerCase(altt.charAt(0)); } } public String getPointmasters() { return altconf; } //}}} //{{{ empty_code_segment //############################################################################## //}}} }//class
true
1d67a54c5ed816f6b047e910b94d72f99479526f
Java
sycho0311/NetWorkOmok
/src/client/view/lobby/UserListPanel.java
UTF-8
1,449
2.484375
2
[]
no_license
package client.view.lobby; import java.awt.Dimension; import javax.swing.DefaultListModel; import javax.swing.JList; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import client.service.RoomManager; import client.view.Observer; public class UserListPanel extends JScrollPane implements Observer, ListSelectionListener { private static final long serialVersionUID = 5694576677020621386L; private DefaultListModel<String> users = new DefaultListModel<>(); JList<String> userListView = new JList<>(users); private RoomManager manager = RoomManager.getInstance(); public UserListPanel(int width, int height) { setPreferredSize(new Dimension(width, height)); // User List View userListView.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); userListView.addListSelectionListener(this); setViewportView(userListView); manager.allow(this); } @Override public void update() { users.clear(); for (int i = 0; i < manager.getNumOfUsers(); i++) users.addElement(manager.getUser(i)); } @Override public void valueChanged(ListSelectionEvent e) { String userId = userListView.getSelectedValue(); JTextField tf = ((LobbyPanel) getParent()).getChatTextField(); tf.setText("[" + userId + "] "); tf.requestFocus(); } }
true
26ca2f9ad64f0c03cbecdeeebd2e80324fd009e0
Java
perlovdinger/gloria1
/Gloria/ProcureMaterialDomain/src/main/java/com/volvo/gloria/procurematerial/d/entities/status/requestlist/RequestListOperations.java
UTF-8
2,515
1.929688
2
[]
no_license
package com.volvo.gloria.procurematerial.d.entities.status.requestlist; import java.util.Date; import java.util.List; import com.volvo.gloria.common.b.CommonServices; import com.volvo.gloria.common.c.dto.UserDTO; import com.volvo.gloria.common.repositories.b.TraceabilityRepository; import com.volvo.gloria.procurematerial.b.MaterialServices; import com.volvo.gloria.procurematerial.c.dto.MaterialLineDTO; import com.volvo.gloria.procurematerial.d.entities.RequestList; import com.volvo.gloria.procurematerial.repositories.b.MaterialHeaderRepository; import com.volvo.gloria.util.GloriaApplicationException; /** * Possible operations for all status. */ public interface RequestListOperations { RequestList addToRequestList(RequestList requestList, List<MaterialLineDTO> materialLineDTOs, MaterialHeaderRepository materialHeaderRepository) throws GloriaApplicationException; RequestList removeFromRequestList(RequestList requestList, List<MaterialLineDTO> materialLineDTOs, MaterialHeaderRepository materialHeaderRepository) throws GloriaApplicationException; void cancel(RequestList requestList, UserDTO userDTO, MaterialHeaderRepository materialHeaderRepository, TraceabilityRepository traceabilityRepository) throws GloriaApplicationException; List<RequestList> createRequestList(Date requiredDeliveryDate, Long priority, String deliveryAddressType, String deliveryAddessId, String deliveryAddressName, UserDTO user, List<MaterialLineDTO> materialLineDTOs, MaterialServices materialServices, CommonServices commonServices, MaterialHeaderRepository materialHeaderRepository) throws GloriaApplicationException; RequestList updateRequestList(RequestList requestList, Date requiredDeliveryDate, Long priority, String deliveryAddressType, String deliveryAddessId, String deliveryAddressName, UserDTO user, List<MaterialLineDTO> materialLineDTOs, MaterialServices materialServices, CommonServices commonServices, MaterialHeaderRepository materialHeaderRepository) throws GloriaApplicationException; void sendRequestList(RequestList requestList, Date requiredDeliveryDate, Long priority, String deliveryAddressType, String deliveryAddessId, String deliveryAddressName, UserDTO user, List<MaterialLineDTO> materialLineDTOs, MaterialServices materialServices, CommonServices commonServices, MaterialHeaderRepository materialHeaderRepository) throws GloriaApplicationException; }
true
992f54681aa060177e451fceb7ea96656955be17
Java
morgansmb/MeteoJAVA
/src/utils/CapteurManager.java
UTF-8
752
2.421875
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 utils; import capteurs.Capteur; import java.util.ArrayList; import java.util.List; /** * * @author Morgan */ public class CapteurManager { private static List<Capteur> listAllCap = new ArrayList<>(); public static void setListCap(List<Capteur> list) { listAllCap = list; } public static List<Capteur> getList() { return listAllCap; } public static void ajouterCapteur(Capteur cap){ listAllCap.add(cap); } public static void supprimerCapteur(Capteur cap){ listAllCap.remove(cap); } }
true
cc48159117207e39ef670e22049d526cd52174fd
Java
gdefias/learn-java
/java-basic/javalibs/src/main/java/bit/BitUtil.java
UTF-8
8,640
3.59375
4
[ "Apache-2.0" ]
permissive
package bit; /** * Created by Defias on 2017/9/1. */ public class BitUtil { /** * int到byte[] * @param i * @return * 大端字节序Big Endian(网络字节序) 存放在内存中最低位的数值是来自数据的最左边边部分(也就是数据的最高位部分) */ public static byte[] intToBigEndianBytes(int i) { byte[] result = new byte[4]; result[0] = (byte)((i >> 24) & 0xFF); result[1] = (byte)((i >> 16) & 0xFF); result[2] = (byte)((i >> 8) & 0xFF); result[3] = (byte)(i & 0xFF); return result; } /** * byte[]转int * @param bytes * @return * 大端字节序 */ public static int bigEndianBytesToInt(byte[] bytes) { int value=0; for (int i=0; i<4; i++) { int shift = (4-1-i)*8; value += (bytes[i] & 0x000000FF) << shift; } return value; } /** * short转byte[] * * @param s 需要转换的short * 大端字节序 */ public static byte[] shortToBigEndianBytes(short s) { byte[] b = new byte[2]; b[0] = (byte) (s >> 8); b[1] = (byte) (s >> 0); return b; } /** * byte[]转short * * @param b * @return * 大端字节序 */ public static short bigEndianBytesToShort(byte[] b) { return (short) (((b[0] << 8) | b[1] & 0xff)); } /** * 将64位的long值放到8字节的byte数组 * @param num * @return 返回转换后的byte数组 * 大端字节序 */ public static byte[] longToByteArray(long num) { byte[] result = new byte[8]; result[0] = (byte) (num >>> 56); //取最高8位放到0下标 result[1] = (byte) (num >>> 48); result[2] = (byte) (num >>> 40); result[3] = (byte) (num >>> 32); result[4] = (byte) (num >>> 24); result[5] = (byte) (num >>> 16); result[6] = (byte) (num >>> 8); result[7] = (byte) (num); //取最低8位放到7下标 return result; } /** * 将8字节的byte数组转成一个long值 * @param byteArray * @return 转换后的long型数值 * 大端字节序 */ public static long byteArrayToInt(byte[] byteArray) { byte[] a = new byte[8]; int i = a.length-1, j = byteArray.length-1; for (; i>=0; i--, j--) { //从b的尾部(即int值的低位)开始copy数据 if (j >= 0) a[i] = byteArray[j]; else a[i] = 0; //如果b.length不足4,则将高位补0 } //注意: 此处和byte数组转换成int的区别在于,下面的转换中要将先将数组中的元素转换成long型再做移位操作,若直接做位移操作将得不到正确结果,因为Java默认操作数字时,若不加声明会将数字作为int型来对待,此处必须注意。 long v0 = (long) (a[0] & 0xff) << 56; //&0xff将byte值无差异转成int,避免Java自动类型提升后,会保留高位的符号位 long v1 = (long) (a[1] & 0xff) << 48; long v2 = (long) (a[2] & 0xff) << 40; long v3 = (long) (a[3] & 0xff) << 32; long v4 = (long) (a[4] & 0xff) << 24; long v5 = (long) (a[5] & 0xff) << 16; long v6 = (long) (a[6] & 0xff) << 8; long v7 = (long) (a[7] & 0xff); return v0 + v1 + v2 + v3 + v4 + v5 + v6 + v7; } /** * float转换byte数组 * * @param bb * @param x * @param index * 大端字节序 */ public static void putFloat(byte[] bb, float x, int index) { // byte[] b = new byte[4]; int l = Float.floatToIntBits(x); for (int i=0; i<4; i++) { bb[index + i] = new Integer(l).byteValue(); l = l >> 8; } } /** * float转换byte数组 */ public static byte[] float2byte(float f) { // 把float转换为byte[] int fbit = Float.floatToIntBits(f); byte[] b = new byte[4]; for (int i=0; i<4; i++) { b[i] = (byte) (fbit >> (24 - i * 8)); } // 翻转数组 int len = b.length; // 建立一个与源数组元素类型相同的数组 byte[] dest = new byte[len]; // 为了防止修改源数组,将源数组拷贝一份副本 System.arraycopy(b, 0, dest, 0, len); byte temp; // 将顺位第i个与倒数第i个交换 for (int i = 0; i < len / 2; ++i) { temp = dest[i]; dest[i] = dest[len - i - 1]; dest[len - i - 1] = temp; } return dest; } /** * 通过byte数组取得float * * @param bb * @param index * @return * 大端字节序 */ public static float getFloat(byte[] b, int index) { int l; l = b[index + 0]; l &= 0xff; l |= ((long) b[index + 1] << 8); l &= 0xffff; l |= ((long) b[index + 2] << 16); l &= 0xffffff; l |= ((long) b[index + 3] << 24); return Float.intBitsToFloat(l); } /** * double转换byte * * @param bb * @param x * @param index * 大端字节序 */ public static void putDouble(byte[] bb, double x, int index) { // byte[] b = new byte[8]; long l = Double.doubleToLongBits(x); for (int i=0; i<4; i++) { bb[index + i] = new Long(l).byteValue(); l = l >> 8; } } /** * 通过byte数组取得double * * @param bb * @param index * @return * 大端字节序 */ public static double getDouble(byte[] b, int index) { long l; l = b[0]; l &= 0xff; l |= ((long) b[1] << 8); l &= 0xffff; l |= ((long) b[2] << 16); l &= 0xffffff; l |= ((long) b[3] << 24); l &= 0xffffffffl; l |= ((long) b[4] << 32); l &= 0xffffffffffl; l |= ((long) b[5] << 40); l &= 0xffffffffffffl; l |= ((long) b[6] << 48); l &= 0xffffffffffffffl; l |= ((long) b[7] << 56); return Double.longBitsToDouble(l); } //======================================================= /** * short转byte[] * * @param s 需要转换的short * 小端字节序 */ public static byte[] shortToLittleEndianBytes(short s) { byte[] b = new byte[2]; b[1] = (byte) (s >> 8); b[0] = (byte) (s >> 0); return b; } /** * byte[]转short * * @param b * @return * 小端字节序 */ public static short littleEndianBytesToShort(byte[] b) { return (short) (((b[1] << 8) | b[0] & 0xff)); } /** * short装byte[] * * @param b * @param s 需要转换的short * @param index * 小端字节序Little Endian 存放在内存中最低位的数值是来自数据的最右边部分(也就是数据的最低位部分) */ public static void putShortToLittleEndianBytes(byte b[], short s, int index) { b[index + 1] = (byte) (s >> 8); b[index + 0] = (byte) (s >> 0); } /** * byte[]转short * * @param b * @param index 第几位开始取 * @return * 小端字节序 */ public static short getShortFromLittleEndianBytes(byte[] b, int index) { return (short) (((b[index + 1] << 8) | b[index + 0] & 0xff)); } public static void main(String[] args) { //int value = 32; //byte[] bytes = intToBigEndianBytes(value); //System.out.println(bytes); //System.out.println(bigEndianBytesToInt(bytes)); //String hexstr = HexUtil.encodeHexStr(bytes); //System.out.println(hexstr); //String hexstr2 = Integer.toHexString(value); //System.out.println(hexstr2); // //short s = 32; //String hexstrs = Integer.toHexString(s); //System.out.println(hexstrs); //byte[] bytess = shortToBigEndianBytes(s); //System.out.println(bytess); //System.out.println(bigEndianBytesToShort(bytess)); float vf = 12.12f; byte[] result = new byte[4]; putFloat(result, vf, 0); for(byte b: result) { System.out.println(b); } byte[] result2 = float2byte(vf); for(byte b: result2) { System.out.println(b); } System.out.println(getFloat(result, 0)); System.out.println(getFloat(result2, 0)); } }
true
e10e26711ddbef8209354ad9af4295751564e22b
Java
coder-wzq/spring-demo
/src/main/java/com/wzq/springboot/config/DataSourceConfig.java
UTF-8
2,509
1.9375
2
[]
no_license
package com.wzq.springboot.config; import com.alibaba.druid.pool.DruidDataSource; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.SqlSessionTemplate; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.core.env.Environment; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.sql.DataSource; @Configuration @EnableTransactionManagement @MapperScan(basePackages = "com.wzq.springboot.mapper", annotationClass = TargetDataSourceOne.class, sqlSessionFactoryRef = "oneSqlSessionFactory") public class DataSourceConfig { @Autowired private Environment env; @Primary @Bean(name = "oneDB") public DataSource getDataSource() { DruidDataSource dataSource = new DruidDataSource(); dataSource.setUrl(env.getProperty("spring.datasource.druid.wzq.url")); dataSource.setUsername(env.getProperty("spring.datasource.druid.wzq.username")); dataSource.setPassword(env.getProperty("spring.datasource.druid.wzq.password")); return dataSource; } @Bean(name = "oneSqlSessionFactory") @Primary public SqlSessionFactory testSqlSessionFactory(@Qualifier("oneDB") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); return bean.getObject(); } @Bean(name = "oneTransactionManager") @Primary public DataSourceTransactionManager testTransactionManager(@Qualifier("oneDB") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Bean(name = "oneSqlSessionTemplate") @Primary public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("oneSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } @Bean(name = "wzq") public JdbcTemplate oneJdbcTemplate(@Qualifier("oneDB") DataSource ds) { return new JdbcTemplate(ds); } }
true
a70a0a058c4fe781d091f8981d625abec07a7961
Java
ApoapsisAlpha/tuumes
/tuumes/phase2/src/main/java/group0153/conferencesystem/adapters/controllers/event/requests/EventRemoveRequest.java
UTF-8
314
2.109375
2
[]
no_license
package group0153.conferencesystem.adapters.controllers.event.requests; /** * Request class for event removal. */ public class EventRemoveRequest { private String eventId; /** * Get the event id. * @return the event id */ public String getEventId() { return eventId; } }
true
09e4152b14e102885e3a26cc97900f5a7be4b5e6
Java
elyelin/java-projects
/TPROG1_2021C1_P2_OrtMarket_Incompleto/src/ar/edu/ort/tp1/tdas/implementaciones/ColaNodos.java
UTF-8
801
2.9375
3
[]
no_license
package ar.edu.ort.tp1.tdas.implementaciones; import ar.edu.ort.tp1.tdas.interfaces.Cola; public class ColaNodos<T> extends TdaNodos<T> implements Cola<T> { private Nodo<T> last; public ColaNodos() { super(); } public ColaNodos(int limite) { super(limite); this.last = null; } @Override public void add(T elemento) { checkFullness(); Nodo<T> nuevoNodo = new Nodo<>(elemento); if (isEmpty()) { first = nuevoNodo; } else { last.next(nuevoNodo); } last = nuevoNodo; incrementSize(); } @Override public T remove() { checkEmptiness(); Nodo<T> aux = first; first = first.next(); decrementSize(); return aux.getElement(); } @Override public T get() { checkEmptiness(); return first.getElement(); } }
true
9c3ccc982e1ac55776e314c6e02d5fa3b39da4b6
Java
tsuzcx/qq_apk
/com.tencent.mm/classes.jar/com/tencent/tencentmap/mapsdk/maps/model/Tile.java
UTF-8
1,567
2
2
[]
no_license
package com.tencent.tencentmap.mapsdk.maps.model; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.graphics.Bitmap.Config; import android.graphics.Canvas; import com.tencent.matrix.trace.core.AppMethodBeat; import java.io.ByteArrayOutputStream; public final class Tile { public static Tile EMPTY_TILE; public final byte[] mData; public final int mHeight; public final int mWidth; static { AppMethodBeat.i(181089); EMPTY_TILE = new Tile(-1, -1, getNoTileData()); AppMethodBeat.o(181089); } public Tile(int paramInt1, int paramInt2, byte[] paramArrayOfByte) { this.mWidth = paramInt1; this.mHeight = paramInt2; this.mData = paramArrayOfByte; } private static byte[] getNoTileData() { AppMethodBeat.i(181088); Object localObject = Bitmap.createBitmap(256, 256, Bitmap.Config.ARGB_8888); new Canvas((Bitmap)localObject).drawARGB(0, 255, 255, 255); ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream(); ((Bitmap)localObject).compress(Bitmap.CompressFormat.PNG, 100, localByteArrayOutputStream); localObject = localByteArrayOutputStream.toByteArray(); AppMethodBeat.o(181088); return localObject; } public final byte[] getData() { return this.mData; } } /* Location: L:\local\mybackup\temp\qq_apk\com.tencent.mm\classes9.jar * Qualified Name: com.tencent.tencentmap.mapsdk.maps.model.Tile * JD-Core Version: 0.7.0.1 */
true
3a86325a88d686bd42395f5a568e6bc56aaa566d
Java
AhmadAlsaleh/Check-Jobs-App
/app/src/main/java/com/crazy_iter/checkjobs/SearchHistoryActivity.java
UTF-8
2,419
2.21875
2
[]
no_license
package com.crazy_iter.checkjobs; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.Menu; import android.view.MenuItem; import android.view.WindowManager; import android.widget.Toast; import com.crazy_iter.checkjobs.Adapters.SearchHistoryAdapter; import com.crazy_iter.checkjobs.Data.SearchHistoryItem; import java.util.ArrayList; public class SearchHistoryActivity extends AppCompatActivity { private RecyclerView searchHistoryRV; private ArrayList<SearchHistoryItem> searchHistoryItems; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_search_history); getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setTitle("Search History"); searchHistoryRV = findViewById(R.id.searchResultRV); searchHistoryItems = new ArrayList<>(); for (int i = 0; i < 3; i++) { searchHistoryItems.add(new SearchHistoryItem("", "Word:"+i, "place:"+i, "100 - 150 $", "5 Hours PM", "6 Days", "Male")); } searchHistoryRV.setHasFixedSize(true); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false); searchHistoryRV.setLayoutManager(layoutManager); RecyclerView.Adapter adapter = new SearchHistoryAdapter(SearchHistoryActivity.this, searchHistoryItems); searchHistoryRV.setAdapter(adapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.search_history_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id) { case android.R.id.home: this.finish(); break; case R.id.clearSearchHistoryItem: Toast.makeText(this, "TODO", Toast.LENGTH_SHORT).show(); this.finish(); break; } return true; } }
true
caf390c3cc4fcf5c56e65d7facc01e63b53fba88
Java
sy-jingqixiansheng/xyh-saas
/xyh_system/src/main/java/com/xyh/system/client/fallback/DepartmentFeignClientFallBack.java
UTF-8
508
1.882813
2
[]
no_license
package com.xyh.system.client.fallback; import com.xyh.system.client.DepartmentFeignClient; import cpm.xyh.entity.company.Department; import org.springframework.stereotype.Service; /** * @Author SQ 服务调用容错类 * @Date 2020/8/19 0019 19:52 * @Version 1.0 */ @Service public class DepartmentFeignClientFallBack implements DepartmentFeignClient { @Override public Department findByCode(String code, String companyId) { //log.info("熔断保护"); return null; } }
true
b47bca91e7a1aa017d8d7b8c3d6a20b49fa5d9b0
Java
AndreiYu/microservices-design-patterns
/authentication-service/src/main/java/com/microservice/authentication/AuthenticationServiceApplication.java
UTF-8
6,582
1.703125
2
[]
no_license
package com.microservice.authentication; import java.util.Collections; import java.util.Properties; import java.util.UUID; import com.microservice.authentication.common.model.Authentication; import com.microservice.authentication.common.model.Authority; import com.microservice.authentication.common.repository.AuthenticationCommonRepository; import com.microservice.authentication.service.CustomLogoutSuccessHandler; import com.microservice.authentication.service.RedisTokenStoreService; import com.microservice.web.common.util.constants.DefaultUsers; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.data.redis.RedisProperties; import org.springframework.boot.info.GitProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Primary; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.mapping.event.ValidatingMongoEventListener; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.oauth2.provider.approval.TokenApprovalStore; import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore; import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; import org.springframework.session.web.http.CookieSerializer; import org.springframework.session.web.http.DefaultCookieSerializer; import org.springframework.stereotype.Controller; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ResponseBody; @Slf4j @SpringBootApplication @EnableRedisHttpSession public class AuthenticationServiceApplication { public static void main(String[] args) { SpringApplication.run(AuthenticationServiceApplication.class, args); } @ConditionalOnProperty(prefix = "configuration", name = "initialLoad", havingValue = "true", matchIfMissing = true) @Bean CommandLineRunner runner(AuthenticationCommonRepository authenticationCommonRepository, PasswordEncoder passwordEncoder, MongoTemplate mongoTemplate) { return args -> { if (authenticationCommonRepository.findByEmail(DefaultUsers.SYSTEM_DEFAULT.getValue()) == null) { Authentication authentication = Authentication.builder() .email(DefaultUsers.SYSTEM_DEFAULT.getValue()) .password(passwordEncoder.encode("noPassword")) .fullName("System Administrator") .enabled(false) .id(UUID.randomUUID().toString()) .build(); log.debug("Creating default authentication: {}", authentication); authentication = mongoTemplate.save(authentication, "users_login"); log.debug("Created Default Authentication: {}", authentication); } if (authenticationCommonRepository.findByEmail("admin@gmail.com") == null) { Authentication authentication = Authentication.builder() .email("admin@gmail.com") .password(passwordEncoder.encode("P@ssword2020!")) .fullName("Admin") .enabled(true) .id(UUID.randomUUID().toString()) .authorities(Collections.singletonList(new Authority("ROLE_ADMIN"))) .build(); log.debug("Creating admin authentication: {}", authentication); authentication = mongoTemplate.save(authentication, "users_login"); log.debug("Created admin Authentication: {}", authentication); } }; } @Bean public CookieSerializer cookieSerializer() { DefaultCookieSerializer serializer = new DefaultCookieSerializer(); serializer.setCookieName("SESSIONID"); serializer.setCookiePath("/"); return serializer; } @Bean public ValidatingMongoEventListener validatingMongoEventListener() { return new ValidatingMongoEventListener(validator()); } @Bean public LocalValidatorFactoryBean validator() { return new LocalValidatorFactoryBean(); } @ConditionalOnMissingBean @Bean RedisConnectionFactory lettuceConnectionFactory(RedisProperties redisProperties) { return new LettuceConnectionFactory(redisProperties.getHost(), redisProperties.getPort()); } @Primary @Bean RedisTokenStore redisTokenStore(RedisConnectionFactory redisConnectionFactory, JwtAccessTokenConverter jwtAccessTokenConverter) { RedisTokenStore redisTokenStore = new RedisTokenStore(redisConnectionFactory); TokenApprovalStore tokenApprovalStore = new TokenApprovalStore(); tokenApprovalStore.setTokenStore(redisTokenStore); JwtTokenStore jwtTokenStore = new JwtTokenStore(jwtAccessTokenConverter); jwtTokenStore.setApprovalStore(tokenApprovalStore); return redisTokenStore; } @Bean CustomLogoutSuccessHandler customLogoutSuccessHandler(RedisTokenStoreService redisTokenStoreService) { return new CustomLogoutSuccessHandler(redisTokenStoreService); } @ConditionalOnMissingBean @Bean GitProperties gitProperties() { return new GitProperties(new Properties()); } } @Slf4j @Controller @AllArgsConstructor class HomeController { private final AuthenticationCommonRepository authenticationCommonRepository; @GetMapping("/") @ResponseBody public Authentication user(org.springframework.security.core.Authentication authentication) { log.debug("Logged user: {}", authentication); return authenticationCommonRepository.findById(authentication.getName()); } }
true
569947d49f65432b4a1e25bb9df63ab1c62625e6
Java
mquibar/malbec
/branches/Malbec/src/persistencia/Intermediario.java
UTF-8
2,108
2.65625
3
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package persistencia; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.persistence.Query; import persistencia.exceptions.PersistException; /** * * @author desarrollo */ class Intermediario<E> { protected String _clase; public Intermediario(String _clase) { this._clase = _clase; } public List<E> findAll() { try { Query q = ConectionAdmin.getInstance().getManager().createQuery("SELECT c FROM "+_clase + " c"); return q.getResultList(); } catch (Exception ex) { ex.printStackTrace(); System.err.println(ex.getMessage()); return null; } } public void guardar(E obj) throws PersistException { try { ConectionAdmin.getInstance().getManager().persist(obj); } catch (Exception ex) { ex.printStackTrace(); throw new PersistException("Guardar", obj); } } public void actualizar(E obj) throws PersistException { try { ConectionAdmin.getInstance().getManager().merge(obj); } catch (Exception ex) { ex.printStackTrace(); throw new PersistException("Actualizar", obj); } } public List<E> findInOrden(String orden) { Query q = ConectionAdmin.getInstance().getManager().createQuery("SELECT o FROM " + _clase + " o ORDER BY o." + orden); return q.getResultList(); } public List<E> findByCriterio(Criterio criterio) { String sql = "SELECT o FROM " + _clase + " o WHERE " + criterio; Query q = ConectionAdmin.getInstance().getManager().createQuery(sql); for (Object[] criteria : criterio.toParameter()) { q.setParameter(String.valueOf(criteria[0]), criteria[1]); } return q.getResultList(); } public List<E> excecuteQuery(String query){ return ConectionAdmin.getInstance().getManager().createQuery(query).getResultList(); } }
true
81db236f9f8699d8ef5ae501a94b0e4cd6736226
Java
managlia/yeti-model
/src/main/java/com/yeti/model/action/validators/ActionClassificationTypeEventHandler.java
UTF-8
885
2
2
[]
no_license
package com.yeti.model.action.validators; import org.springframework.data.rest.core.annotation.HandleBeforeCreate; import org.springframework.data.rest.core.annotation.HandleBeforeSave; import org.springframework.data.rest.core.annotation.RepositoryEventHandler; import org.springframework.stereotype.Component; import com.yeti.model.action.ActionClassificationType; @Component @RepositoryEventHandler public class ActionClassificationTypeEventHandler { @HandleBeforeSave(ActionClassificationType.class) public void handleActionClassificationTypeSave(ActionClassificationType p) { System.out.println("@HandleBeforeSave validation when using REST Data"); } @HandleBeforeCreate(ActionClassificationType.class) public void handleActionClassificationTypeCreate(ActionClassificationType p) { System.out.println("@HandleBeforeCreate validation when using REST Data"); } }
true
1c1066d3e769cc2cd2550f067fc9a15c6c63a26a
Java
LearnLib/learnlib
/algorithms/active/aaar/src/test/java/de/learnlib/algorithms/aaar/TranslatingLearnerWrapper.java
UTF-8
1,592
2
2
[ "Apache-2.0", "LicenseRef-scancode-free-unknown" ]
permissive
/* Copyright (C) 2013-2023 TU Dortmund * This file is part of LearnLib, http://www.learnlib.de/. * * 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 de.learnlib.algorithms.aaar; import de.learnlib.api.algorithm.LearningAlgorithm; import de.learnlib.api.query.DefaultQuery; import net.automatalib.SupportsGrowingAlphabet; /** * @author frohme */ public class TranslatingLearnerWrapper<L extends LearningAlgorithm<CM, CI, D> & SupportsGrowingAlphabet<CI>, CM, CI, D> implements LearningAlgorithm<CM, CI, D> { private final AbstractAAARLearner<L, ?, CM, ?, CI, D> delegate; public TranslatingLearnerWrapper(AbstractAAARLearner<L, ?, CM, ?, CI, D> delegate) { this.delegate = delegate; } @Override public void startLearning() { this.delegate.startLearning(); } @Override public boolean refineHypothesis(DefaultQuery<CI, D> ceQuery) { return this.delegate.refineHypothesis(ceQuery); } @Override public CM getHypothesisModel() { return this.delegate.getTranslatingHypothesisModel(); } }
true
5a66bca455b2586b099d9c45e8dd6be53e426dbc
Java
chenkaichao03/CLT-SSM
/src/main/java/cn/clt/module/bussiness/ConcernController.java
UTF-8
4,259
2.015625
2
[]
no_license
package cn.clt.module.bussiness; import cn.clt.core.entity.User; import cn.clt.core.entity.UserInfo; import cn.clt.core.enums.Code; import cn.clt.core.exception.BussinessException; import cn.clt.core.params.ManagementPageData; import cn.clt.core.params.Result; import cn.clt.core.service.ActiveUserService; import cn.clt.core.service.ConcernService; import cn.clt.core.service.UserInfoService; import cn.clt.core.service.UserService; import cn.clt.core.vo.ActiveUser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpSession; import java.util.List; /** * @Description 关注 * @Aouthor CLT * @Date 2018/05/07 15:14 */ @Controller @RequestMapping(value = "/concern", produces = {"application/json;charset=UTF-8"}) public class ConcernController { private static final Logger logger = LoggerFactory.getLogger(ConcernController.class); @Autowired private ConcernService concernService; @Autowired private ActiveUserService activeUserService; @Autowired private UserInfoService userInfoService; @Autowired private UserService userService; /** * @Title listConcern * @Description 获取关注列表 * @Author CLT * @Date 2018/5/7 15:18 * @param session * @param model * @return */ @RequestMapping("/list") public String selectConcernPage(HttpSession session, Model model,String userManageId, @RequestParam(defaultValue = "1") Integer pageNo, @RequestParam(defaultValue = "10") Integer pageSize){ try { //获取用户信息 ActiveUser activeUser = activeUserService.getActiveUser(session); String userId = activeUser.getUserId(); List<UserInfo> userInfoList = userInfoService.listUserInfoByUsreId(userId); UserInfo userInfo = null; if (!CollectionUtils.isEmpty(userInfoList)){ userInfo = userInfoList.get(0); } model.addAttribute("userInfo",userInfo); //判断改用户角色 User user = userService.getUserById(userId); if (user != null) { model.addAttribute("userRole", user); } //获取关注列表 分页 if (!StringUtils.isEmpty(userManageId)){ userId = userManageId; } ManagementPageData pageData = concernService.selectConcernPage(userId,pageNo,pageSize); model.addAttribute("pageData",pageData); }catch (Exception e){ e.printStackTrace(); logger.error("获取关注列表失败"); throw new BussinessException("获取关注列表失败"); } return "followuser"; } /** * @Title cancelConcern * @Description 取消关注 * @Author CLT * @Date 2018/5/8 17:46 * @param session * @param model * @param concernedUser 被关注者id * @return */ @RequestMapping("/cancel") @ResponseBody public String cancelConcern(HttpSession session, Model model,String concernedUser){ try { //获取用户信息 ActiveUser activeUser = activeUserService.getActiveUser(session); String userId = activeUser.getUserId(); //取消关注操作 int result = concernService.cancelConcern(userId,concernedUser); if (result == 1) { return Result.ok(Code.OK.getValue(), "取消关注成功.", null); }else { return Result.error("取消关注失败"); } }catch (Exception e){ e.printStackTrace(); logger.error("取消关注失败."); return Result.error("取消关注失败."); } } }
true
4cbd19981cc8854d34926d55a0e99f78489b7d21
Java
zhongxingyu/Seer
/Diff-Raw-Data/2/2_d709e874f6721d28e5932362fbd5623882a52d09/GameOverMessageHandler/2_d709e874f6721d28e5932362fbd5623882a52d09_GameOverMessageHandler_s.java
UTF-8
1,075
3
3
[]
no_license
package foop.java.snake.common.message.handler; import java.net.SocketAddress; import java.util.Observable; import foop.java.snake.common.message.GameOverMessage; import foop.java.snake.common.message.InputMessage; import foop.java.snake.common.message.MessageInterface; import foop.java.snake.common.message.exception.NoMessageHandlerFoundException; public class GameOverMessageHandler extends Observable implements MessageHandlerInterface { @Override public void handle(MessageInterface message, SocketAddress address) throws NoMessageHandlerFoundException { if (message.getType() != InputMessage.TYPE) { throw new NoMessageHandlerFoundException("This is not a GameOver-Message."); } this.printInput((GameOverMessage) message); // Implementation of the observer-pattern setChanged(); notifyObservers((GameOverMessage) message); } private void printInput(GameOverMessage m) { System.out.println("GameOverMessageHandler: Got GameOver-Message."); System.out.println("Message: " + m.getMessage()); } }
true
b47b652338be96674addf3ece2e5e0ba8dfc314d
Java
heathjay/niuke
/Leetcode-2/31/Solution.java
UTF-8
1,116
3.3125
3
[]
no_license
class Solution { public int longestValidParentheses(String s) { int maxans = 0; int[] dp = new int[s.length()]; for(int i = 1;i < s.length();i++){ if(s.charAt(i) == ')'){ if(s.charAt(i-1) =='(' ){ dp[i] = (i >= 2 ? dp[i-1] :0 ) + 2; }else if(i - dp[i-1] > 0 && s.charAt(i-1-dp[i-1]) =='('){ dp[i] = dp[i-1] + ((i-dp[i-1]) >= 2 ? dp[i-dp[i-2]-2] : 0) + 2; } maxans = Math.max(maxans, dp[i]); } } return maxans; } public int longestValidParentheses1(String s) { int max = 0; Stack<Integer> stack = new Stack<>(); stack.push(-1); for(int i =0; i < s.length(); i++){ if(s.charAt(i) == '('){ stack.push(i); }else{ stack.pop(); if(stack.isEmpty()){ stack.push(i); }else{ max = Math.max(max, i - stack.peek()); } } } return max; } }
true
6fe22c8bb916d4029433d67c0c94599f0cce2daa
Java
amjadmajid/GprojectApp
/GprojectAndroidApp/PeriodicQuery/src/org/bfr/periodicquery/PeriodicQueryService.java
UTF-8
5,952
1.898438
2
[]
no_license
/** Copyright 2014 [BFR] 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.bfr.periodicquery; import org.bfr.periodicquery.PeriodicQueryApplication.LocationFuzzing; import org.bfr.periodicquery.PeriodicQueryApplication.SpectrumSource; import org.bfr.periodicquery.sdr.SdrSpectrumSensing; import org.bfr.querytools.google.GoogleSpectrumQuery; import org.bfr.querytools.logging.Logger; import org.bfr.querytools.msr.MsrSpectrumQuery; import org.bfr.querytools.spectrumbridge.SpectrumBridgeQuery; import android.app.Notification; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.IBinder; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.util.Log; public class PeriodicQueryService extends Service { // Maximum time to keep a wake lock in ms private static long wakeLockTimeOut = 10*1000; // Binder so Activities can bind this service. private final PeriodicQueryServiceBinder binder = new PeriodicQueryServiceBinder(this); // Active boolean active = false; // First query of a sequence? Needed for spectrum bridge boolean firstQuery = false; public PeriodicQueryService() { java.util.logging.Logger.getLogger("org.apache.http.wire").setLevel(java.util.logging.Level.FINEST); java.util.logging.Logger.getLogger("org.apache.http.headers").setLevel(java.util.logging.Level.FINEST); System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog"); System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true"); System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire", "debug"); System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http", "debug"); System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http.headers", "debug"); Logger.setLogger(new Logger() { @Override public void logMessage(String message) { Log.d("SpectrumQuery", message); } }); } public void start() { if (active) return; // Start polling AlarmReceiver.scheduleWakeupFromNow(this, 0); // Signal that we're now active active = true; // First query after new start firstQuery = true; } public void stop() { if (!active) return; // Signal that we're now deactivated active = false; } public boolean isActive() { return active; } @Override public void onCreate() { super.onCreate(); AlarmReceiver.setCallBack(pollingCallback); } @Override public void onDestroy() { super.onDestroy(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { // The intent to launch when the user clicks the expanded notification Intent launchIntent = new Intent(this, StartStopActivity.class); launchIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent pendIntent = PendingIntent.getActivity(this, 0, launchIntent, 0); // This constructor is deprecated. Use Notification.Builder instead Notification notice = new Notification(R.drawable.ic_launcher, "Periodic Query", System.currentTimeMillis()); // This method is deprecated. Use Notification.Builder instead. notice.setLatestEventInfo(this, "Periodic Query", "Periodic Query", pendIntent); notice.flags |= Notification.FLAG_NO_CLEAR; startForeground(1234, notice); return START_STICKY; } @Override public IBinder onBind(Intent intent) { return binder; } Runnable pollingCallback = new Runnable() { public void spectrumQuery(PeriodicQueryApplication app) { // Determine location double latitude = app.getLocation().latitude; double longitude = app.getLocation().longitude; // Optionally apply fuzzing if (app.getLocationFuzzing()==LocationFuzzing.UniformSquare) { latitude += Math.random() - 0.5; longitude += Math.random() - 0.5; } // Execute the query switch(app.getSpectrumSource()) { case Google: GoogleSpectrumQuery.query(latitude, longitude); break; case Microsoft: MsrSpectrumQuery.query(latitude, longitude); break; case SpectrumBridge: SpectrumBridgeQuery.query(latitude, longitude, firstQuery); break; default: // none } firstQuery = false; } public void spectrumSense() { SdrSpectrumSensing.sense(); } @Override public void run() { final PeriodicQueryApplication app = (PeriodicQueryApplication)getApplication(); // Schedule next wakeup Log.d("SpectrumQuery", "active: " + active); if (active) AlarmReceiver.scheduleWakeupFromNow(PeriodicQueryService.this, app.getQueryInterval() * 1000); // Get the power manager PowerManager powerManager = (PowerManager)getSystemService(Context.POWER_SERVICE); // Create and acquire a wake lock to keep the processor wake final WakeLock lock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Spectrum Query"); lock.acquire(wakeLockTimeOut); new Thread() { public void run() { try { if (app.getSpectrumSource()==SpectrumSource.RtlSdr) spectrumSense(); else spectrumQuery(app); } catch (Exception ex) { ex.printStackTrace(); } finally { if (lock.isHeld()) lock.release(); } }; }.start(); } }; }
true
7153306ff7264c2712d2a27f623ad7a946b21de9
Java
luccs271course-spring2018/lab5-jackwestlab5
/src/main/java/edu/luc/cs271/linkedstack/ReverseLines.java
UTF-8
592
3.46875
3
[]
no_license
package edu.luc.cs271.linkedstack; import java.util.Scanner; import java.util.List; public class ReverseLines { public static void main(String[] args) { // TODO read successive input lines until EOF, then print out in reverse order LinkedStack<String> stack = new LinkedStack<String>(); final Scanner input = new Scanner(System.in); String line = null; while (input.hasNextLine()) { line = input.nextLine(); stack.push(line); } String tempWord= ""; while( !stack.isEmpty()) { tempWord += "\n" + stack.pop(); } System.out.println(tempWord); } }
true
d32e3a81d9f345800e9c112713059ceee649e96d
Java
Rtanmoy/POC-Sreenu-
/RTP4808(Sreenu)/LoyaltyRewardsSvcProcessLayer/src/main/java/com/henryschain/loyalty/rewards/process/impl/LoyaltyRewardsProcessImpl.java
UTF-8
1,516
2.078125
2
[]
no_license
package com.henryschain.loyalty.rewards.process.impl; import com.henryschain.loyalty.rewards.dao.LoyaltyRewardsDAO; import com.henryschain.loyalty.rewards.dao.impl.LoyaltyRewardsDAOImpl; import com.henryschain.loyalty.rewards.dao.model.CustomerRegDAOReq; import com.henryschain.loyalty.rewards.dao.model.CustomerRegDAORes; import com.henryschain.loyalty.rewards.process.LoyaltyRewardsProcess; import com.henryschain.loyalty.rewards.process.model.CustomerRegProcessReq; import com.henryschain.loyalty.rewards.process.model.CustomerRegProcessResp; import com.henryschain.loyalty.rewards.process.model.CustomerRegReqBuilder; import com.henryschain.loyalty.rewards.process.model.LoyaltyRewardsProcessReq; public class LoyaltyRewardsProcessImpl implements LoyaltyRewardsProcess { public CustomerRegProcessResp registration(CustomerRegProcessReq custreq) { CustomerRegReqBuilder crrb=new CustomerRegReqBuilder(); CustomerRegDAOReq daoreq=crrb.buildRequest(custreq); LoyaltyRewardsDAO dao=new LoyaltyRewardsDAOImpl(); CustomerRegDAORes daoresp=dao.getResponse(daoreq); CustomerRegProcessResp presp=new CustomerRegProcessResp(); presp.setRespCode(daoresp.getRespCode()); presp.setRefNum(daoresp.getRefNum()); presp.setRespMsg(daoresp.getRespMsg()); presp.setStatus(daoresp.getStatus()); return presp; } public LoyaltyRewardsProcessReq getVendorDetails(LoyaltyRewardsProcessReq req) { // TODO Auto-generated method stub return null; } }
true
9766c8b06691edeb9186f8dd105c1eee8299cd0b
Java
SigExe/SummerB20
/src/day23_Arrays/FrequenceOfChar.java
UTF-8
1,096
3.78125
4
[]
no_license
package day23_Arrays; /* write a program that can return the frequency of every single characters from the string: ex: str1 = "aabbccaa"; output: a4b2c2 HINT: easier approach: 1. remove duplicates ==> str2 = "abc" */ public class FrequenceOfChar { public static void main(String[] args) { String str = "ABAB"; String nonDup = ""; String result = ""; for(int i = 0; i <= str.length() - 1; i++){ String ch = "" + str.charAt(i); if(!nonDup.contains(ch)){ nonDup += ch; } } System.out.println(nonDup); for(int j = 0; j <= nonDup.length() - 1; j++){ char ch = nonDup.charAt(0); int count = 0; for(int i = 0; i <= str.length() - 1; i++){ if(str.charAt(i) == ch){ count += 1; } } result += "" + ch + count; } System.out.println(result); } }
true
1827bf000b9c449ee82a32fb7ceecf88e5c6512a
Java
nicholaschum/DecompiledEvoziSmartLED
/sources/com/qihoo360/replugin/C0461g.java
UTF-8
1,305
1.851563
2
[]
no_license
package com.qihoo360.replugin; import android.os.IBinder; import android.text.TextUtils; import java.util.concurrent.ConcurrentHashMap; /* renamed from: com.qihoo360.replugin.g */ public class C0461g { /* renamed from: a */ private static C0461g f2000a; /* renamed from: b */ private ConcurrentHashMap<String, IBinder> f2001b = new ConcurrentHashMap<>(); /* renamed from: a */ public static C0461g m1551a() { if (f2000a != null) { return f2000a; } synchronized (C0461g.class) { if (f2000a == null) { f2000a = new C0461g(); } } return f2000a; } /* renamed from: a */ public IBinder mo4634a(String str) { if (!TextUtils.isEmpty(str)) { IBinder iBinder = this.f2001b.get(str); if (iBinder == null) { return null; } if (iBinder.isBinderAlive() && iBinder.pingBinder()) { return iBinder; } this.f2001b.remove(str); return null; } throw new IllegalArgumentException("service name can not value null"); } /* renamed from: a */ public void mo4635a(String str, IBinder iBinder) { this.f2001b.put(str, iBinder); } }
true
df9b646f95c42f26195b4df529ba6c8a1f0e3c0f
Java
viniciusfacco/java-tibia-robot
/TibiaRobot/src/tibiarobot/TibiaRobotF.java
UTF-8
43,419
1.984375
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 tibiarobot; import javax.swing.JOptionPane; /** * * @author vfrodrigues */ public class TibiaRobotF extends javax.swing.JFrame { private Thread thtibia; private TibiaRobot tibia; /** * Creates new form TibiaRobotF */ public TibiaRobotF() { initComponents(); this.setAlwaysOnTop(true); this.setResizable(false); } /** * 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() { jbIniciar = new javax.swing.JButton(); jbParar = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); jTabbedPane1 = new javax.swing.JTabbedPane(); jPanel1 = new javax.swing.JPanel(); jtfTempoEspera = new javax.swing.JTextField(); jLabel13 = new javax.swing.JLabel(); jPanel2 = new javax.swing.JPanel(); jtfChar1Name = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jcbChar1Ativo = new javax.swing.JCheckBox(); jSeparator1 = new javax.swing.JSeparator(); jLabel14 = new javax.swing.JLabel(); jcbChar1F1 = new javax.swing.JCheckBox(); jcbChar1F2 = new javax.swing.JCheckBox(); jcbChar1F3 = new javax.swing.JCheckBox(); jcbChar1F4 = new javax.swing.JCheckBox(); jcbChar1F5 = new javax.swing.JCheckBox(); jcbChar1F6 = new javax.swing.JCheckBox(); jcbChar1F7 = new javax.swing.JCheckBox(); jcbChar1F8 = new javax.swing.JCheckBox(); jcbChar1F9 = new javax.swing.JCheckBox(); jcbChar1F10 = new javax.swing.JCheckBox(); jcbChar1F11 = new javax.swing.JCheckBox(); jcbChar1F12 = new javax.swing.JCheckBox(); jPanel3 = new javax.swing.JPanel(); jLabel7 = new javax.swing.JLabel(); jtfChar2Name = new javax.swing.JTextField(); jcbChar2Ativo = new javax.swing.JCheckBox(); jSeparator3 = new javax.swing.JSeparator(); jLabel3 = new javax.swing.JLabel(); jcbChar2F1 = new javax.swing.JCheckBox(); jcbChar2F2 = new javax.swing.JCheckBox(); jcbChar2F3 = new javax.swing.JCheckBox(); jcbChar2F4 = new javax.swing.JCheckBox(); jcbChar2F5 = new javax.swing.JCheckBox(); jcbChar2F6 = new javax.swing.JCheckBox(); jcbChar2F7 = new javax.swing.JCheckBox(); jcbChar2F8 = new javax.swing.JCheckBox(); jcbChar2F9 = new javax.swing.JCheckBox(); jcbChar2F10 = new javax.swing.JCheckBox(); jcbChar2F11 = new javax.swing.JCheckBox(); jcbChar2F12 = new javax.swing.JCheckBox(); jPanel4 = new javax.swing.JPanel(); jLabel10 = new javax.swing.JLabel(); jcbChar3Ativo = new javax.swing.JCheckBox(); jtfChar3Name = new javax.swing.JTextField(); jSeparator4 = new javax.swing.JSeparator(); jLabel8 = new javax.swing.JLabel(); jcbChar3F1 = new javax.swing.JCheckBox(); jcbChar3F2 = new javax.swing.JCheckBox(); jcbChar3F3 = new javax.swing.JCheckBox(); jcbChar3F4 = new javax.swing.JCheckBox(); jcbChar3F5 = new javax.swing.JCheckBox(); jcbChar3F6 = new javax.swing.JCheckBox(); jcbChar3F7 = new javax.swing.JCheckBox(); jcbChar3F8 = new javax.swing.JCheckBox(); jcbChar3F9 = new javax.swing.JCheckBox(); jcbChar3F10 = new javax.swing.JCheckBox(); jcbChar3F11 = new javax.swing.JCheckBox(); jcbChar3F12 = new javax.swing.JCheckBox(); jPanel5 = new javax.swing.JPanel(); jLabel4 = new javax.swing.JLabel(); jtfChar4Name = new javax.swing.JTextField(); jcbChar4Ativo = new javax.swing.JCheckBox(); jSeparator5 = new javax.swing.JSeparator(); jLabel9 = new javax.swing.JLabel(); jcbChar4F1 = new javax.swing.JCheckBox(); jcbChar4F2 = new javax.swing.JCheckBox(); jcbChar4F3 = new javax.swing.JCheckBox(); jcbChar4F4 = new javax.swing.JCheckBox(); jcbChar4F5 = new javax.swing.JCheckBox(); jcbChar4F6 = new javax.swing.JCheckBox(); jcbChar4F7 = new javax.swing.JCheckBox(); jcbChar4F8 = new javax.swing.JCheckBox(); jcbChar4F9 = new javax.swing.JCheckBox(); jcbChar4F10 = new javax.swing.JCheckBox(); jcbChar4F11 = new javax.swing.JCheckBox(); jcbChar4F12 = new javax.swing.JCheckBox(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("TibiaRobot by @viniciusfacco"); jbIniciar.setText("Iniciar"); jbIniciar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbIniciarActionPerformed(evt); } }); jbParar.setText("Parar"); jbParar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbPararActionPerformed(evt); } }); jTextArea1.setColumns(20); jTextArea1.setRows(5); jTextArea1.setEnabled(false); jScrollPane1.setViewportView(jTextArea1); jLabel13.setText("Tempo de Espera"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel13) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jtfTempoEspera, javax.swing.GroupLayout.PREFERRED_SIZE, 239, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jtfTempoEspera, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel13)) .addContainerGap(106, Short.MAX_VALUE)) ); jTabbedPane1.addTab("Parâmetros", jPanel1); jLabel1.setText("Nome"); jcbChar1Ativo.setText("Ativar"); jLabel14.setText("Hotkeys"); jcbChar1F1.setText("F1"); jcbChar1F2.setText("F2"); jcbChar1F3.setText("F3"); jcbChar1F4.setText("F4"); jcbChar1F5.setText("F5"); jcbChar1F6.setText("F6"); jcbChar1F7.setText("F7"); jcbChar1F8.setText("F8"); jcbChar1F9.setText("F9"); jcbChar1F10.setText("F10"); jcbChar1F11.setText("F11"); jcbChar1F12.setText("F12"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator1) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(18, 18, 18) .addComponent(jtfChar1Name, javax.swing.GroupLayout.DEFAULT_SIZE, 221, Short.MAX_VALUE) .addGap(18, 18, 18) .addComponent(jcbChar1Ativo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel14) .addGap(18, 18, 18) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jcbChar1F2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jcbChar1F4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jcbChar1F6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jcbChar1F8) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jcbChar1F10)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jcbChar1F1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jcbChar1F3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jcbChar1F5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jcbChar1F7) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jcbChar1F9))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jcbChar1F11) .addComponent(jcbChar1F12)))) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jtfChar1Name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1) .addComponent(jcbChar1Ativo)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel14) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jcbChar1F1) .addComponent(jcbChar1F3) .addComponent(jcbChar1F5) .addComponent(jcbChar1F7) .addComponent(jcbChar1F9) .addComponent(jcbChar1F11))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jcbChar1F2) .addComponent(jcbChar1F4) .addComponent(jcbChar1F6, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jcbChar1F8) .addComponent(jcbChar1F10) .addComponent(jcbChar1F12)) .addContainerGap(33, Short.MAX_VALUE)) ); jTabbedPane1.addTab("Char 1", jPanel2); jLabel7.setText("Nome"); jcbChar2Ativo.setText("Ativar"); jLabel3.setText("Hotkeys"); jcbChar2F1.setText("F1"); jcbChar2F2.setText("F2"); jcbChar2F3.setText("F3"); jcbChar2F4.setText("F4"); jcbChar2F5.setText("F5"); jcbChar2F6.setText("F6"); jcbChar2F7.setText("F7"); jcbChar2F8.setText("F8"); jcbChar2F9.setText("F9"); jcbChar2F10.setText("F10"); jcbChar2F11.setText("F11"); jcbChar2F12.setText("F12"); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator3) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jLabel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(18, 18, 18) .addComponent(jtfChar2Name, javax.swing.GroupLayout.DEFAULT_SIZE, 221, Short.MAX_VALUE) .addGap(18, 18, 18) .addComponent(jcbChar2Ativo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jLabel3) .addGap(18, 18, 18) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jcbChar2F1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jcbChar2F3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jcbChar2F5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jcbChar2F7) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jcbChar2F9)) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jcbChar2F2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jcbChar2F4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jcbChar2F6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jcbChar2F8) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jcbChar2F10))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jcbChar2F11) .addComponent(jcbChar2F12)))) .addContainerGap()) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jtfChar2Name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel7) .addComponent(jcbChar2Ativo)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jcbChar2F1) .addComponent(jcbChar2F3) .addComponent(jcbChar2F5) .addComponent(jcbChar2F7) .addComponent(jcbChar2F9) .addComponent(jcbChar2F11))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jcbChar2F2) .addComponent(jcbChar2F4) .addComponent(jcbChar2F6) .addComponent(jcbChar2F8) .addComponent(jcbChar2F10) .addComponent(jcbChar2F12)) .addContainerGap(33, Short.MAX_VALUE)) ); jTabbedPane1.addTab("Char 2", jPanel3); jLabel10.setText("Nome"); jcbChar3Ativo.setText("Ativar"); jLabel8.setText("Hotkeys"); jcbChar3F1.setText("F1"); jcbChar3F2.setText("F2"); jcbChar3F3.setText("F3"); jcbChar3F4.setText("F4"); jcbChar3F5.setText("F5"); jcbChar3F6.setText("F6"); jcbChar3F7.setText("F7"); jcbChar3F8.setText("F8"); jcbChar3F9.setText("F9"); jcbChar3F10.setText("F10"); jcbChar3F11.setText("F11"); jcbChar3F12.setText("F12"); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator4) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(jLabel10, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(18, 18, 18) .addComponent(jtfChar3Name, javax.swing.GroupLayout.DEFAULT_SIZE, 221, Short.MAX_VALUE) .addGap(18, 18, 18) .addComponent(jcbChar3Ativo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(jLabel8) .addGap(18, 18, 18) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(jcbChar3F2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jcbChar3F4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jcbChar3F6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jcbChar3F8) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jcbChar3F10)) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(jcbChar3F1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jcbChar3F3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jcbChar3F5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jcbChar3F7) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jcbChar3F9))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jcbChar3F11) .addComponent(jcbChar3F12)))) .addContainerGap()) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jtfChar3Name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel10) .addComponent(jcbChar3Ativo)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jSeparator4, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel8) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jcbChar3F1) .addComponent(jcbChar3F3) .addComponent(jcbChar3F5) .addComponent(jcbChar3F7) .addComponent(jcbChar3F9) .addComponent(jcbChar3F11))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jcbChar3F2) .addComponent(jcbChar3F4) .addComponent(jcbChar3F6) .addComponent(jcbChar3F8) .addComponent(jcbChar3F10) .addComponent(jcbChar3F12)) .addContainerGap(33, Short.MAX_VALUE)) ); jTabbedPane1.addTab("Char 3", jPanel4); jLabel4.setText("Nome"); jcbChar4Ativo.setText("Ativar"); jLabel9.setText("Hotkeys"); jcbChar4F1.setText("F1"); jcbChar4F2.setText("F2"); jcbChar4F3.setText("F3"); jcbChar4F4.setText("F4"); jcbChar4F5.setText("F5"); jcbChar4F6.setText("F6"); jcbChar4F7.setText("F7"); jcbChar4F8.setText("F8"); jcbChar4F9.setText("F9"); jcbChar4F10.setText("F10"); jcbChar4F11.setText("F11"); jcbChar4F12.setText("F12"); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator5) .addGroup(jPanel5Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(18, 18, 18) .addComponent(jtfChar4Name, javax.swing.GroupLayout.DEFAULT_SIZE, 221, Short.MAX_VALUE) .addGap(18, 18, 18) .addComponent(jcbChar4Ativo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanel5Layout.createSequentialGroup() .addComponent(jLabel9) .addGap(18, 18, 18) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addComponent(jcbChar4F2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jcbChar4F4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jcbChar4F6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jcbChar4F8) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jcbChar4F10)) .addGroup(jPanel5Layout.createSequentialGroup() .addComponent(jcbChar4F1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jcbChar4F3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jcbChar4F5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jcbChar4F7) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jcbChar4F9))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jcbChar4F11) .addComponent(jcbChar4F12)))) .addContainerGap()) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jtfChar4Name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4) .addComponent(jcbChar4Ativo)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jSeparator5, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel9) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jcbChar4F1) .addComponent(jcbChar4F3) .addComponent(jcbChar4F5) .addComponent(jcbChar4F7) .addComponent(jcbChar4F9) .addComponent(jcbChar4F11))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jcbChar4F2) .addComponent(jcbChar4F4) .addComponent(jcbChar4F6) .addComponent(jcbChar4F8) .addComponent(jcbChar4F10) .addComponent(jcbChar4F12)) .addContainerGap(33, Short.MAX_VALUE)) ); jTabbedPane1.addTab("Char 4", jPanel5); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jbIniciar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jbParar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent(jScrollPane1) .addComponent(jTabbedPane1) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 162, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jbIniciar) .addComponent(jbParar)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jbIniciarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbIniciarActionPerformed if (!jtfTempoEspera.getText().equals("")){ Char ch; jTextArea1.append("Sistema iniciado.\n"); jTextArea1.setCaretPosition(jTextArea1.getText().length()); jbIniciar.setEnabled(false); tibia = null; tibia = new TibiaRobot(this.jTextArea1, Integer.parseInt(jtfTempoEspera.getText())); if(jcbChar1Ativo.isSelected()){ ch = new Char(jcbChar1Ativo.isSelected(), jtfChar1Name.getText()); if(jcbChar1F1.isSelected()){ch.addHotKey(jcbChar1F1.getText());} if(jcbChar1F2.isSelected()){ch.addHotKey(jcbChar1F2.getText());} if(jcbChar1F3.isSelected()){ch.addHotKey(jcbChar1F3.getText());} if(jcbChar1F4.isSelected()){ch.addHotKey(jcbChar1F4.getText());} if(jcbChar1F5.isSelected()){ch.addHotKey(jcbChar1F5.getText());} if(jcbChar1F6.isSelected()){ch.addHotKey(jcbChar1F6.getText());} if(jcbChar1F7.isSelected()){ch.addHotKey(jcbChar1F7.getText());} if(jcbChar1F8.isSelected()){ch.addHotKey(jcbChar1F8.getText());} if(jcbChar1F9.isSelected()){ch.addHotKey(jcbChar1F9.getText());} if(jcbChar1F10.isSelected()){ch.addHotKey(jcbChar1F10.getText());} if(jcbChar1F11.isSelected()){ch.addHotKey(jcbChar1F11.getText());} if(jcbChar1F12.isSelected()){ch.addHotKey(jcbChar1F12.getText());} tibia.addChar(ch); } if(jcbChar2Ativo.isSelected()){ ch = new Char(jcbChar2Ativo.isSelected(), jtfChar2Name.getText()); if(jcbChar2F1.isSelected()){ch.addHotKey(jcbChar2F1.getText());} if(jcbChar2F2.isSelected()){ch.addHotKey(jcbChar2F2.getText());} if(jcbChar2F3.isSelected()){ch.addHotKey(jcbChar2F3.getText());} if(jcbChar2F4.isSelected()){ch.addHotKey(jcbChar2F4.getText());} if(jcbChar2F5.isSelected()){ch.addHotKey(jcbChar2F5.getText());} if(jcbChar2F6.isSelected()){ch.addHotKey(jcbChar2F6.getText());} if(jcbChar2F7.isSelected()){ch.addHotKey(jcbChar2F7.getText());} if(jcbChar2F8.isSelected()){ch.addHotKey(jcbChar2F8.getText());} if(jcbChar2F9.isSelected()){ch.addHotKey(jcbChar2F9.getText());} if(jcbChar2F10.isSelected()){ch.addHotKey(jcbChar2F10.getText());} if(jcbChar2F11.isSelected()){ch.addHotKey(jcbChar2F11.getText());} if(jcbChar2F12.isSelected()){ch.addHotKey(jcbChar2F12.getText());} tibia.addChar(ch); } if(jcbChar3Ativo.isSelected()){ ch = new Char(jcbChar3Ativo.isSelected(), jtfChar3Name.getText()); if(jcbChar3F1.isSelected()){ch.addHotKey(jcbChar3F1.getText());} if(jcbChar3F2.isSelected()){ch.addHotKey(jcbChar3F2.getText());} if(jcbChar3F3.isSelected()){ch.addHotKey(jcbChar3F3.getText());} if(jcbChar3F4.isSelected()){ch.addHotKey(jcbChar3F4.getText());} if(jcbChar3F5.isSelected()){ch.addHotKey(jcbChar3F5.getText());} if(jcbChar3F6.isSelected()){ch.addHotKey(jcbChar3F6.getText());} if(jcbChar3F7.isSelected()){ch.addHotKey(jcbChar3F7.getText());} if(jcbChar3F8.isSelected()){ch.addHotKey(jcbChar3F8.getText());} if(jcbChar3F9.isSelected()){ch.addHotKey(jcbChar3F9.getText());} if(jcbChar3F10.isSelected()){ch.addHotKey(jcbChar3F10.getText());} if(jcbChar3F11.isSelected()){ch.addHotKey(jcbChar3F11.getText());} if(jcbChar3F12.isSelected()){ch.addHotKey(jcbChar3F12.getText());} tibia.addChar(ch); } if(jcbChar4Ativo.isSelected()){ ch = new Char(jcbChar4Ativo.isSelected(), jtfChar4Name.getText()); if(jcbChar4F1.isSelected()){ch.addHotKey(jcbChar4F1.getText());} if(jcbChar4F2.isSelected()){ch.addHotKey(jcbChar4F2.getText());} if(jcbChar4F3.isSelected()){ch.addHotKey(jcbChar4F3.getText());} if(jcbChar4F4.isSelected()){ch.addHotKey(jcbChar4F4.getText());} if(jcbChar4F5.isSelected()){ch.addHotKey(jcbChar4F5.getText());} if(jcbChar4F6.isSelected()){ch.addHotKey(jcbChar4F6.getText());} if(jcbChar4F7.isSelected()){ch.addHotKey(jcbChar4F7.getText());} if(jcbChar4F8.isSelected()){ch.addHotKey(jcbChar4F8.getText());} if(jcbChar4F9.isSelected()){ch.addHotKey(jcbChar4F9.getText());} if(jcbChar4F10.isSelected()){ch.addHotKey(jcbChar4F10.getText());} if(jcbChar4F11.isSelected()){ch.addHotKey(jcbChar4F11.getText());} if(jcbChar4F12.isSelected()){ch.addHotKey(jcbChar4F12.getText());} tibia.addChar(ch); } thtibia = new Thread(tibia); thtibia.start(); } else { JOptionPane.showMessageDialog(null, "Tempo de espera inválido.", "Atenção", JOptionPane.WARNING_MESSAGE); } }//GEN-LAST:event_jbIniciarActionPerformed private void jbPararActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbPararActionPerformed this.jbIniciar.setEnabled(true); tibia.parar(); jTextArea1.append("Sistema parado.\n"); jTextArea1.setCaretPosition(jTextArea1.getText().length()); }//GEN-LAST:event_jbPararActionPerformed /** * @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(TibiaRobotF.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(TibiaRobotF.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(TibiaRobotF.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(TibiaRobotF.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 TibiaRobotF().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JSeparator jSeparator1; private javax.swing.JSeparator jSeparator3; private javax.swing.JSeparator jSeparator4; private javax.swing.JSeparator jSeparator5; private javax.swing.JTabbedPane jTabbedPane1; private javax.swing.JTextArea jTextArea1; private javax.swing.JButton jbIniciar; private javax.swing.JButton jbParar; private javax.swing.JCheckBox jcbChar1Ativo; private javax.swing.JCheckBox jcbChar1F1; private javax.swing.JCheckBox jcbChar1F10; private javax.swing.JCheckBox jcbChar1F11; private javax.swing.JCheckBox jcbChar1F12; private javax.swing.JCheckBox jcbChar1F2; private javax.swing.JCheckBox jcbChar1F3; private javax.swing.JCheckBox jcbChar1F4; private javax.swing.JCheckBox jcbChar1F5; private javax.swing.JCheckBox jcbChar1F6; private javax.swing.JCheckBox jcbChar1F7; private javax.swing.JCheckBox jcbChar1F8; private javax.swing.JCheckBox jcbChar1F9; private javax.swing.JCheckBox jcbChar2Ativo; private javax.swing.JCheckBox jcbChar2F1; private javax.swing.JCheckBox jcbChar2F10; private javax.swing.JCheckBox jcbChar2F11; private javax.swing.JCheckBox jcbChar2F12; private javax.swing.JCheckBox jcbChar2F2; private javax.swing.JCheckBox jcbChar2F3; private javax.swing.JCheckBox jcbChar2F4; private javax.swing.JCheckBox jcbChar2F5; private javax.swing.JCheckBox jcbChar2F6; private javax.swing.JCheckBox jcbChar2F7; private javax.swing.JCheckBox jcbChar2F8; private javax.swing.JCheckBox jcbChar2F9; private javax.swing.JCheckBox jcbChar3Ativo; private javax.swing.JCheckBox jcbChar3F1; private javax.swing.JCheckBox jcbChar3F10; private javax.swing.JCheckBox jcbChar3F11; private javax.swing.JCheckBox jcbChar3F12; private javax.swing.JCheckBox jcbChar3F2; private javax.swing.JCheckBox jcbChar3F3; private javax.swing.JCheckBox jcbChar3F4; private javax.swing.JCheckBox jcbChar3F5; private javax.swing.JCheckBox jcbChar3F6; private javax.swing.JCheckBox jcbChar3F7; private javax.swing.JCheckBox jcbChar3F8; private javax.swing.JCheckBox jcbChar3F9; private javax.swing.JCheckBox jcbChar4Ativo; private javax.swing.JCheckBox jcbChar4F1; private javax.swing.JCheckBox jcbChar4F10; private javax.swing.JCheckBox jcbChar4F11; private javax.swing.JCheckBox jcbChar4F12; private javax.swing.JCheckBox jcbChar4F2; private javax.swing.JCheckBox jcbChar4F3; private javax.swing.JCheckBox jcbChar4F4; private javax.swing.JCheckBox jcbChar4F5; private javax.swing.JCheckBox jcbChar4F6; private javax.swing.JCheckBox jcbChar4F7; private javax.swing.JCheckBox jcbChar4F8; private javax.swing.JCheckBox jcbChar4F9; private javax.swing.JTextField jtfChar1Name; private javax.swing.JTextField jtfChar2Name; private javax.swing.JTextField jtfChar3Name; private javax.swing.JTextField jtfChar4Name; private javax.swing.JTextField jtfTempoEspera; // End of variables declaration//GEN-END:variables }
true
8c2679269ea1dbcb92064d287cd26cd8f7925676
Java
WHJ1101/leetcode
/src/LeetCode297.java
UTF-8
1,926
3.578125
4
[]
no_license
import java.util.LinkedList; import java.util.Queue; public class LeetCode297 { private class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } // Encodes a tree to a single string. public String serialize(TreeNode root) { /* between tree:[] between node: , node: if val != null: val else : "null" */ StringBuilder ans = new StringBuilder("["); Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); while (!queue.isEmpty()){ TreeNode cur = queue.remove(); if(cur == null){ ans.append("null,"); }else { ans.append(cur.val + ","); queue.add(cur.left); queue.add(cur.right); } } ans.setLength(ans.length() - 1); ans.append("]"); return ans.toString(); } // Decodes your encoded data to tree. public TreeNode deserialize(String data) { String[] nodes = data.substring(1,data.length()-1).split(","); TreeNode root = getNode(nodes[0]); Queue<TreeNode> parents = new LinkedList<>(); TreeNode parent =root; boolean isLeft = true; for(int i = 1; i < nodes.length; ++i){ TreeNode cur = getNode(nodes[i]); if(isLeft){ parent.left = cur; }else{ parent.right= cur; } if(cur != null){ parents.add(cur); } isLeft = !isLeft; if(isLeft){ parent = parents.poll(); } } return root; } private TreeNode getNode(String val){ if(val.equals("null")){ return null; } return new TreeNode(Integer.parseInt(val)); } }
true
ab4716298bcb3bc48f909d547e13066f57750d22
Java
T-Davis/api_practice
/java.mysql2/src/main/java/com/java/review/entity/Enrollment.java
UTF-8
1,019
2.328125
2
[]
no_license
package com.java.review.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; /** * Created by tdavis on 4/19/17. */ @Entity public class Enrollment { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; private Integer student_id; private Integer course_id; private Integer grade; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getStudent_id() { return student_id; } public void setStudent_id(Integer student_id) { this.student_id = student_id; } public Integer getCourse_id() { return course_id; } public void setCourse_id(Integer course_id) { this.course_id = course_id; } public Integer getGrade() { return grade; } public void setGrade(Integer grade) { this.grade = grade; } }
true
695954689046857026541f3af1cb0592c81ad978
Java
Srishtiii15/Sprint1-Project
/EmployeeAssetManagementSystem/src/test/java/capgemini/emp_asset/serviceImpl/DepartmentServiceImplTest.java
UTF-8
1,729
2.234375
2
[]
no_license
package capgemini.emp_asset.serviceImpl; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import java.util.Optional; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import capgemini.emp_asset.entity.Department; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest public class DepartmentServiceImplTest { @Autowired private DepartmentServiceImpl departmentService; @Test public final void testGetAllDepartment() { List<Department> assets = departmentService.getAllDepartment(); assertThat(assets.size()>0); } @Test public final void testGetDepartment() { Optional<Department> dept = departmentService.getDepartment(1); assertThat(dept.get().getDeptId()==1); } @Test public final void testAddDepartment() { Department dept = new Department(); dept.setDeptId(2); dept.setName("Marketing"); dept=departmentService.addDepartment(dept); assertThat(dept.getName().equalsIgnoreCase("Marketing")); } @Test public final void testRemoveDepartment() { Department dept = new Department(); dept.setDeptId(2); dept.setName("IT"); dept=departmentService.addDepartment(dept); departmentService.removeDepartment(dept); assertThat(dept.getDeptId()==0); } @Test public final void testEditDepartment() { Department dept = new Department(); dept.setDeptId(1); dept.setName("CS"); dept=departmentService.editDepartment(dept); assertThat(dept.getName().equalsIgnoreCase("CS")); } }
true
7b3ee43fceeb5b2dab0c2afa7f9806af54b2e20d
Java
aurasphere/aura
/aura-android-client/app/src/main/java/co/aurasphere/aura/nebula/modules/social/ImageGenerator.java
UTF-8
7,232
2.96875
3
[ "MIT" ]
permissive
package co.aurasphere.aura.nebula.modules.social; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.os.Environment; import co.aurasphere.aura.nebula.modules.social.util.TextTooLongException; /** * Class which produces a bitmap image with text and the Facebook page name signature. */ public class ImageGenerator { /** * The starting pixel of the signature section. Used to center * the signature vertically. */ private static final int SIGNATURE_PIXEL_START = 668; /** * The maximum font size of the text to be written. */ private static final int MAX_FONT_SIZE = 50; /** * The minimum font size of the main text. */ private static final int MIN_FONT_SIZE = 10; /** * The horizontal text padding. */ private static final int TEXT_PADDING = 40; /** * Max lines number before the fonts get resized automatically. */ private static final int MAX_LINE_NUMBERS = 8; /** * Interline size. */ private static final int INTERLINE = 2; /** * The number of characters left on the line at which the program * will try to insert a line break at first blank space. */ private static final int LINE_BREAK_CHAR_MARGIN = 10; /** * The final image. */ private static Bitmap image; /** * Paint object of final image. */ private static Paint paint; /** * Canvas object of final image. */ private static Canvas canvas; /** * Main image text split by lines. */ private static String[] lines; /** * Creates an image with a quotation in the center and the page name below. * * @param backgroundFileName the background file name on external storage. * @param text the main text to write. * @param pageName the page name. * @return the image as a Bitmap. */ public static Bitmap createImageWithText(String backgroundFileName, String text, String pageName) throws TextTooLongException { // Loads background and copies it in a temp file. Bitmap background = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/" + backgroundFileName); image = background.copy(Bitmap.Config.ARGB_8888, true); // Initializing some parameters. canvas = new Canvas(image); paint = new Paint(); paint.setColor(Color.BLACK); // Text Color paint.setTextSize(MAX_FONT_SIZE); // Text Size canvas.drawBitmap(image, 0, 0, paint); // Processing and return. addPageName(pageName); addMainText(text); return image; } /** * Writes the main text. * * @param text the text to write. */ private static void addMainText(String text) throws TextTooLongException { int ascent = (int) paint.getFontMetrics().ascent; buildLines(text); int currentY = (SIGNATURE_PIXEL_START / 2) + (lines.length / 2 * ascent) + (lines.length / 2 * INTERLINE); for (int i = 0; i < lines.length; i++) { if(lines[i] != null) { writeCenterText(lines[i], currentY - (ascent * i) - INTERLINE); } } } /** * Writes the page name. * * @param pageName the page name */ private static void addPageName(String pageName) { // Used to calculate font height. Rect bounds = new Rect(); paint.getTextBounds("a", 0, 1, bounds); writeCenterText(pageName, (image.getHeight() + SIGNATURE_PIXEL_START + bounds.height()) / 2); } /** * Writes some horizontal-centered text. * * @param text the text to write. * @param y the y coord. */ private static void writeCenterText(String text, int y) { canvas.drawText(text, (image.getWidth() - paint.measureText(text)) / 2, y, paint); } /** * Method which splits the text into a line array. * * @param text the text to split. * @throws TextTooLongException if the text is too long. */ private static void buildLines(String text) throws TextTooLongException { // Max length of a single line in pixels. int lineLength = image.getWidth() - TEXT_PADDING * 2; // Max size of the text in pixels. int maxSize = MAX_LINE_NUMBERS * lineLength; int currentFontSize = MAX_FONT_SIZE + 1; // Text length in pixels. float textLength; // Gets the max font size possible to use according to text length and // image size. do { currentFontSize--; paint.setTextSize(currentFontSize); textLength = paint.measureText(text); // If I get under the minimum font size I throw an exception. if (currentFontSize < MIN_FONT_SIZE) { throw new TextTooLongException(); } } while (maxSize < textLength); // Numbers of lines of the current text. int lineUsed = Math.round(textLength / lineLength) + 1; // The actual lines of text. lines = new String[lineUsed]; // Pointer to the current char in the text. int cursor = 0; float currentLineLength; // Approximative single char length used as a reference. float singleCharLength = paint.measureText("a"); StringBuilder builder; char currentChar; // Iterates all the lines and builds them. for (int i = 0; i < lineUsed; i++) { builder = new StringBuilder(); currentLineLength = 0; // Builds the single line while there's still space in the line and // the cursor is less than the text length. while (currentLineLength < lineLength && cursor < text.length()) { currentChar = text.charAt(cursor); // Adds a char to the line. builder.append(currentChar); // Measures the current line length. currentLineLength = paint.measureText(builder.toString()); // If in the current line there are LINE_BREAK_CHAR_MARGIN // characters or less left, I try to put a linebreak at the // first blank space I find. If I can't (because last word // is longer than LINE_BREAK_CHAR_MARGIN, then I'll break // the line at the max length of the line. if (currentLineLength + (singleCharLength * LINE_BREAK_CHAR_MARGIN) >= lineLength) { if (currentChar == ' ') { // builder.append("\n"); break; } // if (currentLineLength >= lineLength) { // // builder.append("\n"); // break; // } } // Goes to the next character. cursor++; } // Builds the line. lines[i] = builder.toString(); } } }
true
75df72bddfff73d9e9b359dbdde3a0e1217c2ccd
Java
deebhatt/mybooksshelf
/src/main/java/com/mybooks/service/GuestUserService.java
UTF-8
8,010
1.984375
2
[]
no_license
package com.mybooks.service; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.TimeUnit; import javax.inject.Inject; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.mail.SimpleMailMessage; import org.springframework.stereotype.Repository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.mybooks.Controller.GuestUserController; import com.mybooks.commons.ResponseMessage; import com.mybooks.constants.ApplicationConstants; import com.mybooks.dao.GuestUserDAO; import com.mybooks.entities.GuestUser; import com.mybooks.entities.Roles; import com.mybooks.entities.UserMaster; import com.mybooks.enums.USER_ROLES; import com.mybooks.exception.DAOException; import com.mybooks.exception.DBRecordNotFoundException; import com.mybooks.exception.EmailNotFoundException; import com.mybooks.exception.EmailSenderServiceException; import com.mybooks.exception.RoleNotFoundException; import com.mybooks.exception.SmsSenderServiceException; import com.mybooks.exception.UserServiceException; import com.mybooks.service.email.EmailSenderService; import com.mybooks.service.sms.SMSLeadsMessage; import com.mybooks.service.sms.SMSSenderService; import com.mybooks.service.sms.SMSSenderServiceImpl; import com.mybooks.utility.EmailFormatter; import com.mybooks.utility.PropertiesUtil; import com.mybooks.utility.SMSFormatter; import com.mybooks.utility.SecurityUtil; @Service("guestuserService") @Repository public class GuestUserService { private static final Log LOG = LogFactory .getLog(GuestUserService.class); @Inject private GuestUserDAO guestuserDAO; @Inject private EmailSenderService emailSender; @Inject private SMSSenderService smsSender; @Inject private UserService userService; @Transactional(rollbackFor=DAOException.class) public ResponseMessage sendVerificationTokentoUser(String mobileNo) { GuestUser guestuser = null; int generateToken = 0; try { int startValue = Integer.parseInt(PropertiesUtil.getProperty("email.token.start")); int endValue = Integer.parseInt(PropertiesUtil.getProperty("email.token.end")); generateToken = SecurityUtil.generateRandomNumber(startValue, endValue); guestuser = guestuserDAO.findUserByMobileNo(mobileNo); //User already found so update the user guestuser.setTokenCreatedDate(System.currentTimeMillis()); guestuser.setToken((long) generateToken); guestuserDAO.update(guestuser); } catch (DBRecordNotFoundException e) { LOG.debug("Guest User Not Found, so create a new Guest User"); } catch(DAOException e) { LOG.error("There was a technical error while updating Guest User", e); return new ResponseMessage(ResponseMessage.Type.danger, "There was a technical error while updating Guest User. Please try again"); } try { if(guestuser == null) { guestuser = new GuestUser(); guestuser.setMobileNumber(mobileNo); guestuser.setToken((long) generateToken); guestuser.setTokenCreatedDate(System.currentTimeMillis()); guestuserDAO.persist(guestuser); } } catch (DAOException e) { LOG.error("There was a technical error while adding Guest User", e); return new ResponseMessage(ResponseMessage.Type.danger, "There was a technical error while adding Guest User. Please try again"); } // Encode MobileNumber String cookieSecret = SecurityUtil.encodeValue(mobileNo); // SEND EMAIL NOTIFICATION /*SimpleMailMessage message = EmailFormatter.generateTokenEmailMessage(String.valueOf(generateEmailToken), guestuser); try { emailSender.sendEmail(message); } catch (EmailSenderServiceException e) { LOG.error("Errors while sending COD token", e); return new ResponseMessage(ResponseMessage.Type.danger, "There was a technical error while sending Email. Please try again"); }*/ //SEND SMS NOTIFICATION /*SMSLeadsMessage message = SMSFormatter.generateTokenforCashOnDelivery(String.valueOf(generateToken), guestuser); try { smsSender.sendSMS(message); } catch (SmsSenderServiceException e) { LOG.error("Errors while sending COD token", e); return new ResponseMessage(ResponseMessage.Type.danger, "There was a technical error while sending SMS. Please try again"); }*/ return new ResponseMessage( ResponseMessage.Type.success, "The token has been sent to the mobile.", cookieSecret); } public ResponseMessage verifyGuestUSerToken(Long token, String cookieSecret) { //Decode the token value String guestUserMobile = null; if(!cookieSecret.equals("CookieNotFound")) { guestUserMobile = SecurityUtil.decodeValue(cookieSecret); } else { return new ResponseMessage(ResponseMessage.Type.danger, "The token is expired. Please try again!!!"); } GuestUser user; try { user = guestuserDAO.findUserByMobileNoandToken(guestUserMobile, token); Long expiretime = user.getTokenCreatedDate(); Long current = System.currentTimeMillis(); Long mins = TimeUnit.MILLISECONDS.toMinutes(current-expiretime); Long codExpireTime = Long.valueOf(PropertiesUtil.getProperty("cod.token.expire")); if(mins > codExpireTime) { return new ResponseMessage(ResponseMessage.Type.danger, "The token is expired. Please try again!!!"); } else { if(!confirmUserisRegisterdwithMobileNo(guestUserMobile)) { createGuestUserwithMobileNo(guestUserMobile); } return new ResponseMessage( ResponseMessage.Type.success, "The token is valid"); } } catch (DBRecordNotFoundException e) { return new ResponseMessage(ResponseMessage.Type.danger, "The token is incorrect."); } catch(UserServiceException e) { return new ResponseMessage(ResponseMessage.Type.danger, "There was a technical error while registering. Please try again"); } } public void createGuestUserwithEmail(String email) throws UserServiceException { try { UserMaster user = new UserMaster(); user.setEmail(email); user.setVerified(ApplicationConstants.EMAIL_VERIFIED_YES); user.setActive(ApplicationConstants.USER_DEACTIVATED); Roles assignRole = userService.findRoleByName(USER_ROLES.ROLE_GUEST.toString()); List<Roles> listOfRoles = new ArrayList<Roles>(); listOfRoles.add(assignRole); user.setListOfRoles(listOfRoles); userService.saveUser(user); } catch (RoleNotFoundException e) { LOG.error("Assigned Role doesnot exist"); throw new UserServiceException(e); } catch (UserServiceException e) { LOG.error("There was a technical error while registering", e); throw new UserServiceException(e); } } public void createGuestUserwithMobileNo(String mobileNo) throws UserServiceException { try { UserMaster user = new UserMaster(); user.setMobileNumber(mobileNo); user.setVerified(ApplicationConstants.MOBILENO_VERIFIED_YES); user.setActive(ApplicationConstants.USER_DEACTIVATED); Roles assignRole = userService.findRoleByName(USER_ROLES.ROLE_GUEST.toString()); List<Roles> listOfRoles = new ArrayList<Roles>(); listOfRoles.add(assignRole); user.setListOfRoles(listOfRoles); userService.saveUser(user); } catch (RoleNotFoundException e) { LOG.error("Assigned Role doesnot exist"); throw new UserServiceException(e); } catch (UserServiceException e) { LOG.error("There was a technical error while registering", e); throw new UserServiceException(e); } } private boolean confirmUserisRegisterdwithEmail(String guestUserEmail) { try { userService.findByEmail(guestUserEmail); return true; } catch (EmailNotFoundException e) { LOG.debug("GuestUser not Found"); return false; } } private boolean confirmUserisRegisterdwithMobileNo(String guestUserMobileNo) { try { userService.findByMobileNo(guestUserMobileNo); return true; } catch (DBRecordNotFoundException e) { LOG.debug("GuestUser not Found"); return false; } } }
true
3f16d9dfdecf2d349e02f4f3692ebc0ab0c3f08d
Java
jacklizekun/Java_Base
/Javabase_Pro/Six/Override/Dog2Ha.java
UTF-8
188
2.28125
2
[]
no_license
package Override; /** * * @author 李泽坤 * */ public class Dog2Ha extends Dog { @Override public void sleep() { System.out.println("……"); } }
true
2f6dfaa0653256dcc53184f8aeaffa75f65e9a22
Java
CardioVascular-Research-Group/waveform-persistence-portlet
/docroot/WEB-INF/service/edu/jhu/cvrg/waveform/main/dbpersistence/service/CoordinateLocalServiceUtil.java
UTF-8
13,576
1.960938
2
[]
no_license
/** * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved. * * This library 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 2.1 of the License, or (at your option) * any later version. * * This library 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. */ package edu.jhu.cvrg.waveform.main.dbpersistence.service; import com.liferay.portal.kernel.bean.PortletBeanLocatorUtil; import com.liferay.portal.kernel.util.ReferenceRegistry; import com.liferay.portal.service.InvokableLocalService; /** * The utility for the coordinate local service. This utility wraps {@link edu.jhu.cvrg.waveform.main.dbpersistence.service.impl.CoordinateLocalServiceImpl} and is the primary access point for service operations in application layer code running on the local server. * * <p> * This is a local service. Methods of this service will not have security checks based on the propagated JAAS credentials because this service can only be accessed from within the same VM. * </p> * * @author bbenite1 * @see CoordinateLocalService * @see edu.jhu.cvrg.waveform.main.dbpersistence.service.base.CoordinateLocalServiceBaseImpl * @see edu.jhu.cvrg.waveform.main.dbpersistence.service.impl.CoordinateLocalServiceImpl * @generated */ public class CoordinateLocalServiceUtil { /* * NOTE FOR DEVELOPERS: * * Never modify this class directly. Add custom service methods to {@link edu.jhu.cvrg.waveform.main.dbpersistence.service.impl.CoordinateLocalServiceImpl} and rerun ServiceBuilder to regenerate this class. */ /** * Adds the coordinate to the database. Also notifies the appropriate model listeners. * * @param coordinate the coordinate * @return the coordinate that was added * @throws SystemException if a system exception occurred */ public static edu.jhu.cvrg.waveform.main.dbpersistence.model.Coordinate addCoordinate( edu.jhu.cvrg.waveform.main.dbpersistence.model.Coordinate coordinate) throws com.liferay.portal.kernel.exception.SystemException { return getService().addCoordinate(coordinate); } /** * Creates a new coordinate with the primary key. Does not add the coordinate to the database. * * @param CoordinateID the primary key for the new coordinate * @return the new coordinate */ public static edu.jhu.cvrg.waveform.main.dbpersistence.model.Coordinate createCoordinate( long CoordinateID) { return getService().createCoordinate(CoordinateID); } /** * Deletes the coordinate with the primary key from the database. Also notifies the appropriate model listeners. * * @param CoordinateID the primary key of the coordinate * @return the coordinate that was removed * @throws PortalException if a coordinate with the primary key could not be found * @throws SystemException if a system exception occurred * @throws edu.jhu.cvrg.waveform.main.dbpersistence.NoSuchCoordinateException */ public static edu.jhu.cvrg.waveform.main.dbpersistence.model.Coordinate deleteCoordinate( long CoordinateID) throws com.liferay.portal.kernel.exception.PortalException, com.liferay.portal.kernel.exception.SystemException, edu.jhu.cvrg.waveform.main.dbpersistence.NoSuchCoordinateException { return getService().deleteCoordinate(CoordinateID); } /** * Deletes the coordinate from the database. Also notifies the appropriate model listeners. * * @param coordinate the coordinate * @return the coordinate that was removed * @throws SystemException if a system exception occurred */ public static edu.jhu.cvrg.waveform.main.dbpersistence.model.Coordinate deleteCoordinate( edu.jhu.cvrg.waveform.main.dbpersistence.model.Coordinate coordinate) throws com.liferay.portal.kernel.exception.SystemException { return getService().deleteCoordinate(coordinate); } public static com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery() { return getService().dynamicQuery(); } /** * Performs a dynamic query on the database and returns the matching rows. * * @param dynamicQuery the dynamic query * @return the matching rows * @throws SystemException if a system exception occurred */ @SuppressWarnings("rawtypes") public static java.util.List dynamicQuery( com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery) throws com.liferay.portal.kernel.exception.SystemException { return getService().dynamicQuery(dynamicQuery); } /** * Performs a dynamic query on the database and returns a range of the matching rows. * * <p> * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. * </p> * * @param dynamicQuery the dynamic query * @param start the lower bound of the range of model instances * @param end the upper bound of the range of model instances (not inclusive) * @return the range of matching rows * @throws SystemException if a system exception occurred */ @SuppressWarnings("rawtypes") public static java.util.List dynamicQuery( com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery, int start, int end) throws com.liferay.portal.kernel.exception.SystemException { return getService().dynamicQuery(dynamicQuery, start, end); } /** * Performs a dynamic query on the database and returns an ordered range of the matching rows. * * <p> * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. * </p> * * @param dynamicQuery the dynamic query * @param start the lower bound of the range of model instances * @param end the upper bound of the range of model instances (not inclusive) * @param orderByComparator the comparator to order the results by (optionally <code>null</code>) * @return the ordered range of matching rows * @throws SystemException if a system exception occurred */ @SuppressWarnings("rawtypes") public static java.util.List dynamicQuery( com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery, int start, int end, com.liferay.portal.kernel.util.OrderByComparator orderByComparator) throws com.liferay.portal.kernel.exception.SystemException { return getService() .dynamicQuery(dynamicQuery, start, end, orderByComparator); } /** * Returns the number of rows that match the dynamic query. * * @param dynamicQuery the dynamic query * @return the number of rows that match the dynamic query * @throws SystemException if a system exception occurred */ public static long dynamicQueryCount( com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery) throws com.liferay.portal.kernel.exception.SystemException { return getService().dynamicQueryCount(dynamicQuery); } public static edu.jhu.cvrg.waveform.main.dbpersistence.model.Coordinate fetchCoordinate( long CoordinateID) throws com.liferay.portal.kernel.exception.SystemException { return getService().fetchCoordinate(CoordinateID); } /** * Returns the coordinate with the primary key. * * @param CoordinateID the primary key of the coordinate * @return the coordinate * @throws PortalException if a coordinate with the primary key could not be found * @throws SystemException if a system exception occurred * @throws edu.jhu.cvrg.waveform.main.dbpersistence.NoSuchCoordinateException */ public static edu.jhu.cvrg.waveform.main.dbpersistence.model.Coordinate getCoordinate( long CoordinateID) throws com.liferay.portal.kernel.exception.PortalException, com.liferay.portal.kernel.exception.SystemException, edu.jhu.cvrg.waveform.main.dbpersistence.NoSuchCoordinateException { return getService().getCoordinate(CoordinateID); } public static com.liferay.portal.model.PersistedModel getPersistedModel( java.io.Serializable primaryKeyObj) throws com.liferay.portal.kernel.exception.PortalException, com.liferay.portal.kernel.exception.SystemException { return getService().getPersistedModel(primaryKeyObj); } /** * Returns a range of all the coordinates. * * <p> * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. * </p> * * @param start the lower bound of the range of coordinates * @param end the upper bound of the range of coordinates (not inclusive) * @return the range of coordinates * @throws SystemException if a system exception occurred */ public static java.util.List<edu.jhu.cvrg.waveform.main.dbpersistence.model.Coordinate> getCoordinates( int start, int end) throws com.liferay.portal.kernel.exception.SystemException { return getService().getCoordinates(start, end); } /** * Returns the number of coordinates. * * @return the number of coordinates * @throws SystemException if a system exception occurred */ public static int getCoordinatesCount() throws com.liferay.portal.kernel.exception.SystemException { return getService().getCoordinatesCount(); } /** * Updates the coordinate in the database or adds it if it does not yet exist. Also notifies the appropriate model listeners. * * @param coordinate the coordinate * @return the coordinate that was updated * @throws SystemException if a system exception occurred */ public static edu.jhu.cvrg.waveform.main.dbpersistence.model.Coordinate updateCoordinate( edu.jhu.cvrg.waveform.main.dbpersistence.model.Coordinate coordinate) throws com.liferay.portal.kernel.exception.SystemException { return getService().updateCoordinate(coordinate); } /** * Updates the coordinate in the database or adds it if it does not yet exist. Also notifies the appropriate model listeners. * * @param coordinate the coordinate * @param merge whether to merge the coordinate with the current session. See {@link com.liferay.portal.service.persistence.BatchSession#update(com.liferay.portal.kernel.dao.orm.Session, com.liferay.portal.model.BaseModel, boolean)} for an explanation. * @return the coordinate that was updated * @throws SystemException if a system exception occurred */ public static edu.jhu.cvrg.waveform.main.dbpersistence.model.Coordinate updateCoordinate( edu.jhu.cvrg.waveform.main.dbpersistence.model.Coordinate coordinate, boolean merge) throws com.liferay.portal.kernel.exception.SystemException { return getService().updateCoordinate(coordinate, merge); } /** * Returns the Spring bean ID for this bean. * * @return the Spring bean ID for this bean */ public static java.lang.String getBeanIdentifier() { return getService().getBeanIdentifier(); } /** * Sets the Spring bean ID for this bean. * * @param beanIdentifier the Spring bean ID for this bean */ public static void setBeanIdentifier(java.lang.String beanIdentifier) { getService().setBeanIdentifier(beanIdentifier); } public static java.lang.Object invokeMethod(java.lang.String name, java.lang.String[] parameterTypes, java.lang.Object[] arguments) throws java.lang.Throwable { return getService().invokeMethod(name, parameterTypes, arguments); } public static edu.jhu.cvrg.waveform.main.dbpersistence.model.Coordinate addCoordinate( long liferayUserId, long liferayGroupId, long liferayCompanyId, double xCoord, double yCoord) throws com.liferay.portal.kernel.exception.PortalException, com.liferay.portal.kernel.exception.SystemException { return getService() .addCoordinate(liferayUserId, liferayGroupId, liferayCompanyId, xCoord, yCoord); } public static edu.jhu.cvrg.waveform.main.dbpersistence.model.Coordinate updateCoordinate( long coordID, double xCoord, double yCoord) throws com.liferay.portal.kernel.exception.PortalException, com.liferay.portal.kernel.exception.SystemException { return getService().updateCoordinate(coordID, xCoord, yCoord); } public static void clearService() { _service = null; } public static CoordinateLocalService getService() { if (_service == null) { InvokableLocalService invokableLocalService = (InvokableLocalService)PortletBeanLocatorUtil.locate(ClpSerializer.getServletContextName(), CoordinateLocalService.class.getName()); if (invokableLocalService instanceof CoordinateLocalService) { _service = (CoordinateLocalService)invokableLocalService; } else { _service = new CoordinateLocalServiceClp(invokableLocalService); } ReferenceRegistry.registerReference(CoordinateLocalServiceUtil.class, "_service"); } return _service; } /** * @deprecated */ public void setService(CoordinateLocalService service) { } private static CoordinateLocalService _service; }
true
be70c6caf1c236beba2e6b1fb74ffa98874a777b
Java
keshwans/storio
/storio-content-resolver/src/test/java/com/pushtorefresh/storio/contentresolver/operation/delete/PreparedDeleteByQueryTest.java
UTF-8
1,249
1.890625
2
[ "Apache-2.0" ]
permissive
package com.pushtorefresh.storio.contentresolver.operation.delete; import org.junit.Test; import rx.Observable; public class PreparedDeleteByQueryTest { @Test public void deleteBlocking() { final DeleteStub deleteStub = DeleteStub.newInstanceForDeleteByQuery(); final DeleteResult deleteResult = deleteStub.storIOContentResolver .delete() .byQuery(deleteStub.testItemDeleteQueryMap.get(deleteStub.testItems.get(0))) .withDeleteResolver(deleteStub.deleteResolverForQuery) .prepare() .executeAsBlocking(); deleteStub.verifyBehaviorForDeleteByQuery(deleteResult); } @Test public void deleteObservable() { final DeleteStub deleteStub = DeleteStub.newInstanceForDeleteByQuery(); final Observable<DeleteResult> deleteResultObservable = deleteStub.storIOContentResolver .delete() .byQuery(deleteStub.testItemDeleteQueryMap.get(deleteStub.testItems.get(0))) .withDeleteResolver(deleteStub.deleteResolverForQuery) .prepare() .createObservable(); deleteStub.verifyBehaviorForDeleteByQuery(deleteResultObservable); } }
true
60c5d8c465d6a7bbee1abf30c032086507196679
Java
lupur/XML_FTN
/backend/services/vehicle-management/src/main/java/com/ftnxml/vehiclemanagement/messaging/IVehicleMessaging.java
UTF-8
307
1.820313
2
[]
no_license
package com.ftnxml.vehiclemanagement.messaging; import org.springframework.kafka.annotation.KafkaListener; public interface IVehicleMessaging { String NEW_ORDER_REQUEST_TOPIC = "new-order-request"; @KafkaListener(topics = NEW_ORDER_REQUEST_TOPIC) void consumeOrderRequest(String content); }
true
97a8321b4ff1698acaeae1d0c9bc0b2ba6f9a25b
Java
LuxTenebris/TimeManager
/app/src/main/java/com/example/mikhailtalancev/myapplication/GroupActivity.java
UTF-8
17,020
2.109375
2
[]
no_license
package com.example.mikhailtalancev.myapplication; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.QueryDocumentSnapshot; import com.google.firebase.firestore.QuerySnapshot; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class GroupActivity extends AppCompatActivity { FirebaseFirestore db = FirebaseFirestore.getInstance(); DocumentReference docRef; String idg; String description; String priority; String name; String date; String TAG = "Tag"; ArrayList<String> doc_id = new ArrayList<String>(); ArrayList<String> names = new ArrayList<String>(); ArrayList<String> priorities = new ArrayList<String>(); ArrayList<String> dates = new ArrayList<String>(); ArrayList<String> descriptions = new ArrayList<String>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_group); Intent intent = getIntent(); idg = intent.getStringExtra("id"); description = intent.getStringExtra("description"); name = (String) intent.getStringExtra("name"); priority = (String) intent.getStringExtra("priority"); date = (String) intent.getStringExtra("date"); docRef = db.collection("groups").document(idg); TextView note_name = (TextView) findViewById(R.id.GroupName); note_name.setText("Name: "+name); TextView note_priority = (TextView) findViewById(R.id.GroupPriority); note_priority.setText("Priority: "+priority); TextView note_date = (TextView) findViewById(R.id.GroupDate); note_date.setText("Date: "+date); TextView note_description = (TextView) findViewById(R.id.GroupDescription); note_description.setText("Description: "+description); db.collection("group_" + name) .get() .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { List<State> states = new ArrayList(); for (QueryDocumentSnapshot document : task.getResult()) { String tname = (String) document.get("name"); String tpriority = (String) document.get("priority"); String tdate = (String) document.get("date"); names.add(tname); priorities.add(tpriority); dates.add(tdate); descriptions.add((String) document.get("description")); doc_id.add(document.getId()); int color; assert tpriority != null; switch (tpriority) { case "High": color = Color.parseColor("#6773b7"); break; case "Middle": color = Color.parseColor("#198f66"); break; case "Low": color = Color.parseColor("#89c3f1"); break; default: color = 1; } states.add(new State(tname, tpriority, tdate, color)); Log.d("TAG", document.getId() + " => " + document.get("name")); } ListView countriesList = (ListView) findViewById(R.id.lvGroupTasks); // создаем адаптер StateAdapter stateAdapter = new StateAdapter(GroupActivity.this, R.layout.day_task_item, states); // устанавливаем адаптер countriesList.setAdapter(stateAdapter); // слушатель выбора в списке AdapterView.OnItemClickListener itemListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View v, int position, long id) { // получаем выбранный пункт Intent intent = new Intent(GroupActivity.this, GroupNoteActivity.class); intent.putExtra("id", doc_id.get((int) id)); intent.putExtra("name", names.get((int) id)); intent.putExtra("description", descriptions.get((int) id)); intent.putExtra("date", dates.get((int) id)); intent.putExtra("priority", priorities.get((int) id)); intent.putExtra("namegr", name); intent.putExtra("descriptiongr", description); intent.putExtra("dategr", date); intent.putExtra("idgr", idg); intent.putExtra("prioritygr", priority); startActivity(intent); } }; countriesList.setOnItemClickListener(itemListener); } else { Log.d("TAG", "Error getting documents: ", task.getException()); } } }); } @Override protected Dialog onCreateDialog(int id) { switch (id) { case 1: final String[] mAddName = {"Yes", "No"}; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Was group successful?"); // заголовок для диалога builder.setItems(mAddName, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int item) { Intent intent = new Intent(GroupActivity.this, GroupTaskActivity.class); switch (item) { case 0: Map<String, Object> note = new HashMap<>(); note.put("name", name); note.put("description", description); note.put("date", date); note.put("priority", priority); note.put("success", "True"); db.collection("archive_groups") .add(note) .addOnSuccessListener(new OnSuccessListener<DocumentReference>() { @Override public void onSuccess(DocumentReference documentReference) { Log.d("Tag", "DocumentSnapshot added with ID: " + documentReference.getId()); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.w("Tag", "Error adding document", e); } }); docRef.delete(); db.collection("group_" + name) .get() .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot document : task.getResult()) { document.getReference().delete(); Log.d(TAG, document.getId() + " => " + document.getData()); } } else { Log.d(TAG, "Error getting documents: ", task.getException()); } } }); startActivity(intent); finish(); break; case 1: Map<String, Object> note1 = new HashMap<>(); note1.put("name", name); note1.put("description", description); note1.put("date", date); note1.put("priority", priority); note1.put("success", "False"); db.collection("archive_groups") .add(note1) .addOnSuccessListener(new OnSuccessListener<DocumentReference>() { @Override public void onSuccess(DocumentReference documentReference) { Log.d("Tag", "DocumentSnapshot added with ID: " + documentReference.getId()); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.w("Tag", "Error adding document", e); } }); db.collection("group_" + name) .get() .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot document : task.getResult()) { document.getReference().delete(); Log.d(TAG, document.getId() + " => " + document.getData()); } } else { Log.d(TAG, "Error getting documents: ", task.getException()); } } }); docRef.delete(); startActivity(intent); finish(); break; } } }); builder.setCancelable(true); return builder.create(); default: return null; } } public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.group_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.DeleteThisGr: docRef.delete(); Toast.makeText(this, "Group was deleted!", Toast.LENGTH_SHORT).show(); Intent intent2 = new Intent(this, GroupTaskActivity.class); db.collection("group_" + name) .get() .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot document : task.getResult()) { document.getReference().delete(); Log.d(TAG, document.getId() + " => " + document.getData()); } } else { Log.d(TAG, "Error getting documents: ", task.getException()); } } }); db.collection("archive_group_note" + name) .get() .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot document : task.getResult()) { document.getReference().delete(); Log.d(TAG, document.getId() + " => " + document.getData()); } } else { Log.d(TAG, "Error getting documents: ", task.getException()); } } }); startActivity(intent2); finish(); case R.id.CanselThisGr: showDialog(1); return true; case R.id.addGroupTask: Intent intent = new Intent(this, AddGroupTaskActivity.class); intent.putExtra("name", name); intent.putExtra("description", description); intent.putExtra("date", date); intent.putExtra("id", idg); intent.putExtra("priority", priority); startActivity(intent); return true; case R.id.main: Intent intent4 = new Intent(this, MainActivity.class); startActivity(intent4); return true; case R.id.settings: Intent intent3 = new Intent(this, SettingsActivity.class); startActivity(intent3); return true; case R.id.profile: Intent intent1 = new Intent(this, ProfileActivity.class); startActivity(intent1); return true; default: return super.onOptionsItemSelected(item); } } @Override public void onBackPressed() { Intent intent = new Intent(this, GroupTaskActivity.class); startActivity(intent); finish(); } }
true
f7c59c8ab259f8b1440d73320b2579ce27c180c3
Java
robsonmrsp/react-netflics
/src/main/java/br/com/netflics/JPAConfig.java
UTF-8
1,516
2.078125
2
[]
no_license
package br.com.netflics; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.core.io.Resource; import org.springframework.jdbc.datasource.init.DataSourceInitializer; import org.springframework.jdbc.datasource.init.DatabasePopulator; import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; import org.springframework.transaction.annotation.EnableTransactionManagement; /** * * @author JSetup * @see <a href="http://jsetup.com/">JSetup</a> */ @Configuration public class JPAConfig { @Autowired private Environment env; @Value("classpath:db/seed.sql") private Resource seedScript; @Bean public DataSourceInitializer dataSourceInitializer(final DataSource dataSource) { final DataSourceInitializer initializer = new DataSourceInitializer(); initializer.setDataSource(dataSource); initializer.setDatabasePopulator(databasePopulator()); return initializer; } private DatabasePopulator databasePopulator() { final ResourceDatabasePopulator populator = new ResourceDatabasePopulator(); populator.addScript(seedScript); populator.setIgnoreFailedDrops(true); populator.setContinueOnError(true); return populator; } }
true
db87b47f089d467118b2920a4f63b7ae231560e5
Java
Hemaladani2711/RoutePlanner
/app/src/main/java/com/example/yagnikbhatt/routeplanner/reminders/AlarmScheduler.java
UTF-8
2,546
2.1875
2
[]
no_license
package com.example.yagnikbhatt.routeplanner.reminders; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.ContentValues; import android.content.Context; import android.util.Log; import com.example.yagnikbhatt.routeplanner.Data.DatabaseContract; import java.util.Calendar; /** * Created by hemaladani on 1/23/18. */ public class AlarmScheduler { public static String TAG="Scheduler";//AlarmScheduler.class.getSimpleName(); public static String Content="Content"; public void createAlarm(Context mContext, ContentValues contentValues){ AlarmManager alarmManager=(AlarmManager) mContext.getSystemService(mContext.ALARM_SERVICE); //NotificationManager manager=mContext.get PendingIntent pendingIntent=ReminderAlarmService.getReminderPendingIntent(mContext,contentValues); Log.i(TAG,"Description: "+contentValues.getAsString(DatabaseContract.columns.description)+" | Date: "+contentValues.getAsLong(DatabaseContract.columns.date)); alarmManager.setExact(AlarmManager.RTC_WAKEUP,contentValues.getAsLong(DatabaseContract.columns.date),pendingIntent); Calendar calendar=Calendar.getInstance(); calendar.setTimeInMillis(contentValues.getAsLong(DatabaseContract.columns.date)); Log.i(AlarmScheduler.class.getSimpleName(),"Alarm set at"+ calendar.getTime()); } public int createquery(){ return 0; } /* public void setRepeatingAlarm(Context mContext, List<ContentValues> myTasks){ AlarmManager alarmManager=(AlarmManager) mContext.getSystemService(mContext.ALARM_SERVICE); //NotificationManager manager=mContext.get for(int i=0;i<myTasks.size();i++) { ContentValues contentValues=myTasks.get(i); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(contentValues.getAsLong(DatabaseContract.columns.date)); Intent intent1=new Intent(mContext, ShowNotificationBroadcast.class); intent1.putExtra(Content,contentValues); //intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pendingIntent=PendingIntent.getBroadcast(mContext,0,intent1,PendingIntent.FLAG_CANCEL_CURRENT); Log.i(AlarmScheduler.class.getSimpleName(), "Alarm set at" + calendar.getTime()+" for :"+contentValues.getAsString(DatabaseContract.columns.description)); alarmManager.setExact(AlarmManager.RTC_WAKEUP, contentValues.getAsLong(DatabaseContract.columns.date), pendingIntent); contentValues.clear(); } }*/ }
true
0101d443cf05eeccbb4b53b11d45ef7d8643c0a2
Java
danielSaldivia/Supertecbook
/src/java/controlador/ControllerComuna.java
UTF-8
1,879
1.835938
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 controlador; import ControladorJpa.ComunaJpaController; import Model.Comuna; import java.time.LocalDateTime; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.request; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.portlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import org.springframework.web.servlet.view.RedirectView; /** * * @author yo */ @Controller public class ControllerComuna { @RequestMapping(value = "/comuna", method = RequestMethod.GET) public ModelAndView showForm() { return new ModelAndView("comuna", "comuna", new Comuna()); } @RequestMapping(value = "/addcomuna", method = RequestMethod.POST) public String submit(@Valid @ModelAttribute("comuna") Comuna com, BindingResult result, ModelMap model) { if (result.hasErrors()) { return "error"; } model.addAttribute("nombre", com.getNombre()); model.addAttribute("codigo", com.getCodigo()); return "addcomuna"; } }
true
8ee09bbfac6ae51b673bb826aa688bcd6099b222
Java
SemanticBeeng/compass2
/compass2-core/src/main/java/no/ovitas/compass2/kb/factory/KBFactory.java
UTF-8
2,584
2.109375
2
[]
no_license
package no.ovitas.compass2.kb.factory; import no.ovitas.compass2.config.ConfigurationManager; import no.ovitas.compass2.config.settings.KnowledgeBaseSettingPlugin; import no.ovitas.compass2.exception.ConfigurationException; import no.ovitas.compass2.kb.KnowledgeBaseManager; import no.ovitas.compass2.kb.TopicNameIndexer; import no.ovitas.compass2.util.CompassUtil; import no.ovitas.compass2.util.loaders.ImplementationLoader; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.context.ApplicationContext; /** * @author magyar * @version 1.0 */ public class KBFactory { private static KBFactory instance = null; protected ConfigurationManager configurationManager; protected String kbFile; protected boolean loadOnStartup; private Log log = LogFactory.getLog(getClass()); protected KnowledgeBaseManager manager = null;; public KBFactory() { ApplicationContext context = CompassUtil.getApplicationContext(); configurationManager = (ConfigurationManager) context .getBean("configurationManager"); } public KnowledgeBaseManager getKBImplementation() throws ConfigurationException { if (manager == null) { log.info("Started Initializing KnowledgeBaseManager..."); if (configurationManager.getKnowledgeBasePlugin() == null) { log.info("KnowledgeBaseManager not available!"); return null; } KnowledgeBaseSettingPlugin defaultKnowledgeBase = configurationManager .getKnowledgeBasePlugin().getDefaultKnowledgeBase(); log.info("Load default knowledge base manager: " + defaultKnowledgeBase.getId()); manager = ImplementationLoader.loadInstance( defaultKnowledgeBase.getImplementation(), KnowledgeBaseManager.class); if (manager != null) { manager.setConfiguration(configurationManager); manager.init(defaultKnowledgeBase.getParams().getParams()); TopicNameIndexer topicNameIndexerImplementation = TopicNameIndexerFactory .getInstance().getTopicNameIndexerImplementation(); manager.setTopicNameIndexer(topicNameIndexerImplementation); log.info("Finished Initalizing KnowledgeBaseManager!"); } else { log.info("KnowledgeBaseManager not available!"); } } return manager; } public static KBFactory getInstance() { if (instance == null) { instance = new KBFactory(); } return instance; } public static void clear() { if (instance != null) instance.manager = null; TopicNameIndexerFactory.clear(); } }
true
43f8db310ebae2d71e3d04109c7fc886818e7a4b
Java
program02/SpringMvcHbCrudNB113TC8572
/src/java/com/exam/StudentController.java
UTF-8
1,908
2.390625
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 com.exam; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /** * * @author Student */ @Controller public class StudentController { @RequestMapping("/") public String home() { return "index"; } @RequestMapping(value = "/insert", method = RequestMethod.POST) public String insert(@ModelAttribute() Student student, Model m) { StudentDao d = new StudentDao(); d.insert(student); m.addAttribute("students", d.show()); return "result"; } @RequestMapping(value = "/show") public String show(@ModelAttribute() Student student, Model m) { StudentDao d = new StudentDao(); m.addAttribute("students", d.show()); return "result"; } @RequestMapping(value = "/update", method = RequestMethod.POST) public String update(@ModelAttribute() Student student, Model m) { StudentDao d = new StudentDao(); d.update(student); m.addAttribute("students", d.show()); return "result"; } @RequestMapping(value = "/updatef", method = RequestMethod.POST) public String updatef(@ModelAttribute() Student student, Model m) { m.addAttribute("s", student); return "updatef"; } @RequestMapping(value = "/delete") public String delete(@ModelAttribute() Student student, Model m) { StudentDao d = new StudentDao(); d.delete(student); m.addAttribute("students", d.show()); return "result"; } }
true
faea06a772ab40733781f5a8eb4183d8abe9fd59
Java
Shindred/pointer-file
/src/FileManager.java
UTF-8
1,195
3
3
[]
no_license
import java.io.*; public class FileManager { static void write(File file, Zooclub zooclub) { try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) { bw.write(zooclub.toString()); } catch (IOException e) { e.printStackTrace(); } } static void supplement(File file, Zooclub zooclub) { try (BufferedWriter bw = new BufferedWriter(new FileWriter(file, true))) { bw.newLine(); bw.write(zooclub.toString()); } catch (IOException e) { e.printStackTrace(); } } static void serialize(Zooclub zooclub, File file) { try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))) { oos.writeObject(zooclub); } catch (IOException e) { e.printStackTrace(); } } static void deSerialize(File file) { try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) { Zooclub zoo = (Zooclub) ois.readObject(); System.out.println(zoo); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } }
true
cdea9dba29603cc27290a970cffe4fec891fe349
Java
RingoDev/stocks
/src/main/java/com/ringodev/stocks/service/stocks/StocksCommandLineRunner.java
UTF-8
539
1.617188
2
[]
no_license
package com.ringodev.stocks.service.stocks; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; @Component public class StocksCommandLineRunner implements CommandLineRunner { private final StocksRepository repository; @Autowired StocksCommandLineRunner(StocksRepository repository) { this.repository = repository; } @Override public void run(String... args) throws Exception { } }
true
4d46a1c8788278f5070e1c513564d9d0233b550c
Java
krish058/EFFECTIVE-PATTERN-DISCOVERY-FOR-TEXT-MINING
/Algorithm1.java
UTF-8
4,972
2.640625
3
[]
no_license
package effective; import javax.swing.JTable; import java.util.ArrayList; import javax.swing.table.DefaultTableModel; import java.util.Arrays; public class Algorithm1 { JTable table; double min_sup=50; ArrayList<DPBean> dp = new ArrayList<DPBean>(); ArrayList<DPBean> list = new ArrayList<DPBean>(); ArrayList<String> dup = new ArrayList<String>(); DefaultTableModel dtm; public void startProcess(JTable table,DefaultTableModel dtm){ this.table = table; this.dtm=dtm; dp.clear(); dup.clear(); for(int i=0;i<table.getRowCount();i++){ String data = table.getValueAt(i,1).toString().trim(); String terms[] = data.split(","); for(int j=0;j<terms.length;j++){ String term = terms[j]; if(!dup.contains(term)){ dup.add(term); String result = getResult(term); if(!result.equals("none")){ String out[]=result.split("#"); DPBean bean = new DPBean(); bean.setTerm(term); bean.setParagraph(out[0]); bean.setSupport(Double.parseDouble(out[1].trim())); dp.add(bean); } } } if(terms.length >= 2){ splitTerms(terms); } if(terms.length >= 3){ ThirdTerms(terms); } } dup.clear(); int as[]=new int[dp.size()]; for(int i=0;i<dp.size();i++){ DPBean bean = dp.get(i); as[i] = bean.getTerm().split(",").length; } Arrays.sort(as); for(int i=as.length-1;i>=0;i--){ for(int j=0;j<dp.size();j++){ DPBean bean = dp.get(j); String tr = bean.getTerm(); if(as[i] == tr.split(",").length && !dup.contains(tr)){ DPBean bn = new DPBean(); bn.setParagraph(bean.getParagraph()); bn.setTerm(bean.getTerm()); bn.setSupport(bean.getSupport()); list.add(bn); dup.add(tr); j = dp.size(); } } } for(int i=0;i<list.size();i++){ DPBean bean = list.get(i); Object row[]={bean.getTerm(),bean.getParagraph(),bean.getSupport()}; dtm.addRow(row); } } public void ThirdTerms(String[] terms){ ArrayList<String> list = new ArrayList<String>(); for(int i=0;i<terms.length;i++){ for(int j=i+1;j<terms.length;j++){ for(int k=j+1;k<terms.length;k++){ String term = terms[i]+","+terms[j]+","+terms[k]; if(!dup.contains(term)){ dup.add(term); String result = getThirdResult(term,2); if(!result.equals("none")){ String out[]=result.split("#"); DPBean bean = new DPBean(); bean.setTerm(term); bean.setParagraph(out[0]); bean.setSupport(Double.parseDouble(out[1].trim())); dp.add(bean); } } } } } } public String getThirdResult(String term,int end){ StringBuffer sb=new StringBuffer(); double count = 0; for(int i=0;i<table.getRowCount();i++){ String terms[] = table.getValueAt(i,1).toString().trim().split(","); for(int j=0;j<terms.length;j++){ for(int k=j+1;k<terms.length;k++){ for(int m=k+1;m<terms.length;m++){ String data = terms[j]+","+terms[k]+","+terms[m]; if(term.equals(data)){ count = count+1; sb.append(table.getValueAt(i,0).toString().trim()+","); } } } } } double sup = (count/table.getRowCount())*100; if(sup < min_sup){ sb.delete(0,sb.length()); sb.append("none"); }else{ sb.deleteCharAt(sb.length()-1); sb.append("#"+count); } return sb.toString(); } public void splitTerms(String[] terms){ ArrayList<String> list = new ArrayList<String>(); for(int i=0;i<terms.length;i++){ for(int j=i+1;j<terms.length;j++){ String term = terms[i]+","+terms[j]; if(!dup.contains(term)){ dup.add(term); String result = getCompleteResult(term,2); if(!result.equals("none")){ String out[]=result.split("#"); DPBean bean = new DPBean(); bean.setTerm(term); bean.setParagraph(out[0]); bean.setSupport(Double.parseDouble(out[1].trim())); dp.add(bean); } } } } } public String getCompleteResult(String term,int end){ StringBuffer sb=new StringBuffer(); double count = 0; for(int i=0;i<table.getRowCount();i++){ String terms[] = table.getValueAt(i,1).toString().trim().split(","); for(int j=0;j<terms.length;j++){ for(int k=j+1;k<terms.length;k++){ String data = terms[j]+","+terms[k]; if(term.equals(data)){ count = count+1; sb.append(table.getValueAt(i,0).toString().trim()+","); } } } } double sup = (count/table.getRowCount())*100; if(sup < min_sup){ sb.delete(0,sb.length()); sb.append("none"); }else{ sb.deleteCharAt(sb.length()-1); sb.append("#"+count); } return sb.toString(); } public String getResult(String term){ StringBuffer sb=new StringBuffer(); double count=0; for(int i=0;i<table.getRowCount();i++){ String terms[] = table.getValueAt(i,1).toString().trim().split(","); for(int j=0;j<terms.length;j++){ if(terms[j].equals(term)){ count = count+1; sb.append(table.getValueAt(i,0).toString().trim()+","); } } } double sup = (count/table.getRowCount())*100; if(sup < min_sup){ sb.delete(0,sb.length()); sb.append("none"); }else{ sb.deleteCharAt(sb.length()-1); sb.append("#"+count); } return sb.toString(); } }
true
e3fc4b91f4a395522f4635c1d090e0978ae2ad76
Java
Dzc96/dinner-02
/src/main/java/com/appointment/dinner/exception/LogicalVerificationException.java
UTF-8
587
2.390625
2
[]
no_license
package com.appointment.dinner.exception; import com.appointment.dinner.constants.CommonConstants; /** * Description : 进行逻辑验证不通过时产生的错误 */ public class LogicalVerificationException extends BaseException { private static final long serialVersionUID = 1L; private static final String ERROR_MSG = "逻辑验证错误"; public LogicalVerificationException() { super(LogicalVerificationException.ERROR_MSG, CommonConstants.EX_OTHER_CODE); } public LogicalVerificationException(String message) { super(message, CommonConstants.EX_OTHER_CODE); } }
true
46693b7386d708a40b8935dc955da5957532c67f
Java
suicaijiao/tool
/xingrunkeji/timber-portal/src/main/java/com/soonphe/portal/controller/UmsGainpacketHistoryController.java
UTF-8
3,912
2.015625
2
[]
no_license
package com.soonphe.portal.controller; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.soonphe.portal.commons.golbal.result.ResponseResult; import com.soonphe.portal.entity.*; import com.soonphe.portal.service.*; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; /** * <p> * 增益表 前端控制器 * </p> * * @author soonphe * @since 2020-05-30 */ @RestController @RequestMapping("/ums-gainpacket-history") @Api(tags = "【增益包记录】增益包记录") public class UmsGainpacketHistoryController { private static final Logger logger = LoggerFactory.getLogger(UmsGainpacketHistoryController.class); @Autowired private IUmsGainpacketHistoryService service; @Autowired private IUmsGainpacketService gainpacketService; @Autowired private IWmsWalletService walletService; @Autowired private ISmsStatsService iSmsStatsService; /** * 创建 * * @param tyAdvert * @return */ @ApiOperation("创建") @PostMapping("/createObj") public ResponseResult<UmsGainpacketHistory> createObj(@ApiParam(required = true, value = "实体") @RequestBody UmsGainpacketHistory tyAdvert) { //查询用户钱包余额 WmsWallet wallet = walletService.getById(tyAdvert.getUid()); //查询增益包 UmsGainpacket contract = gainpacketService.getById(tyAdvert.getGid()); if (contract.getState()==2) { return ResponseResult.failed("增益包不可用"); } if (wallet.getFtAmount().compareTo(contract.getSpec())<0){ return ResponseResult.failed("钱包余额不足"); } if (wallet.getGainpackLevel() != null && wallet.getGainpackLevel() > 0) { return ResponseResult.failed("增益包不可重复购买"); } tyAdvert.setCreateDate(new Date()); service.save(tyAdvert); wallet.setFtAmount(wallet.getFtAmount().subtract(contract.getSpec())); wallet.setGainpackLevel(contract.getLevel()); wallet.setGainpackGameNum(contract.getDailyGameNum()); wallet.setGameNum(wallet.getGameNum()+contract.getDailyGameNum()); walletService.updateById(wallet); //统计每日数据 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); String now = simpleDateFormat.format(new Date()); SmsStats smsStats = new SmsStats(); List<SmsStats> smsStatsList = iSmsStatsService.list(new QueryWrapper<SmsStats>().lambda() .eq(SmsStats::getCreateDate, now)); if (smsStatsList.size() > 0) { smsStats = smsStatsList.get(0); smsStats.setGainpacketCount(smsStats.getGainpacketCount().add(contract.getSpec())); } else { smsStats.setCreateDate(new Date()); smsStats.setGainpacketCount(contract.getSpec()); } iSmsStatsService.saveOrUpdate(smsStats); return ResponseResult.success(tyAdvert); } /** * 查询list * * @return */ @ApiOperation("查询list") @GetMapping("/getList") public ResponseResult<List<UmsGainpacketHistory>> getList(@ApiParam(required = true, value = "uid") @RequestParam(value = "uid") int uid) { List<UmsGainpacketHistory> list = service.list(new QueryWrapper<UmsGainpacketHistory>().lambda() .eq(UmsGainpacketHistory::getUid, uid)); return ResponseResult.success(list); } }
true
ab45d4bfb2c5ce6b1c0fe62bc96894d1a2e15dc6
Java
wogus519/jaehyun
/Mellow/src/mypage/beans/Member.java
UTF-8
1,710
2.328125
2
[]
no_license
package mypage.beans; public class Member { private String id; private String password; private String password_ck; private String name; private String postcode; private String address; private String phone; private String email; public Member() { // TODO Auto-generated constructor stub } public Member(String id, String password, String password_ck, String name, String postcode, String address, String phone, String email) { this.id = id; this.password = password; this.password_ck = password_ck; this.name = name; this.postcode = postcode; this.address = address; this.phone = phone; this.email = email; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getPassword_ck() { return password_ck; } public void setPassword_ck(String password_ck) { this.password_ck = password_ck; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPostcode() { return postcode; } public void setPostcode(String postcode) { this.postcode = postcode; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
true
00a38aca0b419a201d2678c0757b27eac92f0753
Java
araltiparmak/springboot-junit-mockito
/src/test/java/com/araltiparmak/springbootjunitmockito/mockitosample/Verify.java
UTF-8
1,354
2.453125
2
[]
no_license
package com.araltiparmak.springbootjunitmockito.mockitosample; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import static org.mockito.Mockito.*; import static org.mockito.internal.verification.VerificationModeFactory.atLeast; import static org.mockito.internal.verification.VerificationModeFactory.times; @ExtendWith(MockitoExtension.class) public class Verify { @Mock BookService bookService; @Test void testOnce() { bookService.findAll(); verify(bookService).findAll(); } @Test void testTimes() { bookService.findAll(); bookService.findAll(); bookService.findAll(); verify(bookService, times(3)).findAll(); } @Test void testAtLeastOnce() { bookService.findAll(); bookService.findAll(); verify(bookService, atLeastOnce()).findAll(); } @Test void testAtLeastTwo() { bookService.findAll(); bookService.findAll(); verify(bookService, atLeast(2)).findAll(); } @Test void testAtMostTwo() { bookService.findAll(); verify(bookService, atMost(2)).findAll(); } @Test void testNever() { verify(bookService, never()).findAll(); } }
true
1582f854f996b38b8421b2f3939b62c34a8bea1f
Java
4teamsoft/CoinsoftWeb
/src/com/coinsoft/models/Person.java
UTF-8
2,374
2.703125
3
[]
no_license
package com.coinsoft.models; import java.sql.ResultSet; import java.sql.SQLException; public class Person { private int id; private String code; private String dni; private String name; private String lastName; private int age; private String mail; private String status; public Person(int id, String code, String dni, String name, String lastName, int age, String mail, String status) { this.id = id; this.code = code; this.dni = dni; this.name = name; this.lastName = lastName; this.age = age; this.mail = mail; this.status = status; } public Person() { } public int getId() { return id; } public Person setId(int id) { this.id = id; return this; } public String getCode() { return code; } public Person setCode(String code) { this.code = code;return this; } public String getDni() { return dni; } public Person setDni(String dni) { this.dni = dni;return this; } public String getName() { return name; } public Person setName(String name) { this.name = name;return this; } public String getLastName() { return lastName; } public Person setLastName(String lastName) { this.lastName = lastName;return this; } public int getAge() { return age; } public Person setAge(int age) { this.age = age;return this; } public String getMail() { return mail; } public Person setMail(String mail) { this.mail = mail;return this; } public String getStatus() { return status; } public Person setStatus(String status) { this.status = status;return this; } public static Person from(ResultSet rs) { try { return new Person( rs.getInt("id"), rs.getString("code"), rs.getString("dni"), rs.getString("name"), rs.getString("last_name"), rs.getInt("age"), rs.getString("mail"), rs.getString("status") ); } catch (SQLException e) { e.printStackTrace(); } return null; } }
true
4dbdd80586a797fb8608dba24a0d87b0b4a6d708
Java
RAES9/PROGRA2
/Abb/src/com/company/Abb.java
UTF-8
5,207
3
3
[]
no_license
package com.company; public class Abb { private String textoInOrden; private class nodoArbol { private Abb hd; private Abb hi; private int dato; private void nodoArbol() { hd = null; hi = null; dato = 0; } } public nodoArbol raiz; public void abb() { nodoArbol raiz = new nodoArbol(); } private boolean esVacio() { return (raiz == null); } public void insertar(int a) { if (esVacio()) { nodoArbol nuevo = new nodoArbol(); nuevo.dato = a; nuevo.hd = new Abb(); nuevo.hi = new Abb(); raiz = nuevo; } else { if (a > raiz.dato) { (raiz.hd).insertar(a); } if (a < raiz.dato) { (raiz.hi).insertar(a); } } } public void preOrder() { if (!esVacio()) { System.out.print(raiz.dato + ", "); raiz.hi.preOrder(); raiz.hd.preOrder(); } } public void inOrder() { textoInOrden = ""; if (!esVacio()) { raiz.hi.inOrder(); System.out.print(raiz.dato + ", "); raiz.hd.inOrder(); } } public void posOrder() { if (!esVacio()) { raiz.hd.posOrder(); raiz.hi.posOrder(); System.out.print(raiz.dato + ", "); } } public Abb buscar(int a) { Abb arbolito = null; if (!esVacio()) { if (a == raiz.dato) { return this; } else { if (a < raiz.dato) { arbolito = raiz.hi.buscar(a); } else { arbolito = raiz.hd.buscar(a); } } } return arbolito; } private int buscarMin() { Abb arbolActual = this; while (!arbolActual.raiz.hi.esVacio()) { arbolActual = arbolActual.raiz.hi; } int devuelvo = arbolActual.raiz.dato; arbolActual.raiz = null; return devuelvo; } private boolean esHoja() { boolean hoja = false; if ((raiz.hi).esVacio() && (raiz.hd).esVacio()) { hoja = true; } return hoja; } public String graphizinOrden() { String texto = "digraph G \n" + "{\n" + " node [shape=circle];\n" + " node [style=filled];\n" + " node [fillcolor=\"#EEEEEE\"];\n" + " node [color=\"#EEEEEE\"];\n" + " edge [color=\"#31CEF0\"];\n"; nodoArbol iz = null; nodoArbol dr = null; while (raiz != null) { if (iz == null) { iz = raiz.hd.raiz; dr = raiz.hd.raiz; } if (raiz.hd.raiz != null) { texto += raiz.dato + " -> " + raiz.hd.raiz.dato + ";\n"; } if (raiz.hi.raiz != null) { texto += raiz.dato + " -> " + raiz.hi.raiz.dato + ";\n"; } raiz = raiz.hi.raiz; } while (iz!=null){ try { if (iz != null) { if (iz.hd.raiz != null) { texto += iz.dato + " -> " + iz.hd.raiz.dato + ";\n"; } if (iz.hi.raiz != null) { texto += iz.dato + " -> " + iz.hi.raiz.dato + ";\n"; } iz = iz.hd.raiz; } } catch (NullPointerException e) { e.printStackTrace(); iz=null; } } while (dr != null) { try { if (dr != null) { if (dr.hd.raiz != null && !texto.contains(dr.dato + " -> " + dr.hd.raiz.dato + ";\n")) { texto += dr.dato + " -> " + dr.hd.raiz.dato + ";\n"; } if (dr.hi.raiz != null && !texto.contains(dr.dato + " -> " + dr.hi.raiz.dato + ";\n")) { texto += dr.dato + " -> " + dr.hi.raiz.dato + ";\n"; } dr = dr.hi.raiz; } } catch (NullPointerException e) { e.printStackTrace(); dr=null; } } texto += "rankdir=TP;\n" + "}"; return texto; } public void eliminar(int a) { Abb paraEliminar = buscar(a); if (!paraEliminar.esVacio()) { if (paraEliminar.esHoja()) { paraEliminar.raiz = null; } else { if (!paraEliminar.raiz.hi.esVacio() && !paraEliminar.raiz.hd.esVacio()) { paraEliminar.raiz.dato = paraEliminar.raiz.hd.buscarMin(); } else { if (paraEliminar.raiz.hi.esVacio()) { paraEliminar.raiz = paraEliminar.raiz.hd.raiz; } else { paraEliminar.raiz = paraEliminar.raiz.hi.raiz; } } } } } }
true
fbd302084fc55c06a52e6ea349506f9794c5b9f5
Java
PTHy/MVC_model_tutorial
/src/sms/view/ConsoleView.java
UHC
4,701
3.109375
3
[]
no_license
package sms.view; import java.util.ArrayList; import java.util.Scanner; import sms.dto.Grade; import sms.dto.Student; public class ConsoleView { public String getStudentNo(Scanner sc, String msg) { System.out.println("\n> "+msg+" : "); return sc.next(); } public void printRegistedStudent(int stu_no) { System.out.println("> ̹ ϵ лԴϴ."); } public void showAllStudents(ArrayList<Student> students) { int cnt = 1; System.out.println("\n> "+students.size()+" л ȸմϴ."); System.out.println(" й ̸ г ּ ȭȣ "); for(Student student : students) { System.out.println(cnt+"."+student.getStu_no()+" "+student.getStu_name()+" "+student.getStu_year()+" "+student.getStu_addr()+" "+student.getStu_tel()+" "+student.getStu_birth()+" "); cnt++; } } public Student addNewStudent(int stu_no, Scanner sc) { sc.useDelimiter(System.getProperty("line.separator")); System.out.println("\n> ο л Է\n"); System.out.print("> ̸:"); String stu_name = sc.next(); System.out.println("> г:"); int stu_year = sc.nextInt(); System.out.println("> ּ:"); String stu_addr = sc.next(); System.out.println("> ȭȣ:"); String stu_tel = sc.next(); System.out.println("> "); String stu_birth = sc.next(); return new Student(stu_no, stu_name, stu_year, stu_addr, stu_tel,stu_birth); } public void printAddSuccess(Student newStudent) { System.out.println("> й : "+newStudent.getStu_no()+" л ϵǾϴ."); } public void printAddFail(Student newStudent) { // TODO Auto-generated method stub System.out.println("> й : "+newStudent.getStu_no()+" л ߽ϴ."); } public void printUnfitForm(String unfitForm) { System.out.println("> : "+unfitForm+" Ŀ ʽϴ." + "(: 2001-01-01)"); } public void studentNotFound() { System.out.println("> ã л ʽϴ."); } public void printDeleteSuccess(int stu_no) { System.out.println("> й : "+stu_no+" л Ǿϴ."); } public void printDeleteFail(int stu_no) { System.out.println("> й : "+stu_no+" л Ͽϴ."); } public void printModifySuccess(Student student) { System.out.println("> й : "+student.getStu_no()+" л Ǿϴ."); } public void printModifyFail(Student student) { System.out.println("> й : "+student.getStu_no()+" л Ͽϴ."); } public void printAddSuccessGrade(Grade newGrade) { System.out.println("> й : "+newGrade.getStu_no()+" л ϵǾϴ"); } public void printAddFailGrade(Grade newGrade) { System.out.println("> й : "+newGrade.getStu_no()+" л Ͽ Ͽϴ"); } public Grade addNewGrade(int stu_no, Scanner sc) { sc.useDelimiter(System.getProperty("line.separator")); System.out.println("\n> ο Է\n"); System.out.print("> :"); int grade_kor = sc.nextInt(); System.out.println("> :"); int grade_math = sc.nextInt(); System.out.println("> :"); int grade_eng = sc.nextInt(); return new Grade(stu_no, grade_kor, grade_eng, grade_math); } public void printRegistedGrade(int stu_no) { System.out.println("> ̹ ϵ лԴϴ."); } public void showAllGrades(ArrayList<Grade> grades) { int cnt = 1; System.out.println("\n> "+grades.size()+" л ȸմϴ."); System.out.println(" й "); for(Grade grade : grades) { System.out.println(cnt+"."+grade.getStu_no()+" "+grade.getGrade_kor()+" "+grade.getGrade_eng()+" "+grade.getGrade_math()); cnt++; } } public void printModifySuccessGrade(Grade grade) { System.out.println("> й : "+grade.getStu_no()+" л Ǿϴ."); } public void printModifyFailGrade(Grade grade) { System.out.println("> й : "+grade.getStu_no()+" л Ͽϴ."); } public void printDeleteSuccessGrade (int stu_no) { System.out.println("> й : "+stu_no+" л Ǿϴ."); } public void printDeleteFailGrade(int stu_no) { System.out.println("> й : "+stu_no+" л Ͽϴ."); } }
true
3783b85befb6a68b4b28c0dd6eb678f54a789ac0
Java
Nishikanto/SlideController_1.0
/Networking_Project/SlideController/app/src/main/java/com/example/root/slidecontroller/DBhelper.java
UTF-8
4,007
2.40625
2
[]
no_license
package com.example.root.slidecontroller; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import java.util.ArrayList; /** * Created by root on 10/1/16. */ public class DBhelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "slideController.db"; private static final String TABLE_NAME = "ipadresses"; private static final String COLUMN_ID = "id"; private static final String COLUMN_NAME = "name"; private static final String COLUMN_IP = "ip"; private static final String COLUMN_ACTIVE = "active"; private SQLiteDatabase db; public DBhelper(Context context) { super(context, DATABASE_NAME, null, 1); db = this.getWritableDatabase(); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL( "create table ipadresses " + "(id integer primary key, name text, ip text, active int)" ); db.execSQL("insert into ipadresses(name, ip, active) values('Room 329','100.10.68.15',0)"); db.execSQL("insert into ipadresses(name, ip, active) values('Room 330','100.10.68.16',0)"); db.execSQL("insert into ipadresses(name, ip, active) values('Room 331','100.10.68.17',0)"); db.execSQL("insert into ipadresses(name, ip, active) values('Room 332','100.10.68.18',0)"); db.execSQL("insert into ipadresses(name, ip, active) values('Room 333','100.10.68.19',0)"); db.execSQL("insert into ipadresses(name, ip, active) values('Room 334','192.168.2.100',0)"); db.execSQL("insert into ipadresses(name, ip, active) values('SUST WIFI - NUSRAT','10.100.5.1',0)"); db.execSQL("insert into ipadresses(name, ip, active) values('EMULATOR','10.0.3.2',1)"); db.execSQL("insert into ipadresses(name, ip, active) values('New Phone','192.168.0.110',1)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS ipadresses"); onCreate(db); } public boolean insertData(String name, String ip, int active){ ContentValues contentValues = new ContentValues(); contentValues.put("name", name); contentValues.put("ip", ip); contentValues.put("active", active); db.insert("ipadresses", null, contentValues); return true; } public boolean activateIp(int id){ ContentValues contentValues = new ContentValues(); contentValues.put("active", 1); db.update("ipadresses", contentValues, "id = ? ", new String[] {Integer.toString(id)} ); return true; } public ArrayList<IpClass> getAllIps(){ ArrayList<IpClass> array_list = new ArrayList<IpClass>(); Cursor res = db.rawQuery( "select * from ipadresses", null ); res.moveToFirst(); while(res.isAfterLast() == false){ IpClass ipClass = new IpClass(); ipClass.setId(Integer.parseInt(res.getString(res.getColumnIndex(COLUMN_ID)))); ipClass.setName(res.getString(res.getColumnIndex(COLUMN_NAME))); ipClass.setActive(Integer.parseInt(res.getString(res.getColumnIndex(COLUMN_ACTIVE)))); ipClass.setIp(res.getString(res.getColumnIndex(COLUMN_IP))); array_list.add(ipClass); res.moveToNext(); } return array_list; } public boolean deactivateAllIp(){ db.execSQL("UPDATE ipadresses SET active=0"); return true; } public String getActiveIp(){ String activeIp = "0"; Cursor res = db.rawQuery( "select ip from ipadresses where active=1", null ); res.moveToFirst(); while(res.isAfterLast() == false){ activeIp = res.getString(res.getColumnIndex(COLUMN_IP)); res.moveToNext(); } return activeIp; } }
true
2131d3f92ffad76ed940c2eec57258e9228b85ec
Java
SirMontoia/Exercicios-e-Projetos-Generation
/Exercício Preliminar Spring/src/main/java/com/helloworld/hello/HelloApplication.java
UTF-8
1,064
2.546875
3
[]
no_license
package com.helloworld.hello; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @RequestMapping("/") @RestController public class HelloApplication { @GetMapping ("/exercicio1") public String helloworld(){ return "Para esta atividade, tive de focar na mentalidade de " + "crescimento e tive de demonstrar persistência em aprender o passo a passo"; } @GetMapping ("/exercicio2") public String helloworld2() { return " Nesta semana, espero conseguir compreender o básico em desenvolvimento web, desde a criação correta do arquivo" + "gerado no Spring initialize até a compreensão da inserção de cada método e import dentro do POM e do executável."; } public static void main(String[] args) { SpringApplication.run(HelloApplication.class, args); } }
true
2de2ec2862fba53b2e2adcf098acbec389771c64
Java
GerritCodeReview/gerrit
/javatests/com/google/gerrit/entities/LabelTypeTest.java
UTF-8
1,750
2.234375
2
[ "Apache-2.0" ]
permissive
// Copyright (C) 2018 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.entities; import static com.google.common.truth.Truth.assertThat; import com.google.common.collect.ImmutableList; import org.junit.Test; public class LabelTypeTest { @Test public void sortLabelValues() { LabelValue v0 = LabelValue.create((short) 0, "Zero"); LabelValue v1 = LabelValue.create((short) 1, "One"); LabelValue v2 = LabelValue.create((short) 2, "Two"); LabelType types = LabelType.create("Label", ImmutableList.of(v2, v0, v1)); assertThat(types.getValues()).containsExactly(v0, v1, v2).inOrder(); } @Test public void insertMissingLabelValues() { LabelValue v0 = LabelValue.create((short) 0, "Zero"); LabelValue v2 = LabelValue.create((short) 2, "Two"); LabelValue v5 = LabelValue.create((short) 5, "Five"); LabelType types = LabelType.create("Label", ImmutableList.of(v2, v5, v0)); assertThat(types.getValues()) .containsExactly( v0, LabelValue.create((short) 1, ""), v2, LabelValue.create((short) 3, ""), LabelValue.create((short) 4, ""), v5) .inOrder(); } }
true
6b8578dbbfe53034ee113ccdd8c4302adb821259
Java
xudonlee/mycode
/springMVC/src/com/itzl/controller/ScopeController.java
UTF-8
1,023
2.28125
2
[]
no_license
package com.itzl.controller; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller @RequestMapping("/scope") public class ScopeController { @RequestMapping(value="/news",method = RequestMethod.DELETE) public String deleteAllNews(HttpServletRequest req) { String[] ids = req.getParameterValues("ids"); for (String id : ids) { System.out.println(id); } return "redirect:/main.jsp"; } @RequestMapping(value = "/news",method = RequestMethod.PUT) public String addNews() { System.out.println("添加新闻成功。。。"); return "redirect:/main.jsp"; } @RequestMapping(value = "/news/{id}",method = RequestMethod.PUT) public String updateNews(@PathVariable int id) { System.out.println("修改的新闻为"+id); return "redirect:/main.jsp"; } }
true
b711b666f5be2736fb1d60cff67c751e94b0d3ed
Java
giovanibarbosa/afazenda
/A Fazenda/src/projeto/gui/NovaTiragem.java
UTF-8
9,709
2.125
2
[]
no_license
/* * To change this template, choose Tools | Templates. * and open the template in the editor. */ /* * NovaTiragem.java * * Created on 28/11/2009, 00:10:59 */ package projeto.gui; import java.util.List; import projeto.afazenda.Rebanho; import projeto.afazenda.Vaca; import projeto.bd.RebanhoDAO; import projeto.bd.VacasDAO; /** * * @author Rodolfo */ public class NovaTiragem extends javax.swing.JFrame { Tiragens menuTiragens; VacasDAO vacasDAO = new VacasDAO(); RebanhoDAO rebanhoDAO = new RebanhoDAO(); /** Creates new form NovaTiragem */ public NovaTiragem(Tiragens menuTiragens, boolean visivel) { this.menuTiragens = menuTiragens; setTitle("A Fazenda - Nova Tiragem"); setVisible(visivel); setBounds(new java.awt.Rectangle(350, 180, 800, 800)); initComponents(); atualizarListaRebanhos(); } /** 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() { agrupadorDeRadioButtons = new javax.swing.ButtonGroup(); titulo = new javax.swing.JLabel(); separador = new javax.swing.JSeparator(); jLabel1 = new javax.swing.JLabel(); tiragemMatinal = new javax.swing.JRadioButton(); tiragemVespertina = new javax.swing.JRadioButton(); jLabel2 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); listaRebanhos = new javax.swing.JComboBox(); jLabel4 = new javax.swing.JLabel(); listaVacas = new javax.swing.JComboBox(); botaoProximo = new javax.swing.JButton(); botaoCancelar = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); titulo.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N titulo.setText("Nova Tiragem"); jLabel1.setText("Tipo:"); agrupadorDeRadioButtons.add(tiragemMatinal); tiragemMatinal.setText("Manha"); agrupadorDeRadioButtons.add(tiragemVespertina); tiragemVespertina.setText("Tarde"); jLabel2.setText("Data (dd/mm/aaaa):"); jLabel3.setText("Rebanho:"); listaRebanhos.setModel(new javax.swing.DefaultComboBoxModel()); listaRebanhos.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { listaRebanhosActionPerformed(evt); } }); jLabel4.setText("Vaca:"); listaVacas.setModel(new javax.swing.DefaultComboBoxModel()); botaoProximo.setText("Proximo"); botaoCancelar.setText("Cancelar"); botaoCancelar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botaoCancelarActionPerformed(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(98, 98, 98) .addComponent(titulo)) .addComponent(separador, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addComponent(jLabel2) .addGap(18, 18, 18) .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 144, Short.MAX_VALUE) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addComponent(jLabel1) .addGap(18, 18, 18) .addComponent(tiragemMatinal) .addGap(18, 18, 18) .addComponent(tiragemVespertina)))) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(botaoProximo) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(botaoCancelar)) .addComponent(listaVacas, 0, 209, Short.MAX_VALUE) .addComponent(listaRebanhos, 0, 209, Short.MAX_VALUE)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(titulo) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(separador, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(tiragemMatinal) .addComponent(tiragemVespertina)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(listaRebanhos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(listaVacas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(botaoProximo) .addComponent(botaoCancelar)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void botaoCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoCancelarActionPerformed setVisible(false); menuTiragens.setVisible(true); }//GEN-LAST:event_botaoCancelarActionPerformed public void atualizarListaRebanhos() { listaRebanhos.removeAllItems(); for(Rebanho reb: rebanhoDAO.getTodosRebanhos()) { listaRebanhos.addItem("" + reb.getID() + " - " + reb.getNome()); } } private void listaRebanhosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_listaRebanhosActionPerformed int indice = listaRebanhos.getSelectedIndex(); //mini-gambiarra para evitar que indice seja -1 ;D if (indice == -1) { indice = 0; } List<Rebanho> listaRebanhosTemp = rebanhoDAO.getTodosRebanhos(); int rebanhoID = listaRebanhosTemp.get(indice).getID(); atualizarListaVacas(rebanhoID); } public void atualizarListaVacas(int rebanhoID) { listaVacas.removeAllItems(); for(Vaca vaca : vacasDAO.getTodasVacas(rebanhoID)) { listaVacas.addItem("" + vaca.getID() + " - " + vaca.getNome()); } } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.ButtonGroup agrupadorDeRadioButtons; private javax.swing.JButton botaoProximo; private javax.swing.JButton botaoCancelar; javax.swing.JComboBox listaRebanhos; javax.swing.JComboBox listaVacas; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JRadioButton tiragemMatinal; private javax.swing.JRadioButton tiragemVespertina; private javax.swing.JTextField jTextField1; private javax.swing.JSeparator separador; private javax.swing.JLabel titulo; // End of variables declaration//GEN-END:variables }
true
d84795e3e82c946ef667242c298ecc226675475b
Java
scottejames/AutoAccounts
/src/scott/nursery/accounts/transaction/TransactionBrowserTableDefinition.java
UTF-8
4,569
2.078125
2
[]
no_license
package scott.nursery.accounts.transaction; import java.math.BigDecimal; import java.text.ParseException; import org.apache.log4j.Logger; import org.eclipse.swt.graphics.Color; import scott.mvc.gui.Utils; import scott.mvc.gui.table.FTableDefinition; import scott.mvc.gui.table.FTableRow; import scott.mvc.gui.table.FTableFilter.SORT_TYPE; import scott.nursery.accounts.NurseryGui; import scott.nursery.accounts.domain.ApplicationModel; import scott.nursery.accounts.domain.CatagoryList; import scott.nursery.accounts.domain.bo.BaseCatagory; import scott.nursery.accounts.domain.bo.BaseTransaction; public class TransactionBrowserTableDefinition extends FTableDefinition { @SuppressWarnings("unused") private static Logger _logger = Logger .getLogger(TransactionBrowserTableDefinition.class); @Override protected Object[][] getTableDefinition() { Object[][] COLUMN_DETAILS = { { "ID", 30, SORT_TYPE.NUMBER, false }, { "Date", 100, SORT_TYPE.DATE, false }, { "Payee", 300, SORT_TYPE.STRING, false }, { "Catagory", 100, SORT_TYPE.STRING, false }, { "EPayee", 300, SORT_TYPE.STRING, true }, { "ChequeNumber", 150, SORT_TYPE.STRING, false }, { "Amount", 150, SORT_TYPE.NUMBER, false }, { "NoChequeMached", 30, SORT_TYPE.STRING, false }, { "Enriched Payee", 30, SORT_TYPE.STRING, false } }; return COLUMN_DETAILS; } public static FTableRow buildRowFromTransaction(BaseTransaction t) { CatagoryList catList = ApplicationModel.getInstance().getCatagoryList(); Long id = t.get_catagoryID(); String catagoryName; if (id != null) { catagoryName = catList.getCatagoryById(id).get_name(); } else { catagoryName = ""; } String [] rowData = new String[] { Utils.toString(t.get_id()), Utils.dateToString(t.get_date()), Utils.toString(t.get_payee()), catagoryName, Utils.toString(t.get_enrichedPayee()), Utils.toString(t.get_chequeNumber()), Utils.toString(t.get_amount()), Utils.boolToString((Boolean) t.is_chequeNotMatched()), Utils.boolToString(t.show_enrichedPayee()) }; Color [] foreColor = new Color[rowData.length]; if (t.show_enrichedPayee()) { foreColor[2]= NurseryGui.RED; } if ((t.get_catagoryID() != null) && (t.is_manualEditCatagory()==false)) { foreColor[3]= NurseryGui.RED; } return new FTableRow(rowData, foreColor,t.get_id()); } public static BaseTransaction buildTransactionFromRow(FTableRow row) { CatagoryList catList = ApplicationModel.getInstance().getCatagoryList(); BaseTransaction transaction = new BaseTransaction(); try { int columnNo = 0; transaction = ApplicationModel.getInstance().getTransactionList().getById((Long)row.getHiddenRowData()); // Extract fields from row @SuppressWarnings("unused") String strId = row.getRowData()[columnNo++]; String strDate = row.getRowData()[columnNo++]; String strPayee = row.getRowData()[columnNo++]; String strCatagoryName = row.getRowData()[columnNo++]; @SuppressWarnings("unused") String strEPayee = row.getRowData()[columnNo++]; String strChequeNo = row.getRowData()[columnNo++]; String strAmount = row.getRowData()[columnNo++]; // calculate derived values Long catagoryId = null; if (strCatagoryName != null) { BaseCatagory catagory = catList .getCatagoryFromName(strCatagoryName); if (catagory != null) catagoryId = catagory.get_id(); } BigDecimal amount = new BigDecimal(strAmount); // Store values into a transaction transaction.set_date(Utils.stringToDate(strDate)); transaction.set_payee(strPayee); transaction.set_catagoryID(catagoryId); transaction.set_chequeNumber(strChequeNo); transaction.set_amount(amount); } catch (ParseException e) { e.printStackTrace(); } return transaction; } }
true
2cde24271e1702209d2c7b558051b075ad58cae8
Java
AY1920S1-CS2103T-F13-4/main
/src/main/java/seedu/ezwatchlist/logic/parser/SearchCommandParser.java
UTF-8
10,056
2.546875
3
[ "MIT" ]
permissive
package seedu.ezwatchlist.logic.parser; import static seedu.ezwatchlist.logic.parser.CliSyntax.PREFIX_ACTOR; import static seedu.ezwatchlist.logic.parser.CliSyntax.PREFIX_FROM_ONLINE; import static seedu.ezwatchlist.logic.parser.CliSyntax.PREFIX_GENRE; import static seedu.ezwatchlist.logic.parser.CliSyntax.PREFIX_IS_WATCHED; import static seedu.ezwatchlist.logic.parser.CliSyntax.PREFIX_NAME; import static seedu.ezwatchlist.logic.parser.CliSyntax.PREFIX_TYPE; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Optional; import java.util.stream.Stream; import seedu.ezwatchlist.commons.core.messages.Messages; import seedu.ezwatchlist.commons.core.messages.SearchMessages; import seedu.ezwatchlist.logic.commands.SearchCommand; import seedu.ezwatchlist.logic.parser.exceptions.ParseException; import seedu.ezwatchlist.model.show.Type; /** * Parses input arguments and creates a new SearchCommand object. */ public class SearchCommandParser implements Parser<SearchCommand> { private static final String INPUT_TRUE = "true"; private static final String INPUT_YES = "yes"; private static final String INPUT_FALSE = "false"; private static final String INPUT_NO = "no"; private HashMap<SearchKey, List<String>> searchShowsHashMap = new HashMap<>(); /** * Parses the given {@code String} of arguments in the context of the SearchCommand. * and returns a SearchCommand object for execution. * @throws ParseException if the user input does not conform the expected format. */ public SearchCommand parse(String args, String currentPanel) throws ParseException { checkNoOtherPrefixPresent(args); ArgumentMultimap argMultimap = ArgumentTokenizer.tokenize( args, PREFIX_NAME, PREFIX_TYPE, PREFIX_ACTOR, PREFIX_GENRE, PREFIX_IS_WATCHED, PREFIX_FROM_ONLINE); checkPrefixPresent(argMultimap); List<String> nameList = argMultimap.getAllValues(PREFIX_NAME); Optional<String> typeOptional = argMultimap.getValue(PREFIX_TYPE); List<String> actorList = argMultimap.getAllValues(PREFIX_ACTOR); List<String> genreList = argMultimap.getAllValues(PREFIX_GENRE); Optional<String> isWatchedOptional = argMultimap.getValue(PREFIX_IS_WATCHED); Optional<String> fromOnlineOptional = argMultimap.getValue(PREFIX_FROM_ONLINE); if (emptyCompulsoryKeyword(nameList, actorList, genreList)) { throw new ParseException("Make sure keyword(s) for n/, a/ or g/ is not empty.\n" + SearchMessages.MESSAGE_USAGE); } parseNameToBeSearched(nameList); parseTypeToBeSearched(typeOptional); parseActorToBeSearched(actorList); parseGenreToBeSearched(genreList); parseIsWatchedToBeSearched(isWatchedOptional); parseFromOnlineToBeSearched(fromOnlineOptional); return new SearchCommand(searchShowsHashMap); } /** * Returns true if any of the prefixes for name, genre or actor is present * in the given {@code ArgumentMultimap}. * @throws ParseException if the user input does not conform the expected format. */ private void checkPrefixPresent(ArgumentMultimap argMultimap) throws ParseException { if (!anyPrefixesPresent(argMultimap, PREFIX_NAME, PREFIX_GENRE, PREFIX_ACTOR) || !argMultimap.getPreamble().isEmpty()) { throw new ParseException(String.format(Messages.MESSAGE_INVALID_COMMAND_FORMAT, SearchMessages.MESSAGE_USAGE)); } } /** * Returns whether there is any compulsory keyword present. * One of the following keyword needs to be present: show name, actor or genre. * @return True if all compulsory keyword is empty. */ private boolean emptyCompulsoryKeyword(List<String> nameList, List<String> actorList, List<String> genreList) { if (nameList.isEmpty() && actorList.isEmpty() && genreList.isEmpty()) { return true; } for (String name : nameList) { if (name.isBlank()) { return true; } } for (String actor : actorList) { if (actor.isBlank()) { return true; } } for (String genre : genreList) { if (genre.isBlank()) { return true; } } return false; } /** * Returns true if any of the prefixes does not contain empty {@code Optional} values in the given * {@code ArgumentMultimap}. */ private static boolean anyPrefixesPresent(ArgumentMultimap argumentMultimap, Prefix... prefixes) { return Stream.of(prefixes).anyMatch(prefix -> argumentMultimap.getValue(prefix).isPresent()); } /** * Checks if the user input the command correctly with the correct syntax. * @param args User input to be checked for the correct syntax. * @throws ParseException if the user input does not conform the expected format. */ private void checkNoOtherPrefixPresent(String args) throws ParseException { String[] keywordsArray = args.split("/"); int arrayLength = keywordsArray.length; for (int i = 0; i < arrayLength - 1; i++) { String s = keywordsArray[i]; String[] sArray = s.split(" "); int sLength = sArray.length; String prefix = sArray[sLength - 1]; if (!prefix.equals("n") && !prefix.equals("a") && !prefix.equals("g") && !prefix.equals("t") && !prefix.equals("o") && !prefix.equals("w")) { throw new ParseException("Invalid syntax.\n" + SearchMessages.MESSAGE_USAGE); } } } /** * Parses the names to be searched. * @param nameList List of names to be searched. */ private void parseNameToBeSearched(List<String> nameList) { searchShowsHashMap.put(SearchKey.KEY_NAME, nameList); } /** * Parses the type to be searched. * @param typeOptional Type to be searched. */ private void parseTypeToBeSearched(Optional<String> typeOptional) throws ParseException { ArrayList<String> listOfType = new ArrayList<String>(); if (typeOptional.isPresent()) { String type = typeOptional.get().toLowerCase(); if (type.isBlank()) { throw new ParseException("Make sure keyword for t/ is not empty." + SearchMessages.MESSAGE_INVALID_TYPE_COMMAND); } String typeTrimmed = type.trim(); if (!(typeTrimmed.equals(Type.MOVIE.getType()) || typeTrimmed.equals(Type.TV_SHOW.getType()))) { throw new ParseException(SearchMessages.MESSAGE_INVALID_TYPE_COMMAND); } listOfType.add(typeTrimmed); } searchShowsHashMap.put(SearchKey.KEY_TYPE, listOfType); } /** * Parses the actors to be searched. * @param actorList List of actors to be searched. */ private void parseActorToBeSearched(List<String> actorList) { searchShowsHashMap.put(SearchKey.KEY_ACTOR, actorList); } /** * Parses the genres to be searched. * @param genreList List of genres to be searched. */ private void parseGenreToBeSearched(List<String> genreList) { searchShowsHashMap.put(SearchKey.KEY_GENRE, genreList); } /** * Parses whether the show is watched. * @param isWatchedOptional True/Yes if is watched, else, False/No */ private void parseIsWatchedToBeSearched(Optional<String> isWatchedOptional) throws ParseException { ArrayList<String> listOfIsWatched = new ArrayList<String>(); if (isWatchedOptional.isPresent()) { String isWatched = isWatchedOptional.get().toLowerCase(); if (isWatched.isBlank()) { throw new ParseException("Make sure keyword for w/ is not empty." + SearchMessages.MESSAGE_INVALID_IS_WATCHED_COMMAND); } String isWatchedTrimmed = isWatched.trim(); if (!(isWatchedTrimmed.equals(INPUT_FALSE) || isWatchedTrimmed.equals(INPUT_NO) || isWatchedTrimmed.equals(INPUT_TRUE) || isWatchedTrimmed.equals(INPUT_YES))) { throw new ParseException(SearchMessages.MESSAGE_INVALID_IS_WATCHED_COMMAND); } listOfIsWatched.add(isWatchedTrimmed); } searchShowsHashMap.put(SearchKey.KEY_IS_WATCHED, listOfIsWatched); } /** * Parses whether the show searched should be from online. * @param fromOnlineOptional True/Yes if is from online, else, False/No. */ private void parseFromOnlineToBeSearched(Optional<String> fromOnlineOptional) throws ParseException { ArrayList<String> listOfFromOnline = new ArrayList<String>(); if (fromOnlineOptional.isPresent()) { String fromOnline = fromOnlineOptional.get().toLowerCase(); if (fromOnline.isBlank()) { throw new ParseException("Make sure keyword for o/ is not empty." + SearchMessages.MESSAGE_INVALID_FROM_ONLINE_COMMAND); } String fromOnlineTrimmed = fromOnline.trim(); if (!(fromOnlineTrimmed.equals(INPUT_FALSE) || fromOnlineTrimmed.equals(INPUT_NO) || fromOnlineTrimmed.equals(INPUT_TRUE) || fromOnlineTrimmed.equals(INPUT_YES))) { throw new ParseException(SearchMessages.MESSAGE_INVALID_FROM_ONLINE_COMMAND); } listOfFromOnline.add(fromOnlineTrimmed); } searchShowsHashMap.put(SearchKey.KEY_FROM_ONLINE, listOfFromOnline); } /** * Return the hash map of the shows to be watched based on the different category. * @return Hash map of the shows to be watched based on the different category. */ public HashMap<SearchKey, List<String>> getSearchShowsHashMap() { return searchShowsHashMap; } }
true
26081746b03c5b8dc0a230537bffcf66b55f6571
Java
Allen-Duan/lvyouwang
/src/main/java/cn/exrick/xboot/modules/your/dao/ProvincesDao.java
UTF-8
376
1.65625
2
[]
no_license
package cn.exrick.xboot.modules.your.dao; import cn.exrick.xboot.base.XbootBaseDao; import cn.exrick.xboot.modules.your.entity.Provinces; import java.util.List; import java.util.Optional; /** * 地区数据处理层 * @author dsh */ public interface ProvincesDao extends XbootBaseDao<Provinces, String> { Optional<Provinces> findByProvinceid(String provincesId); }
true
18d71785a5d6fbc1c2004a0ee3fcafb6a4cf0f07
Java
AparicioFranco/IngSist
/cli/src/main/java/edu/austral/ingsis/CLI.java
UTF-8
113
1.679688
2
[]
no_license
package edu.austral.ingsis; public class CLI { public boolean someCLIMethod(){ return true; } }
true
8ede240426e0e30a27e5bd87a1e537d75c64a2ff
Java
AleksandrStefanovich/AleksandrStefanovich_Academy
/src/by/academy/HomeWork1/Main.java
UTF-8
1,259
3.921875
4
[]
no_license
package by.academy.HomeWork1; import by.academy.HomeWork1.CalculatorWithOperator; public class Main { public static void main(String[] args) { CalculatorWithOperator calc = new CalculatorWithOperator(); double result; // 4.1 + 15 * 7 + (28 / 5) ^ 2 вывод в result // первым выполняется деление, потом возведение в квадрат, сложение с результатом произведения и последним сложение с 4.1 // дробную степень например 2/5 можно реализовать как calc.sqrt(calc.squre(n,2),5) //calc.sqrt считает корень любой степени с точностью до 3 знаков после запятой result = calc.add((calc.add(calc.square(calc.divide(28, 5),2),calc.multiply(15, 7))),4.1); System.out.println(result); System.out.println(calc.sqrt(4096,2)); //корень любой степени любого числа result = calc.divide(result, 0); //returns infinity System.out.println(result); result = calc.divide(20, 0.0d); //returns infinity System.out.println(result); } }
true
49a36d89d85a2259c6cca60a533eca75293d87cd
Java
athidi21athy/kalah-api
/src/main/com/athidi21athy/kalahapi/GameEngine.java
UTF-8
4,168
3.0625
3
[ "MIT" ]
permissive
package com.athidi21athy.kalahapi; import com.athidi21athy.kalahapi.domain.Pit; import com.athidi21athy.kalahapi.exceptions.InvalidMoveException; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.IntStream; @Component public class GameEngine { /* * This is the main function for moving the stones in each pit * Rules. * 1. each player only gets a turn if they placed their last stone in their kalah * */ public List<Pit> tryMove(List<Pit> currentPitList, Integer pitId) throws InvalidMoveException { //Checks if the pits are available for the move if (!currentPitList.get(pitId - 1).getIsAvailable()) { throw new InvalidMoveException(); } List<Pit> newPits = new ArrayList<>(currentPitList.size()); for (Pit item : currentPitList) newPits.add(new Pit(item.getId(), item.getGameId(), item.getStoneCount())); //Since index starts with Zero Pit initialPit = newPits.get(pitId - 1); List<Integer> pitIds = getPitIds(pitId, initialPit); for (Integer id : pitIds) { Pit currentPit = newPits.get(id - 1); currentPit.setStoneCount(currentPit.getStoneCount() + 1); } // Sets the pit stone count to 0 initialPit.setStoneCount(0); //Calculate which pits are available for the next move calculateAvailablePits(newPits, pitIds.get(pitIds.size() - 1), pitId); return newPits; } /* * This function calculate which pits are available for the next move based on some rules * 1. kalah's are never available for move * 2. Players can only get turns if they placed their last stone in the opponents pit */ private void calculateAvailablePits(List<Pit> pits, Integer finalPitId, Integer currentPitId) { for (int idx = 0; idx <= 13; idx++) { if (finalPitId == 7 && idx < 6 && pits.get(idx).getStoneCount() > 0) { pits.get(idx).setIsAvailable(true); } else if (finalPitId == 14 && idx < 13 && idx > 6 && pits.get(idx).getStoneCount() > 0) { pits.get(idx).setIsAvailable(true); } else if (finalPitId == 7 && idx > 6) { pits.get(idx).setIsAvailable(false); } else if (finalPitId == 14 && idx < 6) { pits.get(idx).setIsAvailable(false); } else if (currentPitId < 7 && idx < 13 && idx > 6 && pits.get(idx).getStoneCount() > 0) { pits.get(idx).setIsAvailable(true); } else if (currentPitId > 7 && idx < 6 && pits.get(idx).getStoneCount() > 0) { pits.get(idx).setIsAvailable(true); } else { pits.get(idx).setIsAvailable(false); } } } /* * This function gets the pitIds required for the stones to be moved based on some rules * 1. Players should only place stones in the pits and skip opponents kalah */ private List<Integer> getPitIds(Integer pitId, Pit initialPit) { Integer startAt = pitId + 1; Integer endAt = pitId + initialPit.getStoneCount(); List<Integer> list = IntStream.rangeClosed(startAt, endAt).boxed().collect(Collectors.toList()); // skip 14th if pitId < 7 // skip 7th if pitId > 7, but not the 14th Predicate<Integer> skippingPredicate = pitId < 7 ? id -> id % 14 == 0 : id -> id % 7 == 0 && id % 14 != 0; Integer skipped = Math.toIntExact(list.stream().filter(skippingPredicate).count()); endAt += skipped; List<Integer> pitIds = IntStream.rangeClosed(startAt, endAt).map(id -> { Integer times = id / 14; Integer newId = id - (14 * times); return newId == 0 ? 14 : newId; }).boxed().collect(Collectors.toList()); Predicate<Integer> filterPredicate = pitId < 7 ? p -> p != 14 : p -> p != 7; return pitIds.stream().filter(filterPredicate).collect(Collectors.toList()); } }
true
940abc1eb17a61865f6ae5571af8ff53d16393a6
Java
latougui/gym
/src/main/java/com/latou/gym/domain/Fboard.java
UTF-8
225
1.632813
2
[]
no_license
package com.latou.gym.domain; import lombok.Data; import java.io.Serializable; @Data public class Fboard implements Serializable { private long fboardId; private String fboardName; private String fboardImg; }
true
d5b6a32cee2b8dcec2b587b77c74281bdbf40a53
Java
IlieNemediSilvia/PAO_243
/Laborator1/Example1.java
UTF-8
717
3.203125
3
[]
no_license
package unibuc; public class Example1 { // primitives: byte, short, int, long, float, double, char, boolean // wrapper classes: Byte, Short, Integer, Long, Float, Double, Character, Boolean public static void main(String[] args) { int a = 5, b = 0; short c = 10; long d = 13435L; float e = 6.7f, f = 7.89F; double g = 356.6765; boolean h = true; char j = 'a'; String str = "this is a test"; int sum = 4 + 6; boolean bool = 5 < 10; System.out.println("a+b: " + (a+b)); System.out.println(sum); System.out.println(bool); System.out.println(5 / 2); System.out.println(5 % 2); } }
true
b932af8f99898e7ba143fb715839068967794377
Java
ly01auel/MyProject_1_v1
/MyProjrct_1_v1/src/cn/com/lin/servlet/SendMailServlet.java
UTF-8
2,620
2.578125
3
[]
no_license
package cn.com.lin.servlet; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.Properties; import javax.mail.Message.RecipientType; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class SendMailServlet */ @WebServlet("/SendMailServlet") public class SendMailServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); // 定义返回的信息 String msg = ""; boolean flag = false; /** 获取参数 **/ // 收件人 String revicer = request.getParameter("reciver"); // 标题 String title = request.getParameter("title"); // 内容 String content = request.getParameter("content"); /** **/ try { // 读取配置文件 InputStream in = SendMailServlet.class.getResourceAsStream("/mail.properties"); Properties props = new Properties(); props.load(in); // 创建会话 Session session = Session.getInstance(props); // 穿件邮件体对象(一封邮件对象) MimeMessage message = new MimeMessage(session); message.setSubject(title); message.setSentDate(new Date()); message.setFrom(props.getProperty("user")); message.setRecipient(RecipientType.TO, new InternetAddress(revicer)); message.setContent(content, "text/html;charset=utf-8"); Transport trans = session.getTransport(); trans.connect(props.getProperty("user"), props.getProperty("password")); trans.sendMessage(message, message.getAllRecipients()); trans.close(); msg = "邮件已发送,具体请到邮件客户端进行确认!"; flag = true; } catch (Exception e) { msg = "邮件发送失败,详细原因请联系管理员!"; e.printStackTrace(); } finally { request.setAttribute("msg", msg); request.setAttribute("flag", flag); request.getRequestDispatcher("/sendMail.jsp").forward(request, response); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
true
398788a9003de868716801081e6883b6571e7835
Java
EBIBioSamples/solrReporter
/src/main/java/uk/ac/ebi/solrReporter/sources/DBSource.java
UTF-8
2,903
2.34375
2
[ "Apache-2.0" ]
permissive
package uk.ac.ebi.solrReporter.sources; import oracle.jdbc.pool.OracleDataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; import javax.sql.DataSource; import java.sql.SQLException; import java.util.HashSet; import java.util.Set; @Service public class DBSource implements Source { private Logger log = LoggerFactory.getLogger(this.getClass()); private JdbcTemplate jdbcTemplate; private String sourceURL; @Autowired public void setDataSource(OracleDataSource dataSource) { this.jdbcTemplate = new JdbcTemplate(dataSource); try { sourceURL = dataSource.getURL(); } catch (SQLException e) { log.error("Error getting DB URL.", e); } } @Override public Set<String> getSamplesAccessions() { log.info("Getting public samples accessions from DB."); String samplesAccQuery = "WITH res AS " + "( " + "SELECT b.ACC, COUNT(msi.ACC) AMOUNT FROM BIO_PRODUCT b, MSI_SAMPLE ms, MSI msi " + "WHERE b.ID = ms.SAMPLE_ID " + "AND msi.ID = ms.MSI_ID " + "AND msi.RELEASE_DATE < SYSDATE + 1 " + "AND( b.PUBLIC_FLAG IS NULL OR b.PUBLIC_FLAG = 1) " + "GROUP BY b.ACC" + ") " + "SELECT res.ACC FROM res " + "WHERE res.AMOUNT = 1"; Set<String> accessions = new HashSet<>(); jdbcTemplate.queryForList(samplesAccQuery).forEach(row -> accessions.add((String) row.get("ACC"))); log.info("Successfully fetched " + accessions.size() + " samples accessions from DB."); return accessions; } @Override public Set<String> getGroupsAccessions() { log.info("Getting public groups accessions from DB."); String groupsAccQuery = "WITH res AS" + "(" + "SELECT gp.ACC, COUNT(msi.ACC) AMOUNT FROM BIO_SMP_GRP gp, MSI_SAMPLE_GROUP mg, MSI msi " + "WHERE gp.ID = mg.GROUP_ID " + "AND mg.MSI_ID = msi.ID " + "AND msi.RELEASE_DATE < SYSDATE + 1 " + "AND (gp.PUBLIC_FLAG IS NULL OR gp.PUBLIC_FLAG = 1) " + "GROUP BY gp.ACC " + ") " + "SELECT res.ACC FROM res " + "WHERE res.AMOUNT = 1"; Set<String> accessions = new HashSet<>(); jdbcTemplate.queryForList(groupsAccQuery).forEach(row -> accessions.add((String) row.get("ACC"))); log.info("Successfully fetched " + accessions.size() + " groups accessions from DB."); return accessions; } public String getSourceUrl() { return sourceURL; } }
true
0a5a1921117586d73e1426bc291f8000382a0d0e
Java
ignRyann/General-List-Manager
/src/main/java/model/ModelFactory.java
UTF-8
726
3.21875
3
[]
no_license
package model; import java.io.File; import java.io.IOException; // This class gives access to the model to any other class that needs it. // Calling the static method getModel (i.e., ModelFactory.getModel()) returns // an initialised Model object. This version limits the program to one model object, // which is returned whenever getModel is called. public class ModelFactory { private static Model model; public static Model getModel() throws IOException { if (model == null) { model = new Model(); } // Creates 'data' folder if one does not exist new File("src" + File.separator + "main" + File.separator + "webapp" + File.separator + "data" + File.separator).mkdir(); return model; } }
true
3d2f518c4ec95c5e8cb7b722437316c0408c17ed
Java
songpang/algoritm_archive
/JAVA_Arc/src/ssafy/FindData.java
UTF-8
860
3.046875
3
[]
no_license
package ssafy; public class FindData { public static void main(String[] args) { String[] day = { "FRI", "SAT", "SUN", "MON", "TUE", "WED", "THU" }; int[] date = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; // a 에 월 b에 13 넣어서 // 금요일인지 확인. } static long power(int a, int b) { long res = 1L; while(b > 0) { if(a % 2 == 1) { res *= a; } a = a * a; b >>= 1; } return res; } static int N, R; static long[][] dp = new long[N][R]; static long comb(int n, int r) { if(dp[n][r] > 0) { return dp[n][r]; } if(r == 0 || n == r) { return dp[n][r] = 1; } return dp[n][r] = comb(n-1, r) + comb(n-1, r-1); } }
true
3be90cff0e74eb292440dd878121cc1bbaef421e
Java
i-robot/myshop
/javashop-eop/src/com/enation/app/shop/core/plugin/search/IMultiSelector.java
UTF-8
491
1.835938
2
[]
no_license
package com.enation.app.shop.core.plugin.search; import com.enation.app.shop.core.model.Cat; import java.util.List; import java.util.Map; public abstract interface IMultiSelector { public abstract Map<String, List<SearchSelector>> createMultiSelector(Cat paramCat, String paramString1, String paramString2); } /* Location: D:\project_resource\shop.jar * Qualified Name: com.enation.app.shop.core.plugin.search.IMultiSelector * JD-Core Version: 0.6.1 */
true
3783e558a3cf0a0897ffa0a44811f87281d2412c
Java
zhengjianhui/demo
/demo.service/src/main/java/demo/dao/nosql/impl/Db1TestImpl.java
UTF-8
1,588
2.125
2
[]
no_license
package demo.dao.nosql.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import javax.annotation.Resource; import demo.dao.nosql.DbTest1; /** * Created by zhengjianhui on 16/12/18. */ @Component public class Db1TestImpl implements DbTest1 { // @Qualifier("db2") 选择指定名字的 bean 注入 @Autowired @Qualifier("listenerTemplate") private RedisTemplate<String, String> db1RedisTemplate; @Override public String addTest(final String key, final String value) { String invitationCode = db1RedisTemplate.execute(new RedisCallback<String>() { public String doInRedis(RedisConnection connection) { connection.set(db1RedisTemplate.getStringSerializer().serialize(key), db1RedisTemplate.getStringSerializer().serialize(value)); connection.expire(db1RedisTemplate.getStringSerializer().serialize(key), 20); return key; } }); return invitationCode; } @Override public void clearDB() { db1RedisTemplate.execute(new RedisCallback() { public String doInRedis(RedisConnection connection) { connection.flushDb(); return null; } }); } }
true
8f8c3a2342f534abc0d15efe07a03dba985a03e9
Java
easyfool/learning-core-java
/src/test/java/com/wangfengbabe/learning/classloader/FileClassLoaderTest.java
UTF-8
723
2.515625
3
[]
no_license
package com.wangfengbabe.learning.classloader; import static org.junit.Assert.assertThat; import java.lang.reflect.Method; import org.hamcrest.CoreMatchers; import org.junit.Test; public class FileClassLoaderTest { private FileClassLoader fileClassLoader; @Test public void findClass() throws Exception { String className = "com.wangfengbabe.learning.classloader.HelloWorld"; fileClassLoader = new FileClassLoader("/Users/wangfeng/Documents/keepme"); Class clazz = fileClassLoader.loadClass(className); assertThat(clazz, CoreMatchers.notNullValue()); Method method = clazz.getDeclaredMethod("say", String.class); Object obj = clazz.newInstance(); method.invoke(obj, "world"); } }
true
15c8a1ee64019346a5d36f0e71d9463e03c937db
Java
shristy-chaudhary/Nimesh
/lab1/src/Question4/Modulo7.java
UTF-8
376
3.765625
4
[]
no_license
package Question4; public class Modulo7 { public static void main(String[] args) { int count = 0; int sum = 0; for (int i = 100; i < 200; i++) { if (i % 7 == 0) { count += 1; sum += i; System.out.println(i + "\t is divisible by 7"); } } System.out.println("The total numbers divisible by 7 is : " + count + "\t The sum is : " + sum); } }
true
64ec9bfd15ac9f525bc507ed1b8c19aec6fdcd38
Java
MuhammadAmmad/BackStack
/demo/src/main/java/com/rievo/android/backstack/ViewGroup2.java
UTF-8
1,077
2.21875
2
[ "Apache-2.0" ]
permissive
package com.rievo.android.backstack; import android.content.Context; import android.graphics.Color; import android.rievo.com.backstack.R; import android.view.LayoutInflater; import android.widget.Button; import android.widget.RelativeLayout; import android.widget.TextView; import com.rievo.android.library.LinearBackStack; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by kevin on 2017-04-29. */ public class ViewGroup2 extends RelativeLayout { @BindView(R.id.my_relative_layout) RelativeLayout relativeLayout; @BindView(R.id.next_button) Button nextButton; public ViewGroup2(Context context) { super(context); LayoutInflater.from(context).inflate(R.layout.demo_layout, this, true); ButterKnife.bind(this); relativeLayout.setBackgroundColor(Color.WHITE); nextButton.setOnClickListener(view -> { LinearBackStack.get(MainActivity.TAG) .replaceView(new ViewGroup3.ViewGroup3Creator("This is some text")) .done(); }); } }
true
64d8650950ef40a02e36ca8f6f98575b19ca6d37
Java
CS2103AUG2017-T14-B4/main
/src/main/java/seedu/address/model/person/Birthday.java
UTF-8
1,118
3.03125
3
[ "MIT" ]
permissive
//@@ author NgSuli package seedu.address.model.person; import static java.util.Objects.requireNonNull; import seedu.address.commons.exceptions.IllegalValueException; /** * Represents a Person's birthday in the address book. */ public class Birthday { public static final String MESSAGE_ADDRESS_CONSTRAINTS = "Person birthday can take any values, and it should not be blank"; public final String value; /** * Validates given address. * * @throws IllegalValueException if given address string is invalid. */ public Birthday(String birthday) { requireNonNull(birthday); this.value = birthday; } @Override public String toString() { return value; } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof Birthday // instanceof handles nulls && this.value.equals(((Birthday) other).value)); // state check } @Override public int hashCode() { return value.hashCode(); } } //@@ author
true
ce47c5e49d24a18886ac0d9936ae99d575f8876f
Java
printmiles/MARS
/src/mars/mars/events/FDEditor_BuildFormatDoc.java
UTF-8
683
2.171875
2
[]
no_license
/* Class name: FDEditor_BuildFormatDoc * File name: FDEditor_BuildFormatDoc.java * Created: 30-May-2008 15:56:06 * Modified: 30-May-2008 * Version History: * ~ ~ ~ ~ ~ ~ ~ ~ ~ * 0.001 30-May-2008 Initial build */ package mars.mars.events; import java.awt.event.*; import mars.mars.object.table.GenericTable; /** * This class currently does not have any JavaDoc comments included * @version 0.001 * @author Alex Harris (W4786241) */ public class FDEditor_BuildFormatDoc implements ActionListener { public FDEditor_BuildFormatDoc(GenericTable sourcedata, String source) { // Default constructor } public void actionPerformed(ActionEvent ae) { } }
true
58943e8e64543740bf12a7e510a9849bcc6afb14
Java
ding99/JavaSyntax
/cOptional/src/main/java/Action.java
UTF-8
2,555
3.421875
3
[]
no_license
package main.java; import java.util.Optional; /** * Created by dingw on 7/24/2019. */ public class Action { public Action(){} private void testMap(Optional<String> opt){ Optional<String> upperName = opt.map((value) -> value.toUpperCase()); System.out.println(upperName.orElse("No value found")); } private void testFlatMap(Optional<String> opt){ Optional<String> upperName = opt.flatMap((value) -> Optional.of(value.toUpperCase())); System.out.println(upperName.orElse("No value found")); } private void testFilter(Optional<String> opt){ Optional<String> longName = opt.filter((value) -> value.length() > 6); System.out.println(longName.orElse("The name is not longer than 6")); } public void vary(){ //region null. if of() received a null, an exception will be caused System.out.println("-- null (Exception if of() receives a null)"); Optional<String> someNull; try { someNull = Optional.of(null); } catch(Exception e){ System.out.println("Error: [" + e.getMessage() + "]"); } //endregion Optional<String> name = Optional.of("Steve"); Optional empty = Optional.ofNullable(null); //ofNullable() may receive a null //region ifPresent System.out.println("-- ifPresent (use Consumer<T> interface)"); name.ifPresent((value) -> { System.out.println("value (" + value + ") length " + value.length()); }); //endregion //region orElse System.out.println("-- orElse (use specific default if null)"); System.out.println(empty.orElse("no value present")); System.out.println(name.orElse("some value")); //endregion //region orElseGet System.out.println("-- orElseGet (use default for Supplier<T> interface if null)"); System.out.println(empty.orElseGet(() -> "default value")); System.out.println(name.orElseGet(() -> "default value")); //endregion //region map System.out.println("-- map"); testMap(name); testMap(empty); //endregion //region flatMap //input of flatMap must be of Optional System.out.println("-- flatMap"); testFlatMap(name); testFlatMap(empty); //endregion //region filter System.out.println("-- filter"); testFilter(Optional.of("Jeffrey")); testFilter(name); testFilter(empty); //endregion } }
true
0901a6a29aad92914f013c0d5f0198d2523cd24e
Java
loryrosh/EPAM_hw
/src/main/java/EPAM/lesson170710/hw/HelloWorldBench.java
UTF-8
191
1.679688
2
[]
no_license
package EPAM.lesson170710.hw; import org.openjdk.jmh.annotations.GenerateMicroBenchmark; public class HelloWorldBench { @GenerateMicroBenchmark public void helloWorld() { } }
true
81e891242d257a7f8063a14d5be195d6a61bf574
Java
anschauf/UserRequestReferencer
/src/main/java/Two_Linking.java
UTF-8
2,785
2.890625
3
[]
no_license
import codeLinking.SourceCodeLinker; import helper.Constants; import helper.Review; import helper.TrainingSetToDB; import preclassification.PreClassification; import preclassification.PreclassificationDBImport; import subclassification.SubClassifier; import java.util.List; //TODO: better name public class Two_Linking implements Constants { public static void main(String[] args) throws Exception { argumentCheck(args); String dbName; PreClassification preclassification = PreClassification.valueOf(args[0]); if(args[1].equals("test")) { dbName = DBNAME_TEST; } else { dbName = DBNAME; } //2.1 Update review's preclassification PreclassificationDBImport preClassImport = new PreclassificationDBImport(dbName); preClassImport.importPreClassificationIntoDB(); //2.2 write trainingSet into DB if not done yet if(!preClassImport.collectionExists(TRAININGSET_COLLECTION)) { System.out.println("Loading Training-Set into DB"); TrainingSetToDB trainingSetToDB = new TrainingSetToDB(dbName); trainingSetToDB.writeTrainingSetIntoDB(); } //3. Subclassify the reviews SubClassifier subClassifier = new SubClassifier(dbName, preclassification); List<Review> reviews = subClassifier.subClassify(); //4. SourceCode Linking SourceCodeLinker sourceCodeLinker = new SourceCodeLinker(reviews, dbName); } /** * Checks the given argument. Prints out corresponding error-message * @param args */ private static void argumentCheck(String[] args) { PreClassification preclassification = null; if(args.length != 2) { System.out.println("Wrong number of arguments! Use of program: java StepTwo <preclassification> <mode>"); System.out.println("Whereas <preclassification> is one of the following arguments:"); System.out.println("\t RESSOURCES, PRICING, PROTECTION, USAGE, COMPATIBILITY"); System.out.println("and mode is either 'test' or 'prod'"); System.exit(0); } try { preclassification = PreClassification.valueOf(args[0]); } catch (IllegalArgumentException e) { System.out.println("Wrong preclassification! Use one of the following as first argument:"); System.out.println("\t RESSOURCES, PRICING, PROTECTION, USAGE, COMPATIBILITY"); System.exit(0); } if(!args[1].equals("test") && !args[1].equals("prod")) { System.out.println("Wrong mode! Use one of the following as second argument:"); System.out.println("\t test, prod"); System.exit(0); } } }
true
7dc96ef6b9ed3abf81526ac17121d9c0d802b59d
Java
nycqw/eden-common
/src/main/java/com/eden/common/exception/SwitchCloseException.java
UTF-8
309
2.25
2
[]
no_license
package com.eden.common.exception; /** * 开关关闭异常 * * @author chenqw * @version 1.0 * @since 2019/1/6 */ public class SwitchCloseException extends RuntimeException { public SwitchCloseException(String message) { super("开关【" + message + "】关闭,请求失败"); } }
true
e2432a8d004df2fafbfae58cc8800842f725c127
Java
chendaben/Shop_Design
/src/main/java/com/cyq/bookstore/controller/UsersController.java
UTF-8
4,530
2.421875
2
[]
no_license
package com.cyq.bookstore.controller; /** * 对用户的相关操作 */ import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import com.cyq.bookstore.pojo.Books; import com.cyq.bookstore.pojo.Category; import com.cyq.bookstore.pojo.Users; import com.cyq.bookstore.service.BooksService; import com.cyq.bookstore.service.CategoryService; import com.cyq.bookstore.service.UsersService; @Controller @RequestMapping(value="/user") public class UsersController { @Resource private UsersService usersService; @Resource private BooksService bookService; @Resource private CategoryService categoryService; private static Logger Log=LoggerFactory.getLogger(UsersController.class); /** * 登录验证 */ @ResponseBody @RequestMapping(value = "/login", method = RequestMethod.POST) public Users login(@RequestParam String UserPhone, @RequestParam String UserPassword,HttpSession session) { Users user = new Users(); user.setUserphone(UserPhone); user.setUserpassword(UserPassword); if (usersService.selectUsers(user) != null) { user = usersService.selectUsers(user); Log.info("能查到信息"); session.setAttribute("userId", user.getUserid()); return user; } return null; } /** * 首页 * @param usergrade(1:表示普通用户,2:是管理员) * @return */ @RequestMapping(value = "/index", method = RequestMethod.GET) @ModelAttribute public ModelAndView userBookList(@RequestParam String usergrade){ if (usergrade.equals(1)){ Map<String, Object> model = new HashMap<String, Object>(); //书籍类别信息 List<Category> categorylist=categoryService.selectAllCategory(); model.put("categoryList", categorylist); //书籍信息 List<Books> list = bookService.selectAllBook(); model.put("bookList", list); return new ModelAndView("index", model); }else { return new ModelAndView("indexAdmin", null); } } /** * 用户注册 * @return */ @ResponseBody @RequestMapping(value = "/regist", method = RequestMethod.POST) public int save(@RequestParam String username,@RequestParam String userpassword,@RequestParam String userphone, @RequestParam String useremail) { return usersService.insertUser(username,userpassword,userphone,useremail); } /** * 展示所有用户信息 * @param pageNow * @param pageSize * @return */ @ResponseBody @RequestMapping(method=RequestMethod.GET) public List<Users> showUser(@RequestParam(required=false,defaultValue="1") int pageNow,@RequestParam(required=false,defaultValue="3") int pageSize){ int totalCount=usersService.showAllCount(); List<Users> userList=usersService.showUser(pageNow,pageSize); return userList; } /** * 根据id删除用户 * * @param userid * @return */ @ResponseBody @RequestMapping("/{userid}/delete") public int deleteUser(@PathVariable Integer userid) { return usersService.deleteUserById(userid); } /** * 根据session中的id得到用户个人信息 * * @return */ @ResponseBody @RequestMapping(value = "/info",method=RequestMethod.GET) public Users getUserBySession(HttpSession session) { Integer userId=(Integer) session.getAttribute("userId"); Users user=usersService.getUserById(userId); return user; } /** * 根据 id得到个人信息 * @param id * @return */ @ResponseBody @RequestMapping(value = "/{id}/info",method=RequestMethod.GET) public Users getUserById(@PathVariable int id) { Users user=usersService.getUserById(id); return user; } /** * 更新用户信息 * */ @ResponseBody @RequestMapping(value="/{userid}/update",method=RequestMethod.POST) public void updateUser(@PathVariable int userid,@RequestParam String username,@RequestParam String userpassword,@RequestParam String userphone, @RequestParam String useremail) { Users user=new Users(); user.setUserid(userid); user.setUsername(username); user.setUserpassword(userpassword); user.setUserphone(userphone); user.setUseremail(useremail); usersService.updateUser(user); } }
true
56aa601fb819fe2fd9da8abd247423f0da9cd408
Java
Muktha-J-S/Java-basics
/ex2.java
UTF-8
258
2.578125
3
[]
no_license
package javaclass; public class ex2 { public static void main(String[] args) { // TODO Auto-generated method stub int num,num1,result1; num=10; num1=10; result1= num*num1; System.out.println("The result is "+result1); } }
true
49c3ef46c2042edfa402523fb47d778a5f9cc49d
Java
havlisimo/NotificationServer
/src/main/java/cz/cvut/fit/havlito4/notification_server/controller/entity/NotificationRequest.java
UTF-8
965
2.359375
2
[]
no_license
package cz.cvut.fit.havlito4.notification_server.controller.entity; public class NotificationRequest { private String notidficationId; private String receiverId; private String type; public String getNotidficationId() { return notidficationId; } public void setNotidficationId(String notidficationId) { this.notidficationId = notidficationId; } public String getReceiverId() { return receiverId; } public void setReceiverId(String receiverId) { this.receiverId = receiverId; } public String getType() { return type; } public void setType(String type) { this.type = type; } @Override public String toString() { return "NotificationRequest{" + "notidficationId='" + notidficationId + '\'' + ", receiverId='" + receiverId + '\'' + ", type='" + type + '\'' + '}'; } }
true
5cc20928d85e3f7552a17c01f673d0eeaa08aa64
Java
Yaroslav19/Inventory_Kiryack
/src/com/netcracker/edu/inventory/model/impl/RackArrayImpl.java
UTF-8
1,658
3.171875
3
[]
no_license
package com.netcracker.edu.inventory.model.impl; import com.netcracker.edu.inventory.model.Device; import com.netcracker.edu.inventory.model.Rack; public class RackArrayImpl implements Rack { protected Device[] devices; public RackArrayImpl(int size){ if(size > 0){ devices = new Device[size]; }else { System.err.println("Value of size isn't "); } } @Override public int getSize() { return devices.length; } @Override public int getFreeSize() { int count = 0; for (Device device : devices) if(device == null) count++; return count; } @Override public Device getDevAtSlot(int index) { if(devices[index] != null && index >= 0 && index < devices.length){ return devices[index]; } return null; } @Override public boolean insertDevToSlot(Device device, int index) { if( index >= 0 && index < devices.length && devices[index] == null && device.getIn() > 0 ){ devices[index] = device; return true; } return false; } @Override public Device removeDevFromSlot(int index) { if(devices[index] != null && index >= 0 && index < devices.length){ Device buff = devices[index]; devices[index] = null; return buff; } return null; } @Override public Device getDevByIN(int in) { for (Device device : devices) if (device.getIn() == in && device != null) return device; return null; } }
true
59a396321a34b5fd88b7d173fe15e138a7b8f8b1
Java
marembo2008/vjax
/src/main/java/com/anosym/vjax/converter/VBooleanConverter.java
UTF-8
1,229
2.890625
3
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.anosym.vjax.converter; import com.anosym.vjax.exceptions.VConverterBindingException; /** * * @author Marembo */ public class VBooleanConverter extends VConverter<Boolean> { public Boolean convert(String value) throws VConverterBindingException { //convert it based on yes/no, true/false, 0/1, value = value.trim(); if ("yes".equalsIgnoreCase(value.trim()) || "true".equalsIgnoreCase(value) || "1".equalsIgnoreCase(value)) { return true; } else if ("no".equalsIgnoreCase(value) || "false".equalsIgnoreCase(value) || "0".equalsIgnoreCase(value)) { return false; } else { throw new VConverterBindingException("Invalid boolean representation"); } } public String convert(Boolean value) throws VConverterBindingException { try { return (value) ? "true" : "false"; } catch (Exception e) { throw new VConverterBindingException(e); } } public boolean isConvertCapable(Class<Boolean> clazz) { return clazz == boolean.class || clazz == Boolean.class; } }
true
95ad99e178e1a3ec6959293a9e7f9644252085ba
Java
bkaminnski/enrichers-in-completable-futures
/payments/src/main/java/com/hclc/enrichers/payments/control/PaymentsRepository.java
UTF-8
2,266
2.453125
2
[]
no_license
package com.hclc.enrichers.payments.control; import com.hclc.enrichers.payments.entity.Payment; import org.springframework.stereotype.Repository; import javax.annotation.PostConstruct; import java.math.BigDecimal; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Collections; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; @Repository public class PaymentsRepository { private final ConcurrentHashMap<String, List<Payment>> paymentsByCustomerId = new ConcurrentHashMap<>(); @PostConstruct public void prepareData() { paymentsByCustomerId.put("45e091bf-edbf-4f80-9dd4-90ad50fe131a", generate("86d9863e-9baf-49e8-80e8-0e27ed7c90fc", "2000-04-17T23:59:59", "2019-03-17T23:59:59", new BigDecimal("458.92"))); paymentsByCustomerId.put("ab7a68cb-bcd2-4580-a155-a2bd005f4fde", generate("0b67c86f-d9cc-41ce-909f-a9bcdf1f6a50", "2017-12-02T23:59:59", "2019-04-02T23:59:59", new BigDecimal("188.19"))); } private List<Payment> generate(String policyId, String firstPaymentDueDate, String lastPaymentDueDate, BigDecimal amount) { List<Payment> payments = new LinkedList<>(); LocalDateTime dueDate = LocalDateTime.parse(firstPaymentDueDate); LocalDateTime lastDueDate = LocalDateTime.parse(lastPaymentDueDate); int i = 0; while (!dueDate.isAfter(lastDueDate)) { int daysLate = 0; Date paymentDate = asDate(dueDate.minusDays(2).withHour(12).withMinute(0).withSecond(0)); if (i > 0 && i % 10 == 0) { daysLate = 3; paymentDate = asDate(dueDate.plusDays(daysLate).withHour(12).withMinute(0).withSecond(0)); } payments.add(new Payment(policyId, asDate(dueDate), paymentDate, amount, daysLate)); dueDate = dueDate.plusMonths(1); i++; } return payments; } private Date asDate(LocalDateTime date) { return Date.from(date.atZone(ZoneId.systemDefault()).toInstant()); } public List<Payment> findByCustomerId(String customerId) { return Collections.unmodifiableList(paymentsByCustomerId.getOrDefault(customerId, new LinkedList<>())); } }
true
ef09d99087f387ff657057efe9eeed6c738619c3
Java
pivovarovanatol/leetcodepractice
/leetcodepractice/Array/com/leetcode/algors/OneBitAndTwoBitCharacters/OneBitAndTwoBitCharacterTest.java
UTF-8
1,809
3.046875
3
[]
no_license
package com.leetcode.algors.OneBitAndTwoBitCharacters; //https://leetcode.com/problems/degree-of-an-array/ import org.junit.Assert; import org.junit.Test; public class OneBitAndTwoBitCharacterTest { @Test public void emptyArrayTest(){ // given int[] arr = {}; Solution sl = new Solution(); // when boolean result = sl.isOneBitCharacter(arr); // then boolean expected = false; Assert.assertEquals(expected, result); } @Test public void oneSymbolArrayTest(){ // given int[] arr = {0}; Solution sl = new Solution(); // when boolean result = sl.isOneBitCharacter(arr); // then boolean expected = true; Assert.assertEquals(expected, result); } @Test public void twoSymbolArrayTest(){ // given int[] arr = {1, 0}; Solution sl = new Solution(); // when boolean result = sl.isOneBitCharacter(arr); // then boolean expected = false; Assert.assertEquals(expected, result); } @Test public void twoSymbolTrueArrayTest(){ // given int[] arr = {0, 0}; Solution sl = new Solution(); // when boolean result = sl.isOneBitCharacter(arr); // then boolean expected = true; Assert.assertEquals(expected, result); } @Test public void threeSymbolArrayTest(){ // given int[] arr = {1, 0, 0}; Solution sl = new Solution(); // when boolean result = sl.isOneBitCharacter(arr); // then boolean expected = true; Assert.assertEquals(expected, result); } @Test public void regularArrayTest(){ // given int[] arr = {1, 1, 1, 0}; Solution sl = new Solution(); // when boolean result = sl.isOneBitCharacter(arr); // then boolean expected = false; Assert.assertEquals(expected, result); } }
true
04d9187e02bcf1031846a15be08e6ae19e9f9311
Java
rpomeroy/muhuru-bay-dashboard
/src/main/java/org/mbmg/MainUI.java
UTF-8
943
2.34375
2
[]
no_license
package org.mbmg; import com.vaadin.server.VaadinRequest; import com.vaadin.ui.Button; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.Notification; import com.vaadin.ui.UI; import com.vaadin.ui.VerticalLayout; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class MainUI extends UI implements Button.ClickListener{ private static final long serialVersionUID = 1L; @Autowired private MyService service; @Override protected void init(VaadinRequest request) { final VerticalLayout layout = new VerticalLayout(); layout.setMargin(true); Button button = new Button("Click Me"); button.addClickListener(this); layout.addComponent(button); setContent(layout); } @Override public void buttonClick(ClickEvent event) { Notification.show(service.sayHello()); } }
true
978dd524e277d240fdd00a3ebe3bd87a807b8410
Java
mr-universe-guy/DungeonHoard
/src/com/mru/ld40/health/DamageComponent.java
UTF-8
745
2.40625
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 com.mru.ld40.health; import com.simsilica.es.EntityComponent; import com.simsilica.es.EntityId; /** * * @author Matthew Universe <ff8loser@gmail.com> */ public class DamageComponent implements EntityComponent{ private final long damage; private final EntityId target; public DamageComponent(EntityId target, long damage){ this.target = target; this.damage = damage; } public long getDamage(){ return damage; } public EntityId getTarget(){ return target; } }
true
63a744eda18f76800bad6da3ca89a77ba0ca8e3b
Java
ostigter/testproject3
/azureus-core/src/main/java/org/gudy/azureus2/core3/tracker/server/impl/TRTrackerServerPeerImpl.java
UTF-8
13,478
1.601563
2
[]
no_license
/* * File : TRTrackerServerPeerImpl.java * Created : 5 Oct. 2003 * By : Parg * * Azureus - a Java Bittorrent client * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details ( see the LICENSE file ). * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.gudy.azureus2.core3.tracker.server.impl; import java.net.InetAddress; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.gudy.azureus2.core3.tracker.server.TRTrackerServerPeer; import org.gudy.azureus2.core3.util.HashWrapper; import org.gudy.azureus2.core3.util.HostNameToIPResolver; import org.gudy.azureus2.core3.util.HostNameToIPResolverListener; import org.gudy.azureus2.core3.util.SystemTime; import com.aelitis.azureus.core.dht.netcoords.DHTNetworkPosition; public class TRTrackerServerPeerImpl implements TRTrackerServerPeer, TRTrackerServerSimplePeer, HostNameToIPResolverListener, TRTrackerServerNatCheckerListener { private HashWrapper peer_id; private int key_hash_code; private byte[] ip; private boolean ip_override; private short tcp_port; private short udp_port; private short http_port; private byte crypto_level; private byte az_ver; private String ip_str; private byte[] ip_bytes; private byte NAT_status = NAT_CHECK_UNKNOWN; private long timeout; private long uploaded; private long downloaded; private long amount_left; private long last_contact_time; private boolean download_completed; private boolean biased; private short up_speed; // fields above are serialised when exported private DHTNetworkPosition network_position; private Object user_data; protected TRTrackerServerPeerImpl(HashWrapper _peer_id, int _key_hash_code, byte[] _ip, boolean _ip_override, int _tcp_port, int _udp_port, int _http_port, byte _crypto_level, byte _az_ver, long _last_contact_time, boolean _download_completed, byte _last_nat_status, int _up_speed, DHTNetworkPosition _network_position) { peer_id = _peer_id; key_hash_code = _key_hash_code; ip = _ip; ip_override = _ip_override; tcp_port = (short) _tcp_port; udp_port = (short) _udp_port; http_port = (short) _http_port; crypto_level = _crypto_level; az_ver = _az_ver; last_contact_time = _last_contact_time; download_completed = _download_completed; NAT_status = _last_nat_status; up_speed = _up_speed > Short.MAX_VALUE ? Short.MAX_VALUE : (short) _up_speed; network_position = _network_position; resolveAndCheckNAT(); } /** * Import constructor */ protected TRTrackerServerPeerImpl(HashWrapper _peer_id, int _key_hash_code, byte[] _ip, boolean _ip_override, short _tcp_port, short _udp_port, short _http_port, byte _crypto_level, byte _az_ver, String _ip_str, byte[] _ip_bytes, byte _NAT_status, long _timeout, long _uploaded, long _downloaded, long _amount_left, long _last_contact_time, boolean _download_completed, boolean _biased, short _up_speed) { peer_id = _peer_id; key_hash_code = _key_hash_code; ip = _ip; ip_override = _ip_override; tcp_port = _tcp_port; udp_port = _udp_port; http_port = _http_port; crypto_level = _crypto_level; az_ver = _az_ver; ip_str = _ip_str; ip_bytes = _ip_bytes; NAT_status = _NAT_status; timeout = _timeout; uploaded = _uploaded; downloaded = _downloaded; amount_left = _amount_left; last_contact_time = _last_contact_time; download_completed = _download_completed; biased = _biased; up_speed = _up_speed; } protected boolean update(byte[] _ip, int _port, int _udp_port, int _http_port, byte _crypto_level, byte _az_ver, int _up_speed, DHTNetworkPosition _network_position) { udp_port = (short) _udp_port; http_port = (short) _http_port; crypto_level = _crypto_level; az_ver = _az_ver; up_speed = _up_speed > Short.MAX_VALUE ? Short.MAX_VALUE : (short) _up_speed; network_position = _network_position; boolean res = false; if (_port != getTCPPort()) { tcp_port = (short) _port; res = true; } if (!Arrays.equals(_ip, ip)) { ip = _ip; res = true; } if (res) { resolveAndCheckNAT(); } return (res); } public void NATCheckComplete(boolean ok) { if (ok) { NAT_status = NAT_CHECK_OK; } else { NAT_status = NAT_CHECK_FAILED; } } protected void setNATStatus(byte status) { NAT_status = status; } public byte getNATStatus() { return (NAT_status); } protected boolean isNATStatusBad() { return (NAT_status == NAT_CHECK_FAILED || NAT_status == NAT_CHECK_FAILED_AND_REPORTED); } protected void resolveAndCheckNAT() { // default values pending resolution ip_str = new String(ip); ip_bytes = null; HostNameToIPResolver.addResolverRequest(ip_str, this); // a port of 0 is taken to mean that the client can't/won't receive incoming // connections - tr if (tcp_port == 0) { NAT_status = NAT_CHECK_FAILED_AND_REPORTED; } else { // only recheck if we haven't already ascertained the state if (NAT_status == NAT_CHECK_UNKNOWN) { NAT_status = NAT_CHECK_INITIATED; if (!TRTrackerServerNATChecker.getSingleton().addNATCheckRequest(ip_str, getTCPPort(), this)) { NAT_status = NAT_CHECK_DISABLED; } } } } public void hostNameResolutionComplete(InetAddress address) { if (address != null) { ip_str = address.getHostAddress(); ip_bytes = address.getAddress(); } } protected long getLastContactTime() { return (last_contact_time); } protected boolean getDownloadCompleted() { return (download_completed); } protected void setDownloadCompleted() { download_completed = true; } public boolean isBiased() { return (biased); } public void setBiased(boolean _biased) { biased = _biased; } public HashWrapper getPeerId() { return (peer_id); } public byte[] getPeerID() { return (peer_id.getBytes()); } protected int getKeyHashCode() { return (key_hash_code); } public byte[] getIPAsRead() { return (ip); } public String getIPRaw() { return (new String(ip)); } /** * If asynchronous resolution of the address is required, this will return the non-resolved address until the async process completes */ public String getIP() { return (ip_str); } protected boolean isIPOverride() { return (ip_override); } /** * This will return in resolution of the address is not complete or fails * * @return */ public byte[] getIPAddressBytes() { return (ip_bytes); } public int getTCPPort() { return (tcp_port & 0xffff); } public int getUDPPort() { return (udp_port & 0xffff); } public int getHTTPPort() { return (http_port & 0xffff); } public byte getCryptoLevel() { return (crypto_level); } public byte getAZVer() { return (az_ver); } public int getUpSpeed() { return (up_speed & 0xffff); } public DHTNetworkPosition getNetworkPosition() { return (network_position); } protected void setTimeout(long _now, long _timeout) { last_contact_time = _now; timeout = _timeout; } protected long getTimeout() { return (timeout); } public int getSecsToLive() { return ((int) ((timeout - SystemTime.getCurrentTime()) / 1000)); } protected void setStats(long _uploaded, long _downloaded, long _amount_left) { uploaded = _uploaded; downloaded = _downloaded; amount_left = _amount_left; } public long getUploaded() { return (uploaded); } public long getDownloaded() { return (downloaded); } public long getAmountLeft() { return (amount_left); } public boolean isSeed() { return (amount_left == 0); } public void setUserData(Object key, Object data) { if (user_data == null) { user_data = new Object[] { key, data }; } else if (user_data instanceof Object[]) { Object[] x = (Object[]) user_data; if (x[0] == key) { x[1] = data; } else { HashMap map = new HashMap(); user_data = map; map.put(x[0], x[1]); map.put(key, data); } } else { ((Map) user_data).put(key, data); } } public Object getUserData(Object key) { if (user_data == null) { return (null); } else if (user_data instanceof Object[]) { Object[] x = (Object[]) user_data; if (x[0] == key) { return (x[1]); } else { return (null); } } else { return (((Map) user_data).get(key)); } } public Map export() { Map map = new HashMap(); map.put("peer_id", peer_id.getBytes()); map.put("key_hash_code", new Long(key_hash_code)); map.put("ip", ip); map.put("ip_override", new Long(ip_override ? 1 : 0)); map.put("tcp_port", new Long(tcp_port)); map.put("udp_port", new Long(udp_port)); map.put("http_port", new Long(http_port)); map.put("crypto_level", new Long(crypto_level)); map.put("az_ver", new Long(az_ver)); map.put("ip_str", ip_str); if (ip_bytes != null) { map.put("ip_bytes", ip_bytes); } map.put("NAT_status", new Long(NAT_status)); map.put("timeout", new Long(timeout)); map.put("uploaded", new Long(uploaded)); map.put("downloaded", new Long(downloaded)); map.put("amount_left", new Long(amount_left)); map.put("last_contact_time", new Long(last_contact_time)); map.put("download_completed", new Long(download_completed ? 1 : 0)); map.put("biased", new Long(biased ? 1 : 0)); map.put("up_speed", new Long(up_speed)); return (map); } public static TRTrackerServerPeerImpl importPeer(Map map) { try { HashWrapper peer_id = new HashWrapper((byte[]) map.get("peer_id")); int key_hash_code = ((Long) map.get("key_hash_code")).intValue(); byte[] ip = (byte[]) map.get("ip"); boolean ip_override = ((Long) map.get("ip_override")).intValue() == 1; short tcp_port = ((Long) map.get("tcp_port")).shortValue(); short udp_port = ((Long) map.get("udp_port")).shortValue(); short http_port = ((Long) map.get("http_port")).shortValue(); byte crypto_level = ((Long) map.get("crypto_level")).byteValue(); byte az_ver = ((Long) map.get("az_ver")).byteValue(); String ip_str = new String((byte[]) map.get("ip_str")); byte[] ip_bytes = (byte[]) map.get("ip_bytes"); byte NAT_status = ((Long) map.get("NAT_status")).byteValue(); long timeout = ((Long) map.get("timeout")).longValue(); long uploaded = ((Long) map.get("uploaded")).longValue(); long downloaded = ((Long) map.get("downloaded")).longValue(); long amount_left = ((Long) map.get("amount_left")).longValue(); long last_contact_time = ((Long) map.get("last_contact_time")).longValue(); boolean download_completed = ((Long) map.get("download_completed")).intValue() == 1; boolean biased = ((Long) map.get("biased")).intValue() == 1; short up_speed = ((Long) map.get("up_speed")).shortValue(); return (new TRTrackerServerPeerImpl(peer_id, key_hash_code, ip, ip_override, tcp_port, udp_port, http_port, crypto_level, az_ver, ip_str, ip_bytes, NAT_status, timeout, uploaded, downloaded, amount_left, last_contact_time, download_completed, biased, up_speed)); } catch (Throwable e) { return (null); } } protected String getString() { return (new String(ip) + ":" + getTCPPort() + "(" + new String(peer_id.getHash()) + ")"); } }
true
9b041fb14e6584ae43a50a688d5c8210adbc7b62
Java
timboudreau/netbeans-contrib
/portalpack.portlets.genericportlets/src/main/java/org/netbeans/modules/portalpack/portlets/genericportlets/storyboard/ipc/CustomVMDGraphScene.java
UTF-8
7,669
1.820313
2
[ "Apache-2.0" ]
permissive
/* * The contents of this file are subject to the terms of the Common Development * and Distribution License (the License). You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at http://www.netbeans.org/cddl.html * or http://www.netbeans.org/cddl.txt. * * When distributing Covered Code, include this CDDL Header Notice in each file * and include the License file at http://www.netbeans.org/cddl.txt. * If applicable, add the following below the CDDL Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * The Original Software is NetBeans. The Initial Developer of the Original * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun * Microsystems, Inc. All Rights Reserved. */ package org.netbeans.modules.portalpack.portlets.genericportlets.storyboard.ipc; import org.netbeans.modules.portalpack.portlets.genericportlets.storyboard.widgets.CustomPinWidget; import org.netbeans.api.visual.action.ActionFactory; import org.netbeans.api.visual.action.PopupMenuProvider; import org.netbeans.api.visual.action.WidgetAction; import org.netbeans.api.visual.anchor.Anchor; import org.netbeans.api.visual.anchor.AnchorFactory; import org.netbeans.api.visual.graph.GraphPinScene; import org.netbeans.api.visual.graph.layout.GridGraphLayout; import org.netbeans.api.visual.layout.LayoutFactory; import org.netbeans.api.visual.layout.SceneLayout; import org.netbeans.api.visual.router.Router; import org.netbeans.api.visual.router.RouterFactory; import org.netbeans.api.visual.vmd.VMDConnectionWidget; import org.netbeans.api.visual.vmd.VMDNodeWidget; import org.netbeans.api.visual.vmd.VMDPinWidget; import org.netbeans.api.visual.widget.ConnectionWidget; import org.netbeans.api.visual.widget.LayerWidget; import org.netbeans.api.visual.widget.Widget; import org.netbeans.api.visual.widget.EventProcessingType; import javax.swing.*; import java.awt.*; import org.netbeans.modules.portalpack.portlets.genericportlets.storyboard.ipc.actions.IPCPopUpMenuProvider; import org.netbeans.modules.portalpack.portlets.genericportlets.storyboard.widgets.CustomNodeWidget; /** * * @author Satyaranjan */ public abstract class CustomVMDGraphScene extends GraphPinScene<String, String, String> { public static final String PIN_ID_DEFAULT_SUFFIX = "#default"; // NOI18N protected LayerWidget backgroundLayer = new LayerWidget (this); protected LayerWidget mainLayer = new LayerWidget (this); protected LayerWidget connectionLayer = new LayerWidget (this); protected LayerWidget upperLayer = new LayerWidget (this); private Router router; private WidgetAction moveControlPointAction = ActionFactory.createOrthogonalMoveControlPointAction (); private WidgetAction moveAction = ActionFactory.createMoveAction (); private SceneLayout sceneLayout; public CustomVMDGraphScene () { setKeyEventProcessingType (EventProcessingType.FOCUSED_WIDGET_AND_ITS_PARENTS); addChild (backgroundLayer); addChild (mainLayer); addChild (connectionLayer); addChild (upperLayer); router = RouterFactory.createOrthogonalSearchRouter (mainLayer, connectionLayer); getActions ().addAction (ActionFactory.createZoomAction ()); getActions ().addAction (ActionFactory.createPanAction ()); getActions ().addAction (ActionFactory.createRectangularSelectAction (this, backgroundLayer)); sceneLayout = LayoutFactory.createSceneGraphLayout (this, new GridGraphLayout<String, String> ().setChecker (true)); } /** * Implements attaching a widget to a node. The widget is VMDNodeWidget and has object-hover, select, popup-menu and move actions. * @param node the node * @return the widget attached to the node */ protected Widget attachNodeWidget (String node) { CustomNodeWidget widget = new CustomNodeWidget (this); mainLayer.addChild (widget); widget.getHeader ().getActions ().addAction (createObjectHoverAction ()); // widget.getActions ().addAction (createSelectAction ()); // widget.getActions ().addAction (popupMenuAction); widget.getActions ().addAction (moveAction); return widget; } /** * Implements attaching a widget to a pin. The widget is VMDPinWidget and has object-hover and select action. * The the node id ends with "#default" then the pin is the default pin of a node and therefore it is non-visual. * @param node the node * @param pin the pin * @return the widget attached to the pin, null, if it is a default pin */ protected Widget attachPinWidget (String node, String pin) { if (pin.endsWith (PIN_ID_DEFAULT_SUFFIX)) return null; CustomPinWidget widget = new CustomPinWidget (this); ((VMDNodeWidget) findWidget (node)).attachPinWidget (widget); widget.getActions ().addAction (createObjectHoverAction ()); widget.getActions ().addAction (createSelectAction ()); return widget; } /** * Implements attaching a widget to an edge. the widget is ConnectionWidget and has object-hover, select and move-control-point actions. * @param edge the edge * @return the widget attached to the edge */ protected Widget attachEdgeWidget (String edge) { VMDConnectionWidget connectionWidget = new VMDConnectionWidget (this, router); connectionLayer.addChild (connectionWidget); connectionWidget.getActions ().addAction (createObjectHoverAction ()); connectionWidget.getActions ().addAction (createSelectAction ()); connectionWidget.getActions ().addAction (moveControlPointAction); return connectionWidget; } /** * Attaches an anchor of a source pin an edge. * The anchor is a ProxyAnchor that switches between the anchor attached to the pin widget directly and * the anchor attached to the pin node widget based on the minimize-state of the node. * @param edge the edge * @param oldSourcePin the old source pin * @param sourcePin the new source pin */ protected void attachEdgeSourceAnchor (String edge, String oldSourcePin, String sourcePin) { ((ConnectionWidget) findWidget (edge)).setSourceAnchor (getPinAnchor (sourcePin)); } /** * Attaches an anchor of a target pin an edge. * The anchor is a ProxyAnchor that switches between the anchor attached to the pin widget directly and * the anchor attached to the pin node widget based on the minimize-state of the node. * @param edge the edge * @param oldTargetPin the old target pin * @param targetPin the new target pin */ protected void attachEdgeTargetAnchor (String edge, String oldTargetPin, String targetPin) { ((ConnectionWidget) findWidget (edge)).setTargetAnchor (getPinAnchor (targetPin)); } private Anchor getPinAnchor (String pin) { if(pin == null) return null; VMDNodeWidget nodeWidget = (VMDNodeWidget) findWidget (getPinNode (pin)); Widget pinMainWidget = findWidget (pin); Anchor anchor; if(nodeWidget == null) return null; if (pinMainWidget != null) { anchor = AnchorFactory.createDirectionalAnchor (pinMainWidget, AnchorFactory.DirectionalAnchorKind.HORIZONTAL, 8); anchor = nodeWidget.createAnchorPin (anchor); } else anchor = nodeWidget.getNodeAnchor (); return anchor; } }
true
0283f5bfb34c000f5ba4b9c019a4f6554ab7e7f6
Java
ticketmaster-api/ticketmaster-api.github.io
/tests/serenity/src/main/java/com/tkmdpa/taf/pages/site/products_and_docs/PD_PublishAPIPage.java
UTF-8
1,978
1.929688
2
[ "MIT" ]
permissive
package com.tkmdpa.taf.pages.site.products_and_docs; import com.tkmdpa.taf.pages.AncestorPage; import net.serenitybdd.core.annotations.findby.FindBy; import net.serenitybdd.core.pages.WebElementFacade; import net.thucydides.core.annotations.DefaultUrl; import java.util.HashMap; import java.util.Map; @DefaultUrl("/products-and-docs/apis/publish/") public class PD_PublishAPIPage extends AncestorPage { public final String pageHeader = "PUBLISH API"; @FindBy(xpath = "//div[@class='article-wrapper' and ./h2[contains(.,'Overview')]]/p[contains(.,'Example:')]/code") private WebElementFacade apikey01PlaceHolder; @FindBy(xpath = "//div[@class='article-wrapper' and ./h2[contains(.,'Publish Events')]]/div/figure/pre/code[@class='language-js']/span[@class='s2' and contains(.,'https://app.ticketmaster.com/publish/v2/events?apikey=')]") private WebElementFacade apikey02PlaceHolder; @FindBy(xpath = "//div[@class='article-wrapper']/div/figure/pre/code[@class='language-http']/span[@class='nn' and contains(.,'/publish/v2/events?apikey=')]") private WebElementFacade apikey03PlaceHolder; @FindBy(xpath = "//div[@class='article-wrapper' and ./h2[contains(.,'Search Events')]]/div/a") private WebElementFacade codeSection; @FindBy(xpath = "//div[@class='article-wrapper' and ./h2[contains(.,'Search Events')]]/div/blockquote/p/a[@href='#curl']") private WebElementFacade switchToCUrlCode; public WebElementFacade getSwitchToCUrlCode() { return switchToCUrlCode; } public WebElementFacade getCodeSection() { return codeSection; } public Map<String,WebElementFacade> getAPIKeyPlaceHoldersList() { Map<String,WebElementFacade> elements = new HashMap<>(); elements.put("apikey01PlaceHolder", apikey01PlaceHolder); elements.put("apikey02PlaceHolder", apikey02PlaceHolder); elements.put("apikey03PlaceHolder", apikey03PlaceHolder); return elements; } }
true
cf1f662e02458f72608bfd7dc10e2902e19b8cdc
Java
Kaabachi/alpano
/src/ch/epfl/alpano/dem/ElevationProfile.java
UTF-8
3,961
2.84375
3
[]
no_license
package ch.epfl.alpano.dem; import ch.epfl.alpano.Distance; import ch.epfl.alpano.GeoPoint; import ch.epfl.alpano.Math2; import ch.epfl.alpano.Azimuth; import ch.epfl.alpano.Preconditions; import ch.epfl.alpano.dem.ContinuousElevationModel; import static java.util.Objects.requireNonNull; /** * * @author Bayrem Kaabachi (261340), Emine Ghariani (262850) * */ public final class ElevationProfile { private final ContinuousElevationModel elevationModel ; private final GeoPoint origin; private final double azimuth; private final double length; private final double[] tabLon ; private final double[] tabLat ; final static double SPACING = 4096; /** * construit un profil altimétrique basé sur le MNT donné et dont le tracé débute au point origin, suit le grand cercle dans la direction donnée par azimuth, et a une longueur de length mètres ; * @param elevationModel MNT continu * @param origin GeoPoint dont le trace debute * @param azimuth Azimuth donnant la direction * @param length Longueur en metres * @throws IllegalArgumentException si l'azimuth n'est pas canonique, ou si la longueur n'est pas strictement positive * @throws NullPointerException si origin ou elevationModel sont nul */ public ElevationProfile(ContinuousElevationModel elevationModel, GeoPoint origin, double azimuth, double length){ Preconditions.checkArgument(Azimuth.isCanonical(azimuth) && length>0); this.elevationModel=requireNonNull(elevationModel); this.origin=requireNonNull(origin); this.azimuth=azimuth; this.length=length; int lengthOfArray=(int)Math.ceil(length/SPACING) +1; tabLon=new double[lengthOfArray]; tabLat=new double[lengthOfArray]; for(int i=0;i<lengthOfArray;i++){ tabLat[i]=Math.asin(Math.sin(this.origin.latitude())* Math.cos(Distance.toRadians(SPACING * i)) + Math.cos(this.origin.latitude()) * Math.sin(Distance.toRadians(SPACING * i)) * Math.cos(Azimuth.toMath(this.azimuth))); tabLon[i]= ((this.origin.longitude() - Math.asin(Math.sin(Azimuth.toMath(this.azimuth)) * Math.sin(Distance.toRadians(SPACING * i)) / Math.cos(tabLat[i])) + Math.PI) % (Math2.PI2)) - Math.PI; } } /** * retourne l'altitude du terrain à la position donnée du profil * @param x Position donne du profil * @throws IllegalArgumentException si la position n'est pas dans les bornes du profil * @return l'altitude du terrain à la position donnée du profil */ public GeoPoint positionAt(double x){ Preconditions.checkArgument(x>=0 && x<=this.length); int id = (int)(x/SPACING) ; double longitude = Math2.lerp(tabLon[id],tabLon[id+1],x/SPACING - id) ; double latitude = Math2.lerp(tabLat[id], tabLat[id+1], (x/SPACING)-id) ; return new GeoPoint(longitude,latitude); } /** * retourne les coordonnées du point à la position donnée du profil * @param x Position donnee du profil * @throws IllegalArgumentException si cette position n'est pas dans les bornes du profil * @return les coordonnées du point à la position donnée du profil */ public double elevationAt(double x){ return this.elevationModel.elevationAt(positionAt(x)); } /** * retourne la pente du terrain à la position donnée du profil * @param x Position donnee du profil * @throws IllegalArgumentException si la position n'est pas dans les bornes du profil. * @return la pente du terrain à la position donnée du profil */ public double slopeAt(double x) { Preconditions.checkArgument(x>=0 && x<=this.length); return this.elevationModel.slopeAt(positionAt(x)); } }
true
010e8e2f15507a8f1dc31d42bb95948212a02413
Java
knara710/miniproject
/Documents/workspace-sts-3.9.4.RELEASE/example2/src/com/knara/dao/DeleteCustomer.java
UTF-8
267
2.046875
2
[]
no_license
package com.knara.dao; import java.util.ArrayList; import com.knara.model.Customer; public class DeleteCustomer { public ArrayList<Customer> deleteCustomerData(ArrayList<Customer> custList, int index) { custList.remove(index); return custList; } }
true
cc80232ad48313d7bc1c52392a696b7860110d9f
Java
juanfcosanz/Java
/Banco/src/com/banco/domain/Cuenta.java
UTF-8
449
2.6875
3
[ "Apache-2.0" ]
permissive
package com.banco.domain; public class Cuenta { private double saldo; public double getSaldo() { return saldo; } public void setSaldo(double saldo) { this.saldo = saldo; } public boolean depositar(double cantidad) { saldo = saldo + cantidad; return true; } public boolean retirar(double cantidad) { boolean result = false; if (cantidad <= saldo) { saldo = saldo - cantidad; result = true; } return result; } }
true
dd9f40273e43885a78da4f115021eb961d84a170
Java
Runnoob-Gallagher/RUNNOOB
/basic-code/RUNOOB/JavaDay03/src/cn/zj/cq/Demo02Calendar.java
UTF-8
503
3.34375
3
[]
no_license
package cn.zj.cq; import java.util.Calendar; import java.util.Date; //Calendar 类是一个抽象类,Calendar 提供了一个类方法 getInstance,以获得此类型的一个通用的对象; public class Demo02Calendar { public static void main(String[] args) { Calendar calA = Calendar.getInstance(); //上面说到获得类的一个对象,那么这个就是一个多态,父类引用指向子类对象; Date ddA = calA.getTime(); System.out.println(ddA); } }
true
9657b0fae66e60befe6fc05a30a2620f23d8f6d1
Java
Team4525/DeepSpace2019RealReal
/DeepSpace2019-master/src/main/java/frc/robot/subsystems/Drive.java
UTF-8
4,885
2.609375
3
[]
no_license
package frc.robot.subsystems; import com.ctre.phoenix.motorcontrol.ControlMode; import com.ctre.phoenix.motorcontrol.FeedbackDevice; import com.ctre.phoenix.motorcontrol.NeutralMode; import com.ctre.phoenix.motorcontrol.can.TalonSRX; import com.ctre.phoenix.motorcontrol.can.VictorSPX; import edu.wpi.first.wpilibj.command.Subsystem; import frc.robot.commands.DriveCommand; public class Drive extends Subsystem { TalonSRX leftTalon = new TalonSRX(1); VictorSPX leftVictor = new VictorSPX(1); TalonSRX rightTalon = new TalonSRX(2); VictorSPX rightVictor = new VictorSPX(2); public Drive() { leftVictor.follow(leftTalon); rightVictor.follow(rightTalon); /* Factory Default all hardware to prevent unexpected behaviour */ leftTalon.configFactoryDefault(); /* Config sensor used for Primary PID [Velocity] */ leftTalon.configSelectedFeedbackSensor(FeedbackDevice.CTRE_MagEncoder_Relative, Constants.kPIDLoopIdx, Constants.kTimeoutMs); leftTalon.setSensorPhase(true); /* Config the peak and nominal outputs */ leftTalon.configNominalOutputForward(0, Constants.kTimeoutMs); leftTalon.configNominalOutputReverse(0, Constants.kTimeoutMs); leftTalon.configPeakOutputForward(1, Constants.kTimeoutMs); leftTalon.configPeakOutputReverse(-1, Constants.kTimeoutMs); /* Config the Velocity closed loop gains in slot0 */ leftTalon.config_kF(Constants.kPIDLoopIdx, Constants.kGains_Velocit.kF, Constants.kTimeoutMs); leftTalon.config_kP(Constants.kPIDLoopIdx, Constants.kGains_Velocit.kP, Constants.kTimeoutMs); leftTalon.config_kI(Constants.kPIDLoopIdx, Constants.kGains_Velocit.kI, Constants.kTimeoutMs); leftTalon.config_kD(Constants.kPIDLoopIdx, Constants.kGains_Velocit.kD, Constants.kTimeoutMs); rightTalon.configFactoryDefault(); /* Config sensor used for Primary PID [Velocity] */ rightTalon.configSelectedFeedbackSensor(FeedbackDevice.CTRE_MagEncoder_Relative, Constants.kPIDLoopIdx, Constants.kTimeoutMs); /** * Phase sensor accordingly. Positive Sensor Reading should match Green * (blinking) Leds on Talon */ rightTalon.setSensorPhase(true); /* Config the peak and nominal outputs */ rightTalon.configNominalOutputForward(0, Constants.kTimeoutMs); rightTalon.configNominalOutputReverse(0, Constants.kTimeoutMs); rightTalon.configPeakOutputForward(1, Constants.kTimeoutMs); rightTalon.configPeakOutputReverse(-1, Constants.kTimeoutMs); /* Config the Velocity closed loop gains in slot0 */ rightTalon.config_kF(Constants.kPIDLoopIdx, Constants.kGains_Velocit.kF, Constants.kTimeoutMs); rightTalon.config_kP(Constants.kPIDLoopIdx, Constants.kGains_Velocit.kP, Constants.kTimeoutMs); rightTalon.config_kI(Constants.kPIDLoopIdx, Constants.kGains_Velocit.kI, Constants.kTimeoutMs); rightTalon.config_kD(Constants.kPIDLoopIdx, Constants.kGains_Velocit.kD, Constants.kTimeoutMs); leftTalon.setNeutralMode(NeutralMode.Brake); rightTalon.setNeutralMode(NeutralMode.Brake); } public void drive(double targetVelocity, double targetOffset) { /* Velocity Closed Loop */ /** * Convert 500 RPM to units / 100ms. 4096 Units/Rev * 500 RPM / 600 100ms/min in * either direction: velocity setpoint is in units/100ms */ double targetVelocity_UnitsPer100ms = targetVelocity; double TargetTurnVelocity = targetOffset; double maxInput = Math.copySign(Math.max(Math.abs(targetVelocity_UnitsPer100ms), Math.abs(TargetTurnVelocity)),targetVelocity_UnitsPer100ms); if (targetVelocity_UnitsPer100ms >= 0.0) { if (TargetTurnVelocity >= 0.0) { leftTalon.set(ControlMode.Velocity, maxInput); rightTalon.set(ControlMode.Velocity, -(targetVelocity_UnitsPer100ms - TargetTurnVelocity)); } else { leftTalon.set(ControlMode.Velocity, targetVelocity_UnitsPer100ms + TargetTurnVelocity); rightTalon.set(ControlMode.Velocity, -maxInput); } } else { if (TargetTurnVelocity >= 0.0) { leftTalon.set(ControlMode.Velocity, targetVelocity_UnitsPer100ms + TargetTurnVelocity); rightTalon.set(ControlMode.Velocity, -maxInput); } else { leftTalon.set(ControlMode.Velocity, maxInput); rightTalon.set(ControlMode.Velocity, -(targetVelocity_UnitsPer100ms - TargetTurnVelocity)); } } } public void initDefaultCommand() { setDefaultCommand(new DriveCommand()); } }
true
9e8b436ebdfac6733add33e2bbd3366c411f9ba4
Java
MJCoderMJCoder/ApplianceAfter-salesServiceSystem
/app/src/main/java/com/lzf/applianceafter_salesservicesystem/bean/Maintenance.java
UTF-8
4,481
2.390625
2
[]
no_license
package com.lzf.applianceafter_salesservicesystem.bean; import java.io.Serializable; /** * CREATE TABLE `maintenance` ( * `maintenance_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '维修申请ID', * `maintenance_name` varchar(45) NOT NULL COMMENT '维修申请名称', * `maintenance_address` varchar(200) NOT NULL COMMENT '维修申请地址', * `maintenance_appliance` varchar(200) NOT NULL COMMENT '维修申请的家电信息', * `maintenance_user` int(11) NOT NULL COMMENT '维修申请的发起用户ID', * `maintenance_status` int(2) NOT NULL COMMENT '0-未接取【用户】/可接取【维修工】\\\\n1-已接取【用户】/未完成【维修工】\\\\n3-已取消\\\\n4-已完成\\\\n', * `maintenance_maintainer` int(11) DEFAULT NULL COMMENT '接取维修申请的维修工ID', * PRIMARY KEY (`maintenance_id`), * UNIQUE KEY `maintenance_request_id_UNIQUE` (`maintenance_id`), * KEY `maintenance_user_idx` (`maintenance_user`), * KEY `maintenance_maintainer_foreign_idx` (`maintenance_maintainer`), * CONSTRAINT `maintenance_maintainer_foreign` FOREIGN KEY (`maintenance_maintainer`) REFERENCES `maintainer` (`maintainer_id`) ON DELETE NO ACTION ON UPDATE NO ACTION, * CONSTRAINT `maintenance_user_foreign` FOREIGN KEY (`maintenance_user`) REFERENCES `user` (`user_id`) ON DELETE NO ACTION ON UPDATE NO ACTION * ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COMMENT='维修申请表' */ public class Maintenance implements Serializable { private static final long serialVersionUID = -3650413031748859924L; private int maintenance_id; private String maintenance_name; private String maintenance_address; private String maintenance_appliance; private int maintenance_user; private int maintenance_status; private int maintenance_maintainer; public Maintenance() { } public Maintenance(int maintenance_id, String maintenance_name, String maintenance_address, String maintenance_appliance, int maintenance_user, int maintenance_status, int maintenance_maintainer) { this.maintenance_id = maintenance_id; this.maintenance_name = maintenance_name; this.maintenance_address = maintenance_address; this.maintenance_appliance = maintenance_appliance; this.maintenance_user = maintenance_user; this.maintenance_status = maintenance_status; this.maintenance_maintainer = maintenance_maintainer; } public int getMaintenance_id() { return maintenance_id; } public void setMaintenance_id(int maintenance_id) { this.maintenance_id = maintenance_id; } public String getMaintenance_name() { return maintenance_name; } public void setMaintenance_name(String maintenance_name) { this.maintenance_name = maintenance_name; } public String getMaintenance_address() { return maintenance_address; } public void setMaintenance_address(String maintenance_address) { this.maintenance_address = maintenance_address; } public String getMaintenance_appliance() { return maintenance_appliance; } public void setMaintenance_appliance(String maintenance_appliance) { this.maintenance_appliance = maintenance_appliance; } public int getMaintenance_user() { return maintenance_user; } public void setMaintenance_user(int maintenance_user) { this.maintenance_user = maintenance_user; } public int getMaintenance_status() { return maintenance_status; } public void setMaintenance_status(int maintenance_status) { this.maintenance_status = maintenance_status; } public int getMaintenance_maintainer() { return maintenance_maintainer; } public void setMaintenance_maintainer(int maintenance_maintainer) { this.maintenance_maintainer = maintenance_maintainer; } @Override public String toString() { return "Maintenance{" + "maintenance_id=" + maintenance_id + ", maintenance_name='" + maintenance_name + '\'' + ", maintenance_address='" + maintenance_address + '\'' + ", maintenance_appliance='" + maintenance_appliance + '\'' + ", maintenance_user=" + maintenance_user + ", maintenance_status=" + maintenance_status + ", maintenance_maintainer=" + maintenance_maintainer + '}'; } }
true