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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
dc56592b18b52236d9551cbb7cf8ec3b3e92c1c1 | Java | yusrianp/Mini-Project-Java | /med_id/src/main/java/com/example/med_id/model/Biodata.java | UTF-8 | 1,286 | 2.34375 | 2 | [] | no_license | package com.example.med_id.model;
import javax.persistence.*;
import java.sql.Blob;
@Entity
@Table(name = "m_biodata")
public class Biodata extends CommonEntity{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Long Id;
@Column(name = "fullname")
private String Fullname;
@Column(name = "mobile_phone", length = 15, nullable = true)
private String MobilePhone;
@Lob
@Column(name = "image")
private Blob Image;
@Column(name = "image_path")
private String ImagePath;
public Long getId() {
return Id;
}
public void setId(Long id) {
Id = id;
}
public String getFullname() {
return Fullname;
}
public void setFullname(String fullname) {
Fullname = fullname;
}
public String getMobilePhone() {
return MobilePhone;
}
public void setMobilePhone(String mobilePhone) {
MobilePhone = mobilePhone;
}
public Blob getImage() {
return Image;
}
public void setImage(Blob image) {
Image = image;
}
public String getImagePath() {
return ImagePath;
}
public void setImagePath(String imagePath) {
ImagePath = imagePath;
}
}
| true |
7387b3294a19dc3416c75c9583e9f768f8459247 | Java | S3FA/super-street-fire | /ssf-java/GameModel/src/main/java/ca/site3/ssf/gamemodel/PlayerBlockActionEvent.java | UTF-8 | 701 | 2.703125 | 3 | [] | no_license | package ca.site3.ssf.gamemodel;
@SuppressWarnings("serial")
public final class PlayerBlockActionEvent implements IGameModelEvent {
final private int playerNum; // The number of the player who is blocking
final private boolean blockWasEffective; // Whether the block was effective at actually blocking an incoming attack
public PlayerBlockActionEvent(int playerNum, boolean blockWasEffective) {
super();
this.playerNum = playerNum;
this.blockWasEffective = blockWasEffective;
}
public int getPlayerNum() {
return this.playerNum;
}
public boolean getBlockWasEffective() {
return this.blockWasEffective;
}
public Type getType() {
return Type.PLAYER_BLOCK_ACTION;
}
}
| true |
52c32722091bfa78ea1398b9cb1392200f8be909 | Java | dhvines/complexity-calculator-service | /ComplexityCalculatorService/src/main/java/com/ibm/migr/inventory/model/Archives.java | UTF-8 | 1,036 | 1.914063 | 2 | [] | no_license |
package com.ibm.migr.inventory.model;
public class Archives {
private int ears;
private int wars;
private int rars;
private int ejbs;
private int utilityJars;
private int appClients;
public int getEars() {
return ears;
}
public void setEars(int ears) {
this.ears = ears;
}
public int getWars() {
return wars;
}
public void setWars(int wars) {
this.wars = wars;
}
public int getRars() {
return rars;
}
public void setRars(int rars) {
this.rars = rars;
}
public int getEjbs() {
return ejbs;
}
public void setEjbs(int ejbs) {
this.ejbs = ejbs;
}
public int getUtilityJars() {
return utilityJars;
}
public void setUtilityJars(int utilityJars) {
this.utilityJars = utilityJars;
}
public int getAppClients() {
return appClients;
}
public void setAppClients(int appClients) {
this.appClients = appClients;
}
}
| true |
4f097e766285c383a3803b44070df09f94305d72 | Java | AustereTony-MCMods/Oxygen-Core | /src/main/java/austeretony/oxygen_core/client/gui/menu/NotificationsMenuEntry.java | UTF-8 | 992 | 2.015625 | 2 | [] | no_license | package austeretony.oxygen_core.client.gui.menu;
import austeretony.oxygen_core.client.OxygenGUIManager;
import austeretony.oxygen_core.client.api.ClientReference;
import austeretony.oxygen_core.client.settings.EnumCoreClientSetting;
import austeretony.oxygen_core.common.config.OxygenConfig;
import austeretony.oxygen_core.common.main.OxygenMain;
public class NotificationsMenuEntry implements OxygenMenuEntry {
@Override
public int getId() {
return OxygenMain.NOTIFICATIONS_SCREEN_ID;
}
@Override
public String getLocalizedName() {
return ClientReference.localize("oxygen_core.gui.notifications.title");
}
@Override
public int getKeyCode() {
return OxygenConfig.NOTIFICATIONS_MENU_KEY.asInt();
}
@Override
public boolean isValid() {
return EnumCoreClientSetting.ADD_NOTIFICATIONS_MENU.get().asBoolean();
}
@Override
public void open() {
OxygenGUIManager.openNotificationsMenu();
}
}
| true |
43fcc1e8d7873274b9b55a3eb8b705e1e00fec6a | Java | apache/iotdb | /iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/udf/utils/UDFDataTypeTransformer.java | UTF-8 | 2,501 | 2.140625 | 2 | [
"Apache-2.0",
"BSD-3-Clause",
"EPL-1.0",
"CDDL-1.1",
"MIT",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.iotdb.commons.udf.utils;
import org.apache.iotdb.tsfile.file.metadata.enums.TSDataType;
import org.apache.iotdb.udf.api.type.Type;
import java.util.List;
import java.util.stream.Collectors;
/**
* Transform between {@link org.apache.iotdb.tsfile.file.metadata.enums.TSDataType} and {@link
* org.apache.iotdb.udf.api.type.Type}
*/
public class UDFDataTypeTransformer {
private UDFDataTypeTransformer() {}
public static TSDataType transformToTsDataType(Type type) {
return type == null ? null : TSDataType.getTsDataType(type.getType());
}
public static List<TSDataType> transformToTsDataTypeList(List<Type> typeList) {
return typeList == null
? null
: typeList.stream()
.map(UDFDataTypeTransformer::transformToTsDataType)
.collect(Collectors.toList());
}
public static Type transformToUDFDataType(TSDataType tsDataType) {
return tsDataType == null ? null : getUDFDataType(tsDataType.getType());
}
public static List<Type> transformToUDFDataTypeList(List<TSDataType> tsDataTypeList) {
return tsDataTypeList == null
? null
: tsDataTypeList.stream()
.map(UDFDataTypeTransformer::transformToUDFDataType)
.collect(Collectors.toList());
}
private static Type getUDFDataType(byte type) {
switch (type) {
case 0:
return Type.BOOLEAN;
case 1:
return Type.INT32;
case 2:
return Type.INT64;
case 3:
return Type.FLOAT;
case 4:
return Type.DOUBLE;
case 5:
return Type.TEXT;
default:
throw new IllegalArgumentException("Invalid input: " + type);
}
}
}
| true |
f16a4156b863bc60d8d1086f8b9e88a9c493645e | Java | rajeev66053/java_tutorial | /bucky/src/Collection/index.java | UTF-8 | 1,001 | 3.28125 | 3 | [] | no_license | package Collection;
import java.util.*;
public class index {
public static void main(String[] args) {
String[] things= {"eggs","lasers","hats","pie"};
List<String> list1=new ArrayList<String>();
//add array items to list
for(String x:things) {
list1.add(x);
}
String[] morethings= {"lasers","hats"};
List<String> list2=new ArrayList<String>();
//add array items to list
for(String y:morethings) {
list2.add(y);
}
for(int i=0;i<list1.size();i++) {
System.out.printf("%s ", list1.get(i));
}
System.out.println();
for(int i=0;i<list2.size();i++) {
System.out.printf("%s ", list2.get(i));
}
editlist(list1,list2);
System.out.println();
for(int i=0;i<list1.size();i++) {
System.out.printf("%s ", list1.get(i));
}
}
public static void editlist(Collection<String> l1,Collection<String> l2) {
Iterator<String> it =l1.iterator();
while(it.hasNext()) {
if(l2.contains(it.next())) {
it.remove();
}
}
}
}
| true |
41d28b93180d157c6e23b1e33ef24f62712a0f38 | Java | NieMinxin/BasicJava | /src/com/ellen/c2/MainTest.java | UTF-8 | 218 | 2.015625 | 2 | [] | no_license | package com.ellen.c2;
public class MainTest {
public static void main(String[] args) {
Animal animal = new Animal() {
@Override
public void f1() {
}
};
}
}
| true |
ea7b1ae76d5652ac1ef830609bb85d63ba688ce3 | Java | TheShed412/SquareAnadTriangle | /SquareAndTriangle.java | UTF-8 | 630 | 3.421875 | 3 | [] | no_license | class SquareAndTriangle
{
public static void main(String[] args)
{
int both = 0;
int n = 2;
boolean foundOne;
System.out.println("Well 0 and 1 are obvious answers! But hopefully there are more...");
while(true){
for(int m=n; m<=(n*n); m++){
foundOne = (n*n == (m*(m+1))/2);
if (foundOne){
System.out.println("Matt, "+(n*n)+" is one!");
System.out.println("m: "+m);
System.out.println("n: "+n);
both++;
System.out.println("Place: "+both);
}//if
}//for
n++;
}//while
}//main
}//class
| true |
256396420ab05015cb3ddce412fdf478c7aa7a2b | Java | motoloto/Foodme | /WEB-INF/classes/com/cop/model/CopDAO.java | UTF-8 | 20,409 | 2.359375 | 2 | [] | no_license | package com.cop.model;
import java.util.*;
import java.sql.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import com.odr.model.jdbcUtil_CompositeQuery_OneCopByOdr;
public class CopDAO implements CopDAO_interface {
private static DataSource ds = null;
static {
try {
Context ctx = new InitialContext();
ds = (DataSource) ctx.lookup("java:comp/env/jdbc/TestDB2");
} catch (NamingException e) {
e.printStackTrace();
}
}
private static final String INSERT_STMT =
"INSERT INTO COUPON (COP_NO,REST_NO,COP_NAME,COP_CONTENT,COP_ORLPRICE,COP_PRICE,COP_DL,COP_STATE,COP_DATE,COP_CIRCU,COP_SELAMT) VALUES (sequence_COP_NO.NEXTVAL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
private static final String GET_ALL_STMT =
"SELECT COP_NO,REST_NO,COP_NAME, COP_CONTENT,COP_ORLPRICE,COP_PRICE,COP_DL,COP_STATE,COP_DATE,COP_CIRCU,COP_SELAMT FROM COUPON order by COP_NO";
private static final String GET_ONE_STMT =
"SELECT COP_NO,REST_NO,COP_NAME, COP_CONTENT,COP_ORLPRICE,COP_PRICE,COP_DL,COP_STATE,COP_DATE,COP_CIRCU,COP_SELAMT FROM COUPON where COP_NO = ?";
private static final String GET_COP_BY_REST_NO =
"SELECT COP_NO,REST_NO,COP_NAME, COP_CONTENT,COP_ORLPRICE,COP_PRICE,COP_DL,COP_STATE,COP_DATE,COP_CIRCU,COP_SELAMT FROM COUPON where REST_NO = ? AND COP_STATE='1'";
private static final String GetCopByRest_no =
"SELECT COP_NO,REST_NO,COP_NAME, COP_CONTENT,COP_ORLPRICE,COP_PRICE,COP_DL,COP_STATE,COP_DATE,COP_CIRCU,COP_SELAMT FROM COUPON where REST_NO = ?";
private static final String DELETE =
"DELETE FROM COUPON where COP_NO = ?";
private static final String UPDATE =
"UPDATE COUPON set REST_NO=?, COP_NAME=?, COP_CONTENT=?, COP_ORLPRICE=?, COP_PRICE=?,COP_DL=?,COP_STATE=?,COP_DATE=?,COP_CIRCU=?,COP_SELAMT=? where COP_NO = ?";
private static final String GET_HOTSALE_COP =
"select * from coupon,(select max(cop_selamt) as max_selamt from coupon) where cop_selamt = max_selamt and cop_state='1'" ;
private static final String GET_Latest_COP =
"select * from coupon,(select max(cop_date) as max_date from coupon) where cop_date = max_date and cop_state='1'";
@Override
public CopVO findHotSaleCop( ) {
CopVO CopVo = null;
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = ds.getConnection();
pstmt = con.prepareStatement(GET_HOTSALE_COP);
rs = pstmt.executeQuery();
while (rs.next()) {
// CopVo �]�٬� Domain objects
CopVo = new CopVO();
CopVo.setCop_no(rs.getInt("COP_NO"));
CopVo.setRest_no(rs.getInt("REST_NO"));
CopVo.setCop_name(rs.getString("COP_NAME"));
CopVo.setCop_content(rs.getString("COP_CONTENT"));
CopVo.setCop_orlprice(rs.getInt("COP_ORLPRICE"));
CopVo.setCop_price(rs.getInt("COP_PRICE"));
CopVo.setCop_dl(rs.getDate("COP_DL"));
CopVo.setCop_state(rs.getString("COP_STATE"));
CopVo.setCop_date(rs.getDate("COP_DATE"));
CopVo.setCop_circu(rs.getInt("COP_CIRCU"));
CopVo.setCop_selamt(rs.getInt("COP_SELAMT"));
}
} catch (SQLException se) {
throw new RuntimeException("A database error occured. "
+ se.getMessage());
// Clean up JDBC resources
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException se) {
se.printStackTrace(System.err);
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException se) {
se.printStackTrace(System.err);
}
}
if (con != null) {
try {
con.close();
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
return CopVo;
}
@Override
public CopVO findLatestCop( ) {
CopVO CopVo = null;
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = ds.getConnection();
pstmt = con.prepareStatement(GET_Latest_COP);
rs = pstmt.executeQuery();
while (rs.next()) {
// CopVo �]�٬� Domain objects
CopVo = new CopVO();
CopVo.setCop_no(rs.getInt("COP_NO"));
CopVo.setRest_no(rs.getInt("REST_NO"));
CopVo.setCop_name(rs.getString("COP_NAME"));
CopVo.setCop_content(rs.getString("COP_CONTENT"));
CopVo.setCop_orlprice(rs.getInt("COP_ORLPRICE"));
CopVo.setCop_price(rs.getInt("COP_PRICE"));
CopVo.setCop_dl(rs.getDate("COP_DL"));
CopVo.setCop_state(rs.getString("COP_STATE"));
CopVo.setCop_date(rs.getDate("COP_DATE"));
CopVo.setCop_circu(rs.getInt("COP_CIRCU"));
CopVo.setCop_selamt(rs.getInt("COP_SELAMT"));
}
} catch (SQLException se) {
throw new RuntimeException("A database error occured. "
+ se.getMessage());
// Clean up JDBC resources
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException se) {
se.printStackTrace(System.err);
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException se) {
se.printStackTrace(System.err);
}
}
if (con != null) {
try {
con.close();
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
return CopVo;
}
@Override
public int insert(CopVO copVo) {
int updateCount = 0;
Connection con = null;
PreparedStatement pstmt = null;
try {
con = ds.getConnection();
pstmt = con.prepareStatement(INSERT_STMT);
pstmt.setInt(1, copVo.getRest_no());
pstmt.setString(2, copVo.getCop_name());
pstmt.setString(3, copVo.getCop_content());
pstmt.setInt(4, copVo.getCop_orlprice());
pstmt.setInt(5, copVo.getCop_price());
pstmt.setDate(6, copVo.getCop_dl());
pstmt.setString(7, copVo.getCop_state());
pstmt.setDate(8, copVo.getCop_date());
pstmt.setInt(9, copVo.getCop_circu());
pstmt.setInt(10, copVo.getCop_selamt());
updateCount = pstmt.executeUpdate();
} catch (SQLException se) {
throw new RuntimeException("A database error occured. "
+ se.getMessage());
// Clean up JDBC resources
} finally {
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException se) {
se.printStackTrace(System.err);
}
}
if (con != null) {
try {
con.close();
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
return updateCount;
}
@Override
public int update(CopVO copVo) {
int updateCount = 0;
Connection con = null;
PreparedStatement pstmt = null;
try {
con = ds.getConnection();
pstmt = con.prepareStatement(UPDATE);
pstmt.setInt(1, copVo.getRest_no());
pstmt.setString(2, copVo.getCop_name());
pstmt.setString(3, copVo.getCop_content());
pstmt.setInt(4, copVo.getCop_orlprice());
pstmt.setInt(5, copVo.getCop_price());
pstmt.setDate(6, copVo.getCop_dl());
pstmt.setString(7, copVo.getCop_state());
pstmt.setDate(8, copVo.getCop_date());
pstmt.setInt(9, copVo.getCop_circu());
pstmt.setInt(10, copVo.getCop_selamt());
pstmt.setInt(11, copVo.getCop_no());
updateCount = pstmt.executeUpdate();
} catch (SQLException se) {
throw new RuntimeException("A database error occured. "
+ se.getMessage());
// Clean up JDBC resources
} finally {
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException se) {
se.printStackTrace(System.err);
}
}
if (con != null) {
try {
con.close();
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
return updateCount;
}
@Override
public int delete(Integer cop_no) {
int updateCount = 0;
Connection con = null;
PreparedStatement pstmt = null;
try {
con = ds.getConnection();
pstmt = con.prepareStatement(DELETE);
pstmt.setInt(1, cop_no);
updateCount = pstmt.executeUpdate();
} catch (SQLException se) {
throw new RuntimeException("A database error occured. "
+ se.getMessage());
// Clean up JDBC resources
} finally {
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException se) {
se.printStackTrace(System.err);
}
}
if (con != null) {
try {
con.close();
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
return updateCount;
}
@Override
public CopVO findByPrimaryKey(Integer cop_no) {
CopVO CopVo = null;
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = ds.getConnection();
pstmt = con.prepareStatement(GET_ONE_STMT);
pstmt.setInt(1, cop_no);
rs = pstmt.executeQuery();
while (rs.next()) {
// CopVo �]�٬� Domain objects
CopVo = new CopVO();
CopVo.setCop_no(rs.getInt("COP_NO"));
CopVo.setRest_no(rs.getInt("REST_NO"));
CopVo.setCop_name(rs.getString("COP_NAME"));
CopVo.setCop_content(rs.getString("COP_CONTENT"));
CopVo.setCop_orlprice(rs.getInt("COP_ORLPRICE"));
CopVo.setCop_price(rs.getInt("COP_PRICE"));
CopVo.setCop_dl(rs.getDate("COP_DL"));
CopVo.setCop_state(rs.getString("COP_STATE"));
CopVo.setCop_date(rs.getDate("COP_DATE"));
CopVo.setCop_circu(rs.getInt("COP_CIRCU"));
CopVo.setCop_selamt(rs.getInt("COP_SELAMT"));
}
} catch (SQLException se) {
throw new RuntimeException("A database error occured. "
+ se.getMessage());
// Clean up JDBC resources
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException se) {
se.printStackTrace(System.err);
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException se) {
se.printStackTrace(System.err);
}
}
if (con != null) {
try {
con.close();
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
return CopVo;
}
@Override
public CopVO findCopByRest_no(Integer rest_no) {
CopVO CopVo = null;
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = ds.getConnection();
pstmt = con.prepareStatement(GET_COP_BY_REST_NO);
pstmt.setInt(1, rest_no);
rs = pstmt.executeQuery();
while (rs.next()) {
// CopVo �]�٬� Domain objects
CopVo = new CopVO();
CopVo.setCop_no(rs.getInt("COP_NO"));
CopVo.setRest_no(rs.getInt("REST_NO"));
CopVo.setCop_name(rs.getString("COP_NAME"));
CopVo.setCop_content(rs.getString("COP_CONTENT"));
CopVo.setCop_orlprice(rs.getInt("COP_ORLPRICE"));
CopVo.setCop_price(rs.getInt("COP_PRICE"));
CopVo.setCop_dl(rs.getDate("COP_DL"));
CopVo.setCop_state(rs.getString("COP_STATE"));
CopVo.setCop_date(rs.getDate("COP_DATE"));
CopVo.setCop_circu(rs.getInt("COP_CIRCU"));
CopVo.setCop_selamt(rs.getInt("COP_SELAMT"));
}
} catch (SQLException se) {
throw new RuntimeException("A database error occured. "
+ se.getMessage());
// Clean up JDBC resources
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException se) {
se.printStackTrace(System.err);
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException se) {
se.printStackTrace(System.err);
}
}
if (con != null) {
try {
con.close();
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
return CopVo;
}
@Override
public List<CopVO> getAll() {
List<CopVO> list = new ArrayList<CopVO>();
CopVO CopVo = null;
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = ds.getConnection();
pstmt = con.prepareStatement(GET_ALL_STMT);
rs = pstmt.executeQuery();
while (rs.next()) {
// CopVo �]�٬� Domain objects
CopVo = new CopVO();
CopVo.setCop_no(rs.getInt("COP_NO"));
CopVo.setRest_no(rs.getInt("REST_NO"));
CopVo.setCop_name(rs.getString("COP_NAME"));
CopVo.setCop_content(rs.getString("COP_CONTENT"));
CopVo.setCop_orlprice(rs.getInt("COP_ORLPRICE"));
CopVo.setCop_price(rs.getInt("COP_PRICE"));
CopVo.setCop_dl(rs.getDate("COP_DL"));
CopVo.setCop_state(rs.getString("COP_STATE"));
CopVo.setCop_date(rs.getDate("COP_DATE"));
CopVo.setCop_circu(rs.getInt("COP_CIRCU"));
CopVo.setCop_selamt(rs.getInt("COP_SELAMT"));
list.add(CopVo); // Store the row in the vector
}
} catch (SQLException se) {
throw new RuntimeException("A database error occured. "
+ se.getMessage());
// Clean up JDBC resources
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException se) {
se.printStackTrace(System.err);
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException se) {
se.printStackTrace(System.err);
}
}
if (con != null) {
try {
con.close();
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
return list;
}
//廠商結款用:用餐廳編號找到他發行的餐劵
@Override
public List<CopVO> getCopByRest_no(Integer rest_no) {
List<CopVO> list = new ArrayList<CopVO>();
CopVO CopVo = null;
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = ds.getConnection();
pstmt = con.prepareStatement(GetCopByRest_no);
pstmt.setInt(1, rest_no);
rs = pstmt.executeQuery();
while (rs.next()) {
// CopVo �]�٬� Domain objects
CopVo = new CopVO();
CopVo.setCop_no(rs.getInt("COP_NO"));
CopVo.setRest_no(rs.getInt("REST_NO"));
CopVo.setCop_name(rs.getString("COP_NAME"));
CopVo.setCop_content(rs.getString("COP_CONTENT"));
CopVo.setCop_orlprice(rs.getInt("COP_ORLPRICE"));
CopVo.setCop_price(rs.getInt("COP_PRICE"));
CopVo.setCop_dl(rs.getDate("COP_DL"));
CopVo.setCop_state(rs.getString("COP_STATE"));
CopVo.setCop_date(rs.getDate("COP_DATE"));
CopVo.setCop_circu(rs.getInt("COP_CIRCU"));
CopVo.setCop_selamt(rs.getInt("COP_SELAMT"));
list.add(CopVo); // Store the row in the vector
}
} catch (SQLException se) {
throw new RuntimeException("A database error occured. "
+ se.getMessage());
// Clean up JDBC resources
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException se) {
se.printStackTrace(System.err);
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException se) {
se.printStackTrace(System.err);
}
}
if (con != null) {
try {
con.close();
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
return list;
}
@Override
public List<CopVO> getAll(Map<String, String[]> map) {
List<CopVO> list = new ArrayList<CopVO>();
CopVO CopVo = null;
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = ds.getConnection();
String finalSQL = "select * from COUPON "
+ jdbcUtil_CompositeQuery_Cop.get_WhereCondition(map)
+ "order by cop_no";
pstmt = con.prepareStatement(finalSQL);
rs = pstmt.executeQuery();
System.out.println("●●finalSQL(by DAO) = "+finalSQL);
System.out.println("wherecondition: "+jdbcUtil_CompositeQuery_Cop.get_WhereCondition(map));
while (rs.next()) {
// CopVo �]�٬� Domain objects
CopVo = new CopVO();
CopVo.setCop_no(rs.getInt("COP_NO"));
CopVo.setRest_no(rs.getInt("REST_NO"));
CopVo.setCop_name(rs.getString("COP_NAME"));
CopVo.setCop_content(rs.getString("COP_CONTENT"));
CopVo.setCop_orlprice(rs.getInt("COP_ORLPRICE"));
CopVo.setCop_price(rs.getInt("COP_PRICE"));
CopVo.setCop_dl(rs.getDate("COP_DL"));
CopVo.setCop_state(rs.getString("COP_STATE"));
CopVo.setCop_date(rs.getDate("COP_DATE"));
CopVo.setCop_circu(rs.getInt("COP_CIRCU"));
CopVo.setCop_selamt(rs.getInt("COP_SELAMT"));
list.add(CopVo); // Store the row in the vector
}
} catch (SQLException se) {
throw new RuntimeException("A database error occured. "
+ se.getMessage());
// Clean up JDBC resources
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException se) {
se.printStackTrace(System.err);
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException se) {
se.printStackTrace(System.err);
}
}
if (con != null) {
try {
con.close();
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
return list;
}
@Override
public CopVO getOneCopByOdr(Map<String, String[]> map) {
CopVO CopVo = null;
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = ds.getConnection();
pstmt = con.prepareStatement(GET_ALL_STMT);
rs = pstmt.executeQuery();
System.out.println(GET_ALL_STMT);
String finalSQL = "select * from COUPON "
+ jdbcUtil_CompositeQuery_OneCopByOdr.get_WhereCondition(map)
+ "order by cop_no";
pstmt = con.prepareStatement(finalSQL);
rs = pstmt.executeQuery();
System.out.println("●●finalSQL(by DAO) = "+finalSQL);
while (rs.next()) {
// CopVo �]�٬� Domain objects
CopVo = new CopVO();
CopVo.setCop_no(rs.getInt("COP_NO"));
CopVo.setRest_no(rs.getInt("REST_NO"));
CopVo.setCop_name(rs.getString("COP_NAME"));
CopVo.setCop_content(rs.getString("COP_CONTENT"));
CopVo.setCop_orlprice(rs.getInt("COP_ORLPRICE"));
CopVo.setCop_price(rs.getInt("COP_PRICE"));
CopVo.setCop_dl(rs.getDate("COP_DL"));
CopVo.setCop_state(rs.getString("COP_STATE"));
CopVo.setCop_date(rs.getDate("COP_DATE"));
CopVo.setCop_circu(rs.getInt("COP_CIRCU"));
CopVo.setCop_selamt(rs.getInt("COP_SELAMT"));
}
} catch (SQLException se) {
throw new RuntimeException("A database error occured. "
+ se.getMessage());
// Clean up JDBC resources
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException se) {
se.printStackTrace(System.err);
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException se) {
se.printStackTrace(System.err);
}
}
if (con != null) {
try {
con.close();
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
return CopVo;
}
// public static void main(String[] args) {
//
// CopJDBCDAO dao = new CopJDBCDAO();
//
// //�s�W
// CopVO copVo1 = new CopVO();
// copVo1.setRest_no(7002);
// copVo1.setCop_name("test1");
// copVo1.setCop_content("2005-01-01");
// copVo1.setCop_orlprice(600);
// copVo1.setCop_price(480);
// copVo1.setCop_dl(java.sql.Date.valueOf("2005-01-01"));
// copVo1.setCop_state("0");
// copVo1.setCop_date(java.sql.Date.valueOf("2005-01-01"));
// copVo1.setCop_circu(800);
// copVo1.setCop_selamt(0);
// int updateCount_insert = dao.insert(copVo1);
// System.out.println(updateCount_insert);
//
//
//// �ק�
// CopVO copVo2 = new CopVO();
// copVo2.setCop_no(30007);
// copVo2.setRest_no(7002);
// copVo2.setCop_name("COUPON2");
// copVo2.setCop_content("2002-01-01");
// copVo2.setCop_orlprice(2000);
// copVo2.setCop_price(1200);
// copVo2.setCop_dl(java.sql.Date.valueOf("2005-01-01"));
// copVo2.setCop_state("1");
// copVo2.setCop_date(java.sql.Date.valueOf("2005-01-01"));
// copVo2.setCop_circu(800);
// copVo2.setCop_selamt(10);
// int updateCount_update = dao.update(copVo2);
// System.out.println(updateCount_update);
//
//
//// �R��
// int updateCount_delete = dao.delete(30008);
// System.out.println(updateCount_delete);
//
//// �d��
// CopVO copVo3 = dao.findByPrimaryKey(30010);
// System.out.print(copVo3.getCop_no() + ",");
// System.out.print(copVo3.getRest_no() + ",");
// System.out.print(copVo3.getCop_name() + ",");
// System.out.print(copVo3.getCop_content() + ",");
// System.out.print(copVo3.getCop_orlprice() + ",");
// System.out.println(copVo3.getCop_price() + ",");
// System.out.println("---------------------");
////
//// // �d��
// List<CopVO> list = dao.getAll();
// for (CopVO aEmp : list) {
// System.out.print(aEmp.getCop_no() + ",");
// System.out.print(aEmp.getRest_no() + ",");
// System.out.print(aEmp.getCop_name() + ",");
// System.out.print(aEmp.getCop_content() + ",");
// System.out.print(aEmp.getCop_orlprice() + ",");
// System.out.print(aEmp.getCop_price() + ",");
//
// System.out.println();
// System.out.println("---------------------");
// }
// }
}
| true |
41a4a45ef409569da088ecc480e519285eecb1c0 | Java | okokokok123/ssm- | /springCode/spring01/src/IOC的特点/IGoodsInfoDao.java | WINDOWS-1250 | 81 | 1.78125 | 2 | [] | no_license | package IOCص;
public interface IGoodsInfoDao {
public void add();
}
| true |
3d86b37c116a896664819f6cfdf96e8b5b66964c | Java | MarcinSkrzecz/Kontrahent_Faktura_Backend | /src/main/java/com/marcin/kontrahent_faktura_backend/domain/invoice/InvoiceDto.java | UTF-8 | 450 | 2.0625 | 2 | [] | no_license | package com.marcin.kontrahent_faktura_backend.domain.invoice;
import lombok.Getter;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@Getter
public class InvoiceDto {
private Long invoiceId;
private Long taxId;
private Double invoiceAmount;
public InvoiceDto(Long invoiceId, Long taxId, Double invoiceAmount) {
this.invoiceId = invoiceId;
this.taxId = taxId;
this.invoiceAmount = invoiceAmount;
}
}
| true |
7ee910e330b1a196f174e5fa5b238f0d20d2739b | Java | temasql/TeamSQL | /src/main/java/kr/or/ddit/main/controller/MainController.java | UTF-8 | 2,524 | 1.953125 | 2 | [] | no_license | package kr.or.ddit.main.controller;
import java.util.ArrayList;
import java.util.List;
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.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import kr.or.ddit.crew.service.ICrewService;
import kr.or.ddit.history.model.HistoryTempVO;
import kr.or.ddit.history.service.IHistoryService;
import kr.or.ddit.user.model.UserVO;
import kr.or.ddit.util.Crawling;
import kr.or.ddit.util.CrawlingVO;
@Controller
public class MainController {
private static final Logger logger = LoggerFactory.getLogger(MainController.class);
@Resource(name = "historyService")
private IHistoryService historyService;
@Resource(name = "crewService")
private ICrewService crewService;
@RequestMapping(path = "/main", method = RequestMethod.GET)
public String main(HttpSession session, Model model) {
// 유저아이디
String user_id = ((UserVO) session.getAttribute("USER_INFO")).getUser_id();
List<String> accountList = historyService.getAccountIdList(user_id);
List<HistoryTempVO> historyTempList = new ArrayList<HistoryTempVO>();
for (int i = 0; i < accountList.size(); i++) {
HistoryTempVO historyTempVO = historyService.getLastDateAndName(accountList.get(i));
historyTempList.add(historyTempVO);
}
List<String> accoList = new ArrayList<String>();
for (int i = 0; i < accountList.size(); i++) {
String account_id_underBar = accountList.get(i);
int underBarIdx = account_id_underBar.lastIndexOf("_");
String account_id = account_id_underBar.substring(0, underBarIdx);
accoList.add(account_id);
}
for (int i = 0; i < historyTempList.size(); i++) {
historyTempList.get(i).setAccount_id(accountList.get(i));
historyTempList.get(i).setSlice_account_id(accoList.get(i));
}
if(historyTempList.size() > 4) {
for (int i = 5; i < historyTempList.size(); i++) {
historyTempList.remove(i);
}
}
model.addAttribute("historyTempList", historyTempList);
model.addAttribute("crewMap", crewService.getAccountCrew(user_id));
// IT뉴스
List<List<CrawlingVO>> itNewsList = new Crawling().getITNews();
model.addAttribute("itNewsList", itNewsList);
return "main.tiles";
}
}
| true |
11448d043dfe746d9a96b942a53e5b6f42183ac2 | Java | milostopolic/ISA2018Heroku | /src/test/java/rs/ftn/isa/constants/RoomConstants.java | UTF-8 | 501 | 1.8125 | 2 | [] | no_license | package rs.ftn.isa.constants;
public class RoomConstants {
public static final int NEW_BEDS = 2;
public static final float NEW_PRICE = 100;
public static final double NEW_RATING = 3.65;
public static final boolean NEW_DISCOUNT = true;
public static final Long DB_ID = 1L;
public static final int DB_BEDS = 2;
public static final float DB_PRICE = 40;
public static final double DB_RATING = 3.12;
public static final boolean DB_DISCOUNT = false;
public static final int DB_COUNT = 6;
}
| true |
400fdbfde2f95086f569ccefcf8684a97942f02a | Java | msrkms/Blog | /app/src/main/java/com/sajidur/blog/view/BlogActivity.java | UTF-8 | 2,677 | 2.046875 | 2 | [] | no_license | package com.sajidur.blog.view;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import com.sajidur.blog.R;
import com.sajidur.blog.adapter.BlogAdapter;
import com.sajidur.blog.databinding.ActivityBlogBinding;
import com.sajidur.blog.model.POJO.Blog;
import com.sajidur.blog.viewmodel.BlogViewModel;
import java.util.List;
public class BlogActivity extends AppCompatActivity {
SharedPreferences prefs=null;
private BlogViewModel blogViewModel;
private BlogAdapter blogAdapter;
private List<Blog> blogList;
private ActivityBlogBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding= DataBindingUtil.setContentView(this,R.layout.activity_blog);
prefs = getPreferences(Context.MODE_PRIVATE);
blogViewModel=new ViewModelProvider(this,new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(BlogViewModel.class);
if(needOnlineData()){
blogViewModel.getBlogLiveData().observe(BlogActivity.this, new Observer<List<Blog>>() {
@Override
public void onChanged(List<Blog> blogs) {
blogViewModel.insertIntoROOMDB();
blogList=blogs;
setRecyclerViewBlogData();
System.out.println("Online Data");
prefs.edit().putBoolean("NeedOnlineData", false).commit();
}
});
}else{
blogViewModel.getAllBlogs().observe(BlogActivity.this, new Observer<List<Blog>>() {
@Override
public void onChanged(List<Blog> blogs) {
blogList=blogs;
setRecyclerViewBlogData();
System.out.println("Offline Data");
}
});
}
}
private boolean needOnlineData(){
if(prefs.getBoolean("NeedOnlineData",true)){
return true;
}else{
return false;
}
}
private void setRecyclerViewBlogData(){
blogAdapter=new BlogAdapter(blogList);
binding.recyclerViewBlog.setLayoutManager(new LinearLayoutManager(this));
binding.recyclerViewBlog.setAdapter(blogAdapter);
}
} | true |
8ca38ca2954b9d53dfd6b6796bf2f2e452b89a6a | Java | quantyam/PaperlessHajj2 | /app/src/main/java/com/quantyam/app/paperlesshajj/RuntimePermissionUtil.java | UTF-8 | 135 | 1.546875 | 2 | [] | no_license | package com.quantyam.app.paperlesshajj;
interface RPResultListener {
void onPermissionGranted();
void onPermissionDenied();
} | true |
8d5f56493b0e1acfcff6713f87a5ea9da45fb558 | Java | IrinaKV/Spring2020JavaPractice | /src/day14_StringClass/Credentials2.java | UTF-8 | 527 | 3.703125 | 4 | [] | no_license | package day14_StringClass;
import java.util.Scanner;
public class Credentials2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String word1 = scan.next();
String word2 = scan.next();
System.out.println(word1.length());
System.out.println(word2.length());
if (word1.compareTo(word2)==0){
System.out.println("word1 equals word2");
}else{
System.out.println("word1 does not equal word2");
}
}
}
| true |
809b176f5a64ded272a6956ff228f15f720af6f0 | Java | Seachal/ColorMatrix | /app/src/main/java/com/matrix/yukun/matrix/tool_module/gif/bean/VideoInfo.java | UTF-8 | 1,221 | 2.125 | 2 | [] | no_license | package com.matrix.yukun.matrix.tool_module.gif.bean;
import android.graphics.Bitmap;
/**
* author: kun .
* date: On 2019/2/18
*/
public class VideoInfo {
private Bitmap mBitmap;
private long timeMs;
private boolean isChooseStart;
private boolean isChooseEnd;
private boolean isChooseCenter;
public VideoInfo( int timeMs,Bitmap bitmap) {
mBitmap = bitmap;
this.timeMs = timeMs;
}
public boolean isChooseCenter() {
return isChooseCenter;
}
public void setChooseCenter(boolean chooseCenter) {
isChooseCenter = chooseCenter;
}
public boolean isChooseStart() {
return isChooseStart;
}
public void setChooseStart(boolean chooseStart) {
isChooseStart = chooseStart;
}
public boolean isChooseEnd() {
return isChooseEnd;
}
public void setChooseEnd(boolean chooseEnd) {
isChooseEnd = chooseEnd;
}
public Bitmap getBitmap() {
return mBitmap;
}
public void setBitmap(Bitmap bitmap) {
mBitmap = bitmap;
}
public long getTimeMs() {
return timeMs;
}
public void setTimeMs(long timeMs) {
this.timeMs = timeMs;
}
}
| true |
22fb4c0a3d75bfaaa53a15348dc9b7c7811b9edd | Java | CocosApp/cocos-android | /app/src/main/java/com/cocos/cocosapp/presentation/main/favoritos/FavoritosAdapter.java | UTF-8 | 4,219 | 1.992188 | 2 | [] | no_license | package com.cocos.cocosapp.presentation.main.favoritos;
import android.content.Context;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.cocos.cocosapp.R;
import com.cocos.cocosapp.core.LoaderAdapter;
import com.cocos.cocosapp.data.entities.RestauranteResponse;
import com.cocos.cocosapp.utils.OnClickListListener;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by katherine on 15/05/17.
*/
public class FavoritosAdapter extends LoaderAdapter<RestauranteResponse> implements OnClickListListener {
private Context context;
private RestItem restItem;
public FavoritosAdapter(ArrayList<RestauranteResponse> restEntinties, Context context, RestItem restItem) {
super(context);
setItems(restEntinties);
this.context = context;
this.restItem = restItem;
}
public FavoritosAdapter(ArrayList<RestauranteResponse> restEntinties, Context context) {
super(context);
setItems(restEntinties);
this.context = context;
}
public ArrayList<RestauranteResponse> getItems() {
return (ArrayList<RestauranteResponse>) getmItems();
}
@Override
public long getYourItemId(int position) {
return getmItems().get(position).getId();
}
@Override
public RecyclerView.ViewHolder getYourItemViewHolder(ViewGroup parent) {
View root = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_favoritos, parent, false);
return new ViewHolder(root, this);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void bindYourViewHolder(RecyclerView.ViewHolder holder, final int position) {
final RestauranteResponse restEntinty = getItems().get(position);
((ViewHolder) holder).tvName.setText(restEntinty.getName());
if (restEntinty.getSubcategory().size() > 0) {
((ViewHolder) holder).tvCategoty.setText(restEntinty.getSubcategory().get(0).getName());
} else {
((ViewHolder) holder).tvCategoty.setText("Sin categoría");
}
if (restEntinty.getPhoto1() != null) {
Glide.with(context)
.load(restEntinty.getPhoto1())
.into(((ViewHolder) holder).back);
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
((ViewHolder) holder).back.setImageDrawable(context.getDrawable(R.drawable.cocos_app_default));
} else {
((ViewHolder) holder).back.setImageDrawable(context.getResources().getDrawable(R.drawable.cocos_app_default));
}
}
((ViewHolder) holder).btnQuitarFavorito.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
restItem.deleteItem(restEntinty, position);
}
});
}
@Override
public void onClick(int position) {
RestauranteResponse restEntinty = getItems().get(position);
restItem.clickItem(restEntinty);
}
static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
@BindView(R.id.back)
ImageView back;
@BindView(R.id.tv_name)
TextView tvName;
@BindView(R.id.tv_categoty)
TextView tvCategoty;
@BindView(R.id.btn_quitar_favorito)
LinearLayout btnQuitarFavorito;
private OnClickListListener onClickListListener;
ViewHolder(View itemView, OnClickListListener onClickListListener) {
super(itemView);
ButterKnife.bind(this, itemView);
this.onClickListListener = onClickListListener;
this.itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
onClickListListener.onClick(getAdapterPosition());
}
}
}
| true |
90382354329c5e11f2b45a69c3f2f77bd00d924a | Java | md-salim/RestServiceJersey | /src/main/java/org/koushik/javabrains/messenger/service/MessageService.java | UTF-8 | 1,856 | 2.875 | 3 | [] | no_license | package org.koushik.javabrains.messenger.service;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import org.koushik.javabrains.messenger.database.DatabaseClass;
import org.koushik.javabrains.messenger.exception.DataNotFountException;
import org.koushik.javabrains.messenger.model.Message;
public class MessageService {
private Map<Long, Message> messages = DatabaseClass.getMessages();
public MessageService(){
messages.put(1L, new Message(1,"Hello World","koushik"));
messages.put(2L, new Message(2,"Hello jersy","koushik"));
}
public List<Message> getAllMessages() {
return new ArrayList<Message>(messages.values());
}
public List<Message> getAllMessagesForYour(int year){
List<Message> messagesForYear = new ArrayList<>();
Calendar cal = Calendar.getInstance();
for(Message message : messages.values()){
cal.setTime(message.getCreated());
if(cal.get(Calendar.YEAR) == year){
messagesForYear.add(message);
}
}
return messagesForYear;
}
public List<Message> getAllmesMessagesPaginated(int start, int size){
ArrayList<Message> list = new ArrayList<Message>(messages.values());
if(start + size>list.size()) return new ArrayList<Message>();
return list.subList(start, start + size);
}
public Message getMessage(long id){
Message message = messages.get(id);
if(message == null){
throw new DataNotFountException("message with id:"+id+"not found");
}
return message;
}
public Message addMessage(Message message){
message.setId(messages.size()+1);
messages.put(message.getId(),message);
return message;
}
public Message updateMessage(Message message){
if(message.getId() <=0){
return null;
}
messages.put(message.getId(),message); return message;
}
public Message removeMessage(long id){
return messages.remove(id);
}
}
| true |
262a288d5545ded2ef7cd73644531484e3aa4bde | Java | shvoonder/biu.swe | /Ex3/src/Stopwatch/MyStopwatch.java | UTF-8 | 1,370 | 3.15625 | 3 | [] | no_license | package Stopwatch;
import java.time.ZonedDateTime;
import java.util.Scanner;
public class MyStopwatch extends Thread implements Runnable {
private ZonedDateTime currTime;
private int endMin;
private int endSec;
private int endHour;
private int startMin;
private int startSec;
private int startHour;
private Scanner s;
public MyStopwatch (){
s = new Scanner(System.in);
this.currTime = ZonedDateTime.now();
this.startSec = currTime.getSecond();
this.startMin = currTime.getMinute();
this.startHour = currTime.getHour();
}
public void run(){
chk();
this.currTime = ZonedDateTime.now();
this.endSec = currTime.getSecond();
this.endMin = currTime.getMinute();
this.endHour = currTime.getHour();
printTime();
}
private void printTime(){
int secTot = this.endSec - this.startSec;
int minTot = this.endMin - this.startMin;
int hourTot = this.endHour - this.startHour;
if (secTot < 0) {
secTot = 60 + secTot;
minTot--;
}
if (minTot < 0){
minTot = 60 + minTot;
hourTot--;
}
System.out.println(hourTot + ":" + minTot + ":" + secTot);
}
private synchronized void chk (){
String str = s.nextLine();
}
}
| true |
989e550b90d6320f4c15fff66fae04e75bafb130 | Java | vastsuperking/gltools | /src/java/gltools/ffp/FFPTexCoordAttribute.java | UTF-8 | 1,488 | 2.265625 | 2 | [] | no_license | package gltools.ffp;
import glcommon.vector.Matrix2f;
import glcommon.vector.Matrix3f;
import glcommon.vector.Matrix4f;
import glcommon.vector.Vector2f;
import glcommon.vector.Vector3f;
import glcommon.vector.Vector4f;
import gltools.gl.GL1;
import gltools.gl.GL2;
import gltools.shader.Attribute;
import gltools.shader.InputUsage;
public class FFPTexCoordAttribute extends Attribute {
public FFPTexCoordAttribute() {
setUsage(InputUsage.VERTEX_TEX_COORD);
}
@Override
public void enableArray(GL2 gl) {
gl.glEnableClientState(GL1.GL_TEXTURE_COORD_ARRAY);
}
@Override
public void disableArray(GL2 gl) {
gl.glDisableClientState(GL1.GL_TEXTURE_COORD_ARRAY);
}
@Override
public void point(int stride, long offset, GL2 gl) {
gl.glTexCoordPointer(getUsage().getDataType().getComponents(), getUsage().getDataType().getComponentType().getID(), stride, offset);
}
@Override
public void setValue(GL2 gl, float val) {
gl.glTexCoord1f(val);
}
@Override
public void setValue(GL2 gl, Vector2f val) {
gl.glTexCoord2f(val.getX(), val.getY());
}
@Override
public void setValue(GL2 gl, Vector3f val) {
gl.glTexCoord3f(val.getX(), val.getY(), val.getZ());
}
@Override
public void setValue(GL2 gl, Vector4f val) {
gl.glTexCoord4f(val.getX(), val.getY(), val.getZ(), val.getW());
}
@Override
public void setValue(GL2 gl, Matrix2f val) {}
@Override
public void setValue(GL2 gl, Matrix3f val) {}
@Override
public void setValue(GL2 gl, Matrix4f val) {}
}
| true |
afb1b364849f60c55abde81d3e65a719cd4405b6 | Java | kevinylo/CarSelection | /app/src/main/java/kevin/lo/cardealers/models/ContactInfo.java | UTF-8 | 1,945 | 2.15625 | 2 | [] | no_license |
package kevin.lo.cardealers.models;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class ContactInfo {
@SerializedName("phone")
@Expose
private String phone;
@SerializedName("website")
@Expose
private String website;
@SerializedName("gpContactFirstName")
@Expose
private String gpContactFirstName;
@SerializedName("gpContactLastName")
@Expose
private String gpContactLastName;
@SerializedName("gpContactEmail")
@Expose
private String gpContactEmail;
@SerializedName("gpCommitment")
@Expose
private String gpCommitment;
@SerializedName("gpPhone")
@Expose
private String gpPhone;
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getGpContactFirstName() {
return gpContactFirstName;
}
public void setGpContactFirstName(String gpContactFirstName) {
this.gpContactFirstName = gpContactFirstName;
}
public String getGpContactLastName() {
return gpContactLastName;
}
public void setGpContactLastName(String gpContactLastName) {
this.gpContactLastName = gpContactLastName;
}
public String getGpContactEmail() {
return gpContactEmail;
}
public void setGpContactEmail(String gpContactEmail) {
this.gpContactEmail = gpContactEmail;
}
public String getGpCommitment() {
return gpCommitment;
}
public void setGpCommitment(String gpCommitment) {
this.gpCommitment = gpCommitment;
}
public String getGpPhone() {
return gpPhone;
}
public void setGpPhone(String gpPhone) {
this.gpPhone = gpPhone;
}
}
| true |
999fc5c84a09062a939fb522f4c0144f09b5e168 | Java | MeghaManwal/Online_Book_Store_App | /OnlineBookStore/src/main/java/com/bridgelabz/onlinebookstore/service/CustomerService.java | UTF-8 | 3,240 | 2.34375 | 2 | [] | no_license | package com.bridgelabz.onlinebookstore.service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bridgelabz.onlinebookstore.dto.CustomerDataDTO;
import com.bridgelabz.onlinebookstore.dto.UpdateCustomerDTO;
import com.bridgelabz.onlinebookstore.exception.BookStoreException;
import com.bridgelabz.onlinebookstore.model.BookCartData;
import com.bridgelabz.onlinebookstore.model.CustomerData;
import com.bridgelabz.onlinebookstore.model.UserData;
import com.bridgelabz.onlinebookstore.repository.CustomerDataRepository;
import com.bridgelabz.onlinebookstore.repository.UserDataRepository;
import com.bridgelabz.onlinebookstore.utils.TokenUtils;
@Service
public class CustomerService implements ICustomerService{
TokenUtils jwtToken = new TokenUtils();
@Autowired
UserDataRepository userdatarepository;
@Autowired
CustomerDataRepository customerdatarepository;
@Override
public CustomerData addNewCustomerDetails(CustomerDataDTO customerdto, String token) {
UUID userId = jwtToken.decodeJWT(token);
Optional<UserData> findExistingUser = userdatarepository.findById(userId);
if(!findExistingUser.isPresent()) {
throw new BookStoreException(BookStoreException.ExceptionTypes.USER_NOT_FOUND);
}
List<CustomerData> customerdatalist = new ArrayList<>();
CustomerData customerdata = new CustomerData(customerdto);
customerdata.setUserId(userId);
customerdatalist.add(customerdata);
CustomerData data = customerdatarepository.save(customerdata);
return data;
}
@Override
public List<CustomerData> displayCustomerDetails(String token) {
UUID userId = jwtToken.decodeJWT(token);
Optional<UserData> findExistingUser = userdatarepository.findById(userId);
if(!findExistingUser.isPresent()) {
throw new BookStoreException(BookStoreException.ExceptionTypes.USER_NOT_FOUND);
}
return customerdatarepository.findAll()
.stream()
.collect(Collectors.toList());
}
@Override
public String updateCustomerData(UpdateCustomerDTO updatedto, String token) {
UUID userId = jwtToken.decodeJWT(token);
Optional<UserData> findExistingUser = userdatarepository.findById(userId);
if(!findExistingUser.isPresent()){
throw new BookStoreException(BookStoreException.ExceptionTypes.USER_NOT_FOUND);
}
CustomerData customerdata = customerdatarepository.findByCustomerId(updatedto.getCustomerdataId())
.orElseThrow(() -> new BookStoreException(BookStoreException.ExceptionTypes.CUSTOMER_NOT_FOUND));
customerdata.setAddress(updatedto.getAddress());
customerdata.setCity(updatedto.getCity());
customerdata.setLandmark(updatedto.getLandmark());
customerdata.setState(updatedto.getState());
customerdata.setPincode(updatedto.getPincode());
customerdatarepository.save(customerdata);
return "Customer Data Updated Successfully";
}
}
| true |
56402d160803ec5b4f0d1d5777cd2ef01033d4dc | Java | devaaron/log-prox | /src/main/java/org/logprox/annotation/LoggerScanner.java | UTF-8 | 96 | 1.609375 | 2 | [] | no_license | package org.logprox.annotation;
public interface LoggerScanner {
public void setLoggers();
}
| true |
5d899d2fce406190dc2fe4b76ca852994c6f0c05 | Java | RuanNunes/cnpjAPI | /src/main/java/com/vixsystem/cnpj/repositories/VSDadosCnpjRepository.java | UTF-8 | 1,449 | 2.078125 | 2 | [] | no_license | package com.vixsystem.cnpj.repositories;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.vixsystem.cnpj.domains.VSDadosCnpj;
import com.vixsystem.cnpj.projections.VCDadosCnpjProjection;
@Repository
public interface VSDadosCnpjRepository extends JpaRepository<VSDadosCnpj, Integer>{
/**
* @autor Ruan Nunes
* @param limit
* CNAE DE FARMACIA
* 4771-7/01 Comércio varejista de produtos farmacêuticos, sem manipulação de fórmulas
* 4771-7/02 Comércio varejista de produtos farmacêuticos, com manipulação de fórmulas
* 4771-7/03 Comércio varejista de produtos farmacêuticos homeopáticos
*
*/
@Transactional(readOnly = true)
@Query(value ="select " +
" razao_social," +
" nome_fantasia," +
" uf," +
" municipio," +
" bairro," +
" cep," +
" cnae_fiscal," +
" cnpj, " +
" id, " +
" migrado " +
" from cnpj_dados_cadastrais_pj " +
" where migrado isnull and cnae_fiscal in ('4771701','4771702','4771703')" +
" limit :limit "
,nativeQuery = true)
List<VCDadosCnpjProjection> selectMigration(@Param("limit") Integer limit);
@Transactional(readOnly = true)
VSDadosCnpj findByCnpj(String cnpj);
}
| true |
1bc14e37d44696aadcf679471e3552fd0382c8ac | Java | andreygalassi/POCSpringJWT | /src/main/java/br/com/agrego/tokenRest/repository/acesso/PermissaoRepositoryImp.java | UTF-8 | 494 | 1.78125 | 2 | [] | no_license | package br.com.agrego.tokenRest.repository.acesso;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import br.com.agrego.tokenRest.model.acesso.Permissao;
import br.com.agrego.tokenRest.repository.AbstractJpaDAO;
@Repository
public class PermissaoRepositoryImp extends AbstractJpaDAO<Permissao> {
@Autowired
private PermissaoRepository repo;
public PermissaoRepository getRepo() {
return repo;
}
}
| true |
ac0ae12996e18074368f45a581dc97a3a8ab5b4d | Java | frafac-JumpStart/jumpstart-5.2.4.0 | /web/src/main/java/jumpstart/web/components/examples/layoutwithmenu/Layout.java | UTF-8 | 872 | 2.40625 | 2 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | package jumpstart.web.components.examples.layoutwithmenu;
import jumpstart.web.annotation.ProtectedPage;
import jumpstart.web.commons.Menu;
import jumpstart.web.commons.MenuOption;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.Property;
@ProtectedPage
public class Layout {
// Parameters
@SuppressWarnings("unused")
@Parameter
@Property
private String _title = "";
@SuppressWarnings("unused")
@Parameter
@Property
private String _chosenOption = "";
private Menu _menu;
// The code
public Menu getMenu() {
if (_menu == null) {
_menu = new Menu();
_menu.add(new MenuOption("Page 1", "examples/layoutwithmenu/Page1"));
_menu.add(new MenuOption("Page 2", "examples/layoutwithmenu/Page2"));
_menu.add(new MenuOption("Page 3", "examples/layoutwithmenu/Page3"));
}
return _menu;
}
}
| true |
7debba0e2ee366ce5959c17817cc2e2de6dc931c | Java | mateuszd2411/ClickerGDX | /core/src/com/mygdx/clicker/Entities/Player.java | UTF-8 | 1,716 | 2.828125 | 3 | [] | no_license | package com.mygdx.clicker.Entities;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.math.Interpolation;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.scenes.scene2d.Action;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
public class Player extends Image {
private final static int WIDHT = 77;
private final static int HEIGHT = 152;
private final static int STARTING_X = 200;
private final static int STARTING_Y = 300;
public Player(){
super(new Texture("player.png"));
this.setOrigin(WIDHT/2, HEIGHT/2);
this.setSize(WIDHT,HEIGHT);
// starting position
this.setPosition(STARTING_X,STARTING_Y);
}
public void reactOnClick() {
int xmoveAmount = MathUtils.random(-130,130);
int ymoveAmount = 10;
float moveActionTime = 0.30f;
Action moveAction = Actions.sequence(
Actions.moveBy(xmoveAmount,ymoveAmount,moveActionTime, Interpolation.circle),
Actions.moveBy(-xmoveAmount,-ymoveAmount,moveActionTime, Interpolation.circle)
);
int xgrowAmount = MathUtils.random(-30,100);
int ygrowAmount = 20;
float growActionTime = 0.2f;
Action growAction = Actions.sequence(
Actions.sizeBy(xgrowAmount,ygrowAmount,growActionTime, Interpolation.circle),
Actions.sizeBy(-xgrowAmount,-ygrowAmount,growActionTime, Interpolation.circle)
);
this.addAction(moveAction);
this.addAction(growAction);
if (this.getHeight() > 170){
this.addAction(Actions.rotateBy(MathUtils.randomSign() * 360,0.4f));
}
}
}
| true |
2017e80866a7af0090ad6f4173306ea12a571742 | Java | magefree/mage | /Mage.Sets/src/mage/cards/d/DarkHeartOfTheWood.java | UTF-8 | 1,282 | 2.484375 | 2 | [
"MIT"
] | permissive |
package mage.cards.d;
import java.util.UUID;
import mage.abilities.common.SimpleActivatedAbility;
import mage.abilities.costs.common.SacrificeTargetCost;
import mage.abilities.effects.common.GainLifeEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.constants.Zone;
import mage.filter.common.FilterControlledPermanent;
import mage.target.common.TargetControlledPermanent;
/**
*
* @author Loki
*/
public final class DarkHeartOfTheWood extends CardImpl {
private static final FilterControlledPermanent filter = new FilterControlledPermanent("Forest");
static {
filter.add(SubType.FOREST.getPredicate());
}
public DarkHeartOfTheWood(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.ENCHANTMENT},"{B}{G}");
// Sacrifice a Forest: You gain 3 life.
this.addAbility(new SimpleActivatedAbility(Zone.BATTLEFIELD, new GainLifeEffect(3), new SacrificeTargetCost(new TargetControlledPermanent(filter))));
}
private DarkHeartOfTheWood(final DarkHeartOfTheWood card) {
super(card);
}
@Override
public DarkHeartOfTheWood copy() {
return new DarkHeartOfTheWood(this);
}
}
| true |
f4b56a160024992b3ae788e673a2237db86ee346 | Java | yesk202092/cloud-sure | /sure-admin/src/main/java/sure/sys/controller/SysRoleController.java | UTF-8 | 2,122 | 2.125 | 2 | [] | no_license | package sure.sys.controller;
import com.sure.BaseController;
import com.sure.DataGrid;
import com.sure.page.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import sure.sys.biz.SysRoleBiz;
import sure.sys.entity.SysRole;
import tk.mybatis.mapper.entity.Example;
/**
* @类名: 角色信息Controller
* @描述: 角色信息
* @作者:
* @日期: 2019-04-24 11:00:13
*/
@Controller
@RequestMapping("sysRole")
public class SysRoleController extends BaseController<SysRoleBiz, SysRole> {
/**
* @名称: grid
* @描述: 分页查询
* @作者: yesk
* @参数: @param page
* @参数: @param name
* @参数: @return
* @返回: DataGrid<UserDetail>
*/
@RequestMapping(value = "grid",method = RequestMethod.POST)
@ResponseBody
public DataGrid<SysRole> page(SysRole sysRole, Page page){
Example example = new Example(SysRole.class);
return null;
}
/**
* @名称: list
* @描述: 进入列表界面
* @作者: yesk
* @参数: @return
* @返回: String
*/
@RequestMapping(value = "list",method = RequestMethod.GET)
public String list(){
return "/manage/sys/sysrole-list";
}
/**
* @名称: add
* @描述: 进入添加界面
* @作者: yesk
* @参数: @return
* @返回: String
*/
@RequestMapping(value = "add",method = RequestMethod.GET)
public String add(){
return "/manage/sys/sysrole-add";
}
/**
* @名称: edit
* @描述: 进入修改界面
* @作者: yesk
* @参数: @param id
* @参数: @param model
* @参数: @return
* @返回: String
*/
@RequestMapping(value = "edit",method = RequestMethod.GET)
public String edit(Long id, ModelMap model){
//model.put("sysRole", baseBiz.get(id));
return "/manage/sys/sysrole-edit";
}
} | true |
c58670ddaae7f6838f8987d3925cd0438735f820 | Java | wlewter/app-framework | /src/main/java/com/fbitn/appframework/repository/SubsystemRepository.java | UTF-8 | 276 | 2.171875 | 2 | [] | no_license | package com.fbitn.appframework.repository;
import java.util.List;
import com.fbitn.appframework.model.Subsystem;
public interface SubsystemRepository {
public List<Subsystem> getAll();
public void insertOne(Subsystem subsystem);
public Subsystem getOne(String name);
}
| true |
405468adf4e2e56954444feab65a617171db176f | Java | apexrobotics/ftc_app_networked_simulator | /PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/LegacyBrickSimulator.java | UTF-8 | 4,835 | 2.484375 | 2 | [
"MIT"
] | permissive | package org.ftccommunity.simulator.modules;
import org.ftccommunity.simulator.modules.devices.Device;
import org.ftccommunity.simulator.modules.devices.DeviceType;
import org.ftccommunity.simulator.modules.devices.NullDevice;
import javafx.geometry.Insets;
import javafx.scene.layout.*;
import javafx.scene.text.Text;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.IOException;
import java.net.DatagramPacket;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
/**
* Model class for a Motor Controller
*
* @author Hagerty High
*/
@XmlRootElement(name="Legacy")
public class LegacyBrickSimulator extends BrickSimulator {
private static final Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
protected final byte[] mCurrentStateBuffer = new byte[208];
protected final byte[] temp15 = new byte[15];
protected final byte[] temp12 = new byte[12];
/*
** Packet types
*/
protected static final byte PACKET_HEADER_0 = (byte)0x55;
protected static final byte PACKET_HEADER_1 = (byte)0xaa;
protected static final byte PACKET_WRITE_FLAG = (byte)0x00;
protected static final byte PACKET_READ_FLAG = (byte)0x80;
/**
* Default constructor.
*/
public LegacyBrickSimulator() {
mType = "Core Legacy Module";
mFXMLFileName = "view/EditDialog.fxml";
mNumberOfPorts = 6;
mDevices = new Device[mNumberOfPorts];
for (int i=0;i<mNumberOfPorts;i++) {
mDevices[i] = new NullDevice();
}
}
private void sendPacketToPhone(byte[] sendData) {
try {
os.write(sendData);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void handleIncomingPacket(byte[] data, int length, boolean wait)
{
if (data[0] == PACKET_HEADER_0 && data[1] == PACKET_HEADER_1) { // valid packet
if (data[2] == PACKET_READ_FLAG) { // read command
byte[] tempBuffer = new byte[data[4]];
System.arraycopy(mCurrentStateBuffer, Byte.toUnsignedInt(data[3]), tempBuffer, 0, tempBuffer.length);
sendPacketToPhone(tempBuffer);
//temp15[3] = (byte)0xfe;
} else { // write command
int offset = Byte.toUnsignedInt(data[3]);
int len = Byte.toUnsignedInt(data[4]);
System.arraycopy(data, 5, mCurrentStateBuffer, offset, len);
// Loop through each ports and process the buffer
for (int i=0;i<mNumberOfPorts;i++) {
mDevices[i].processBuffer(mCurrentStateBuffer, i);
}
}
}
}
/**
* Populate the details pane in the Overview window. This method adds details that are not common
* with the other types of controllers. In this Legacy controller, we need to detail the types of each
* of the six ports. A blank pane is passed in and the routine will fill in a 3x6 grid with the port info.
*/
public void populateDetailsPane(Pane pane) {
GridPane grid = new GridPane();
grid.setMaxSize(Region.USE_COMPUTED_SIZE, Region.USE_COMPUTED_SIZE);
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(10, 10, 10, 10));
grid.prefWidthProperty().bind(pane.widthProperty());
grid.prefHeightProperty().bind(pane.heightProperty());
// ColumnConstraints col1 = new ColumnConstraints();
// col1.setPercentWidth(20);
// ColumnConstraints col2 = new ColumnConstraints();
// col2.setPercentWidth(20);
// ColumnConstraints col3 = new ColumnConstraints();
// col3.setPercentWidth(20);
// ColumnConstraints col4 = new ColumnConstraints();
// col4.setPercentWidth(20);
// ColumnConstraints col5 = new ColumnConstraints();
// col5.setPercentWidth(20);
// grid.getColumnConstraints().addAll(col1,col2,col3,col4,col5);
for (int i=0;i<mNumberOfPorts;i++) {
Text portText = new Text("Port " + i);
grid.add(portText, 0, i);
Text typeText = new Text(mDevices[i].getType().getName());
grid.add(typeText, 1, i);
List<String> nameList = getPortDevice(i).getPortNames();
for (int j=0;j<nameList.size();j++) {
Text nameText = new Text(nameList.get(j));
grid.add(nameText,j+2,i);
}
}
pane.getChildren().add(grid);
}
/**
* Getters/Setters
*/
/**
* GUI Stuff
*/
public void setupDebugGuiVbox(VBox vbox) {
for (int i=0;i<mNumberOfPorts;i++) {
mDevices[i].setupDebugGuiVbox(vbox);
}
}
public void updateDebugGuiVbox() {
for (int i=0;i<mNumberOfPorts;i++) {
mDevices[i].updateDebugGuiVbox();
}
}
public List<DeviceType> getDeviceTypeList() {
List<DeviceType> dtl = new ArrayList<>();
dtl.add(DeviceType.NONE);
dtl.add(DeviceType.TETRIX_MOTOR);
dtl.add(DeviceType.TETRIX_SERVO);
dtl.add(DeviceType.LEGO_LIGHT);
return dtl;
}
} | true |
6e257f05fe1a0219a30f991536c59d282c8efc31 | Java | weidian-txcos/cos-java-sdk-v5 | /src/main/java/com/qcloud/cos/auth/BasicCOSCredentials.java | UTF-8 | 2,424 | 2.78125 | 3 | [
"MIT"
] | permissive | package com.qcloud.cos.auth;
public class BasicCOSCredentials implements COSCredentials {
private final String appId;
private final String accessKey;
private final String secretKey;
/**
*
* @param appId the appid which your resource belong to.
* @param accessKey your accessKey(SecretId). you can get it by https://console.qcloud.com/capi
* @param secretKey your secretKey. you can get it by https://console.qcloud.com/capi
* @deprecated appid should be included in bucket name. for example if your appid
* is 125123123, previous bucket is ott. you should set bucket as ott-125123123.
* use {@link BasicCOSCredentials#BasicCOSCredentials(String, String)}
*/
@Deprecated
public BasicCOSCredentials(String appId, String accessKey, String secretKey) {
super();
if (appId == null) {
throw new IllegalArgumentException("Appid cannot be null.");
}
try {
Long.valueOf(appId);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Appid is invalid num str.");
}
if (accessKey == null) {
throw new IllegalArgumentException("Access key cannot be null.");
}
if (secretKey == null) {
throw new IllegalArgumentException("Secret key cannot be null.");
}
this.appId = appId;
this.accessKey = accessKey;
this.secretKey = secretKey;
}
/**
*
* @param accessKey your accessKey(secretId). you can get it by https://console.qcloud.com/capi
* @param secretKey your secretKey. you can get it by https://console.qcloud.com/capi
*
*/
public BasicCOSCredentials(String accessKey, String secretKey) {
super();
appId = null;
if (accessKey == null) {
throw new IllegalArgumentException("Access key cannot be null.");
}
if (secretKey == null) {
throw new IllegalArgumentException("Secret key cannot be null.");
}
this.accessKey = accessKey;
this.secretKey = secretKey;
}
@Override
public String getCOSAppId() {
return appId;
}
@Override
public String getCOSAccessKeyId() {
return accessKey;
}
@Override
public String getCOSSecretKey() {
return secretKey;
}
}
| true |
ba4fc2e92db8c09e7d72267540bda5e99899d2a0 | Java | izabela02/JavaLdz2019 | /src/Zadanie130/GeneratorLiczbPierwszych.java | UTF-8 | 1,214 | 3.4375 | 3 | [] | no_license | package Zadanie130;
/*Utwórz klasę `GeneratorLiczbPierwszych` oraz zaimplementuj metody:
>* umożliwiającą wygenerowanie wybranej ilości liczb pierwszych. Dla `4` powinno zwrócić
tablicę zawierającą `[2, 3, 5, 7]`, a dla `10` powinno zwrócić tablicę zawierającą `[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]`.
>* zwrócenie wybranej liczby pierwszej
>* spradzają czy liczba podana jako parametr jest pierwsza (powinna zwracać wartość `boolean`)
*/
import java.util.Arrays;
public class GeneratorLiczbPierwszych {
public static void main(String[] args) {
System.out.println(Arrays.toString(generator(1000)));
}
static int[] generator(int liczba) {
int[] arr = new int[liczba];
int counter = 0;
for (int i = 2; counter < liczba; i++) {
if (czyPierwsza(i)) {
arr[counter] = i;
counter++;
}
}
return arr;
}
static boolean czyPierwsza(int liczba) {
if (liczba <= 1) {
return false;
}
for (int i = 2; i <= liczba / 2; i++) {
if (liczba % i == 0) {
return false;
}
}
return true;
}
}
| true |
1c48576510fc592bd4dd2a7853591411df55ddf6 | Java | A1502/janus | /janus-struct-prototype/src/main/java/com/wuxian/janus/struct/prototype/layer1/OuterObjectPrototype.java | UTF-8 | 1,767 | 2.4375 | 2 | [] | no_license | package com.wuxian.janus.struct.prototype.layer1;
import com.wuxian.janus.struct.prototype.JanusPrototype;
import com.wuxian.janus.struct.annotation.PropertyRemark;
import com.wuxian.janus.struct.util.PrototypeUtils;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;
import java.util.Date;
/**
* 外部对象Prototype类
*
* @author wuxian
* @email
* @date 2019/07/11
*/
@Accessors(chain = true)
@Setter
@Getter
@NoArgsConstructor
public class OuterObjectPrototype<ID, UID> extends JanusPrototype<ID, UID> {
public void fill(ID id
, ID outerObjectTypeId, String referenceId, String referenceCode, String referenceName
, String referenceDescription, UID createdBy, Date createdDate, UID lastModifiedBy, Date lastModifiedDate) {
setId(id);
setOuterObjectTypeId(outerObjectTypeId);
setReferenceId(referenceId);
setReferenceCode(referenceCode);
setReferenceName(referenceName);
setReferenceDescription(referenceDescription);
PrototypeUtils.fill(this,createdBy,createdDate,lastModifiedBy,lastModifiedDate);
}
@PropertyRemark(value = "外部对象类型id", example = "1")
private ID outerObjectTypeId;
@PropertyRemark(value = "外部引用id", example = "CN88800")
private String referenceId;
@PropertyRemark(value = "外部引用code", example = "China_Shanghai")
private String referenceCode;
@PropertyRemark(value = "外部引用名称", example = "中国上海市")
private String referenceName;
@PropertyRemark(value = "外部引用描述", example = "这是唯一识别外部数据的描述...")
private String referenceDescription;
//无需version
}
| true |
9b40d4b0d1cea24268a314aad839062027e37786 | Java | ramirezchristopher/blackplum_tshirt_store_backend | /src/main/java/com/business/domain/OrderFulfillmentStatus.java | UTF-8 | 848 | 2.3125 | 2 | [] | no_license | package com.business.domain;
import java.util.Arrays;
import org.apache.commons.lang3.StringUtils;
import lombok.Getter;
public enum OrderFulfillmentStatus {
DRAFT("draft"),
FAILED("failed"),
PENDING("pending"),
CANCELED("canceled"),
ON_HOLD("onhold"),
IN_PROCESS("inprocess"),
PARTIAL("partial"),
FULFILLED("fulfilled");
@Getter
private final String description;
private OrderFulfillmentStatus(String description) {
this.description = description;
}
public static OrderFulfillmentStatus findByDescription(String description) {
if(StringUtils.isBlank(description)) {
return null;
}
return Arrays.asList(OrderFulfillmentStatus.values()).stream()
.filter(status -> status.getDescription().equals(description))
.findFirst()
.orElse(null);
}
}
| true |
55961de29ad398b9334fb156cf1b91812cef270a | Java | geekyouup/androidbookmarker | /androidbookmarker/src/com/geekyouup/android/bookmarker/Bookmarker.java | UTF-8 | 6,833 | 2.171875 | 2 | [] | no_license | package com.geekyouup.android.bookmarker;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Browser;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
public class Bookmarker extends Activity implements OnItemClickListener, OnClickListener {
/** Called when the activity is first created. */
private ListView mListView;
private BookmarkAdapter bookmarkAdapter;
private ImageButton upButton;
private ImageButton downButton;
private ImageButton deleteButton;
private ImageButton launchButton;
private ImageButton topButton;
private ImageButton bottomButton;
private static final int DIALOG_YES_NO_MESSAGE = 1;
private static final int DIALOG_WELCOME = 2;
private int currentPos = -1;
private static final String PREFS_NAME = "BookmarkerPrefs";
private static final String LAUNCHED_KEY="LAUNCHED";
private static final int MENU_ABOUT = 0;
private static final int MENU_ADD = 1;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
bookmarkAdapter = new BookmarkAdapter(this, "");// new ArrayAdapter<Bookmark>(this, android.R.layout.simple_list_item_single_choice,bookmarks);
mListView = ((ListView) findViewById(R.id.mylistview));
mListView.setAdapter(bookmarkAdapter);
mListView.setOnItemClickListener(this);
upButton = (ImageButton) findViewById(R.id.upbutton);
downButton = (ImageButton) findViewById(R.id.downbutton);
deleteButton = (ImageButton) findViewById(R.id.deletebutton);
launchButton = (ImageButton) findViewById(R.id.launchbutton);
topButton = (ImageButton) findViewById(R.id.topbutton);
bottomButton = (ImageButton) findViewById(R.id.bottombutton);
upButton.setOnClickListener(this);
downButton.setOnClickListener(this);
deleteButton.setOnClickListener(this);
launchButton.setOnClickListener(this);
topButton.setOnClickListener(this);
bottomButton.setOnClickListener(this);
//if we have some bookmarks select the first and start everything
if(bookmarkAdapter.getCount()>0)
{
bookmarkAdapter.initialiseAllRows();
currentPos=0;
bookmarkAdapter.setSelected(currentPos);
}
//Make sure the welcome message only appears on first launch
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
if(settings !=null)
{
boolean launchedPreviously = settings.getBoolean(LAUNCHED_KEY, false);
if(!launchedPreviously)
{
showDialog(DIALOG_WELCOME);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(LAUNCHED_KEY, true);
editor.commit();
}
}
}
/**
* Invoked during init to give the Activity a chance to set up its Menu.
*
* @param menu the Menu to which entries may be added
* @return true
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, MENU_ADD, 0, "Add New Bookmark").setIcon(android.R.drawable.ic_menu_info_details);
menu.add(0, MENU_ABOUT, 1, R.string.menu_about).setIcon(android.R.drawable.ic_menu_info_details);
return true;
}
/**
* Invoked when the user selects an item from the Menu.
*
* @param item the Menu entry which was selected
* @return true if the Menu item was legit (and we consumed it), false
* otherwise
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == MENU_ABOUT)
{
showDialog(DIALOG_WELCOME);
return true;
}else if(item.getItemId() == MENU_ADD)
{
Browser.saveBookmark(this, "New Bookmark", "http://");
bookmarkAdapter.notifyDataSetChanged();
return true;
}else return false;
}
public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
currentPos = position;
bookmarkAdapter.setSelected(position);
}
public void onClick(View v) {
if(v == upButton && currentPos >0)
{
bookmarkAdapter.moveItemUp(currentPos);
currentPos--;
}else if(v== downButton && currentPos >=0 && currentPos<bookmarkAdapter.getCount()-1)
{
bookmarkAdapter.moveItemDown(currentPos);
currentPos++;
}else if(v== deleteButton)
{
showDialog(DIALOG_YES_NO_MESSAGE);
}else if(v== topButton)
{
currentPos = bookmarkAdapter.moveToTop(currentPos);
}else if(v== bottomButton)
{
currentPos = bookmarkAdapter.moveToBottom(currentPos);
}else if(v==launchButton)
{
String url = bookmarkAdapter.getUrl(currentPos);
if(url != null)
{
Intent i = new Intent("android.intent.action.VIEW",Uri.parse(url));
startActivity(i);
}
}
}
protected Dialog onCreateDialog(int id) {
if(id == DIALOG_YES_NO_MESSAGE)
{
return new AlertDialog.Builder(Bookmarker.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Confirm Delete")
.setMessage("Are you sure you want to delete this bookmark?")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
bookmarkAdapter.deleteRow(currentPos);
}})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//do nothing
}})
.create();
}else if(id == DIALOG_WELCOME)
{
String message = getString(R.string.welcome);
if(bookmarkAdapter.getCount()<1)
{
message += getString(R.string.nomarks);
}
AlertDialog dialog = new AlertDialog.Builder(Bookmarker.this).create();//new AlertDialog(Bookmarker.this);
dialog.setTitle("Welcome");
dialog.setMessage(message);
dialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
if(bookmarkAdapter.getCount()<1) { finish();}
}
});
dialog.setCancelable(true);
return dialog;
}else return null;
}
} | true |
5afb9fb142e6c6947536fa3fbd5d38225b9213a9 | Java | BugKillerss/Java | /src/main/java/com/java/reinforce/annotation/Testannotation02.java | GB18030 | 1,314 | 2.921875 | 3 | [] | no_license | package com.java.reinforce.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.HashMap;
import java.util.Map;
@Retention(RetentionPolicy.RUNTIME)//Ч
@Target(ElementType.TYPE)//ʾֻ
@interface Service{
String value() default "";
}
@Service("/hello")
class SysLogs{}
public class Testannotation02 {
static Map<String,Object> map=new HashMap<String,Object>();
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
//μSysLogsǷ@Service
Class<?> cls=SysLogs.class;
newInstance(cls);
SysLogs s1=getBean("/hello");
System.out.println(s1);
}
private static <T>T getBean(String s) {
return (T)map.get(s);
}
private static void newInstance(Class<?> cls) throws InstantiationException, IllegalAccessException {
//жSysLogssǷע
boolean flag=cls.isAnnotationPresent(Service.class);
//עȡע
if(!flag) return;
Service service=cls.getDeclaredAnnotation(Service.class);
System.out.println("service:"+service);
String key=service.value();
Object obj=cls.newInstance();
map.put(key,obj);
}
} | true |
3c1639399863588dc3047b6b76d50e1a20bad6f3 | Java | challengerzsz/Algorithm | /LeetCode/src/com/bsb/leetcode/T452.java | UTF-8 | 813 | 3.171875 | 3 | [] | no_license | package com.bsb.leetcode;
import java.util.Arrays;
import java.util.Comparator;
/**
* @author : zengshuaizhi
* @date : 2020-02-08 21:11
*/
public class T452 {
public int findMinArrowShots(int[][] points) {
if (points == null || points.length == 0) return 0;
Arrays.sort(points, Comparator.comparingInt(o -> o[1]));
int cur = points[0][1];
int count = 1;
for (int i = 1; i < points.length; i++) {
if (points[i][0] <= cur) continue;
count++;
cur = points[i][1];
}
return count;
}
public static void main(String[] args) {
int[][] array = {{3, 9}, {7, 12}, {3, 8}, {6, 8}, {9, 10}, {2, 9}, {0, 9}, {3, 9}, {0, 6}, {2, 8}};
System.out.println(new T452().findMinArrowShots(array));
}
}
| true |
f820ee021ef339cf202566bf6960584549b9b496 | Java | Komissarov88/SpringStore | /app/src/main/java/com/komissarov/spring/store/app/repository/ProductRepository.java | UTF-8 | 423 | 2.03125 | 2 | [] | no_license | package com.komissarov.spring.store.app.repository;
import com.komissarov.spring.store.common.entity.Product;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface ProductRepository extends PagingAndSortingRepository<Product, Long> {
List<Product> findAllByCostBetween(double min, double max);
}
| true |
9a25318439f3b9757f822ac306add8fc64415a47 | Java | 957001352/project20201203 | /dhlk_tenant_plat/dhlk_hive/src/main/java/com/dhlk/hive/dhlk_hive/DhlkHiveApplication.java | UTF-8 | 588 | 1.742188 | 2 | [] | no_license | package com.dhlk.hive.dhlk_hive;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.RestController;
@RestController
@EnableDiscoveryClient
@ComponentScan("com.dhlk.hive")
@SpringBootApplication
public class DhlkHiveApplication {
public static void main(String[] args) {
SpringApplication.run(DhlkHiveApplication.class, args);
}
}
| true |
f7632bccca9a27ed4b6f60cc1b4781b8036bc8d7 | Java | tabjy/container-jfr | /src/main/java/com/redhat/rhjmc/containerjfr/tui/tty/NoOpClientReader.java | UTF-8 | 396 | 2.03125 | 2 | [] | no_license | package com.redhat.rhjmc.containerjfr.tui.tty;
import java.io.IOException;
import com.redhat.rhjmc.containerjfr.core.tui.ClientReader;
class NoOpClientReader implements ClientReader {
@Override
public String readLine() {
throw new UnsupportedOperationException("NoOpClientReader does not support readLine");
}
@Override
public void close() throws IOException {}
}
| true |
acbfaa55eed6e75a3f421ce70dd37d8334cd5a21 | Java | eliosco/TD-GAME | /src/pannelli/PannelloInferiore.java | UTF-8 | 4,873 | 2.859375 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pannelli;
import attori.Giocatore;
import javax.swing.*;
import ascoltatori.AscoltatoreDiEventiInferiore;
import static finestre.Finestra.panel;
/**
*Classe di PannelloInferiore
* @author User
*/
public class PannelloInferiore extends JPanel {
private int ondManc;// Variabile che determina il numero di ondate mancanti per terminare la partita.
private JButton ready, morefast, piuLento, normale;// bottoni che determinano la velocità di scorrimento della barra di progresso e la partenza delle ondate.
private String velocita;// Stringa che contiene il valore del bottone cliccato.
private JLabel vel;// label che stampa il valore della velocità della barra di progresso
private AscoltatoreDiEventiInferiore ondate, ricevitoreL, ricevitoreN, ricevitoreV; // recevitori di eventi per ogni bottone.
private JLabel vita;// label che contiene la vita del giocatore.
private JLabel soldi;// label che contiene i soldi del giocatore.
private JLabel ondateMancanti;// label che contiene il valore delle ondate mancanti.
private JProgressBar barraProgresso = new JProgressBar(0, 100);// inizializzazione di una barra di progresso.
/**
*Metodo che restituisce il bottone "ready".
* @return
*/
public JButton getReady() {
return ready;
}
/**
*Metodo che restituisce la barra di progresso.
* @return
*/
public JProgressBar getBarraProgresso() {
return barraProgresso;
}
/**
*Metodo utilizzato per il set della barra di progresso.
* @param barraProgresso
*/
public void setBarraProgresso(JProgressBar barraProgresso) {
this.barraProgresso = barraProgresso;
}
/**
*Metodo che restituisce la label "vita".
* @return
*/
public JLabel getVita() {
return vita;
}
/**
*Metodo utilizzato per il set della label "vita".
* @param vita
*/
public void setVita(JLabel vita) {
this.vita = vita;
}
/**
*Metodo costruttore della classe.
* @param giocatore
*/
public PannelloInferiore(Giocatore giocatore) {
ondManc=3;
ready = new JButton("READY");
ondateMancanti=new JLabel("Mancano "+ ondManc+" ondate.");
morefast = new JButton("veloce");
piuLento = new JButton("lento");
normale = new JButton("normale");
velocita = "normale";
vel = new JLabel();
// inizializzazione degli ascoltatori di eventi.
ondate = new AscoltatoreDiEventiInferiore(ready, vel);
ricevitoreL = new AscoltatoreDiEventiInferiore(piuLento, vel);
ricevitoreN = new AscoltatoreDiEventiInferiore(normale, vel);
ricevitoreV = new AscoltatoreDiEventiInferiore(morefast, vel);
barraProgresso = new JProgressBar(0, 100);
vita = new JLabel("Vita: " + giocatore.getVita());
soldi = new JLabel("Soldi: " + giocatore.getSoldi());
vel.setText("normale");
// aggiunta al pannello delle varie label e bottoni.
add(vita);
add(soldi);
add(ready);
add(morefast);
add(normale);
add(piuLento);
add(barraProgresso);
add(vel);
add(ondateMancanti);
// aggiunta degli ascoltatori di eventi ai bottoni.
morefast.addActionListener(ricevitoreV);
normale.addActionListener(ricevitoreN);
piuLento.addActionListener(ricevitoreL);
ready.addActionListener(ondate);
}
/**
*Metodo che restituisce la label "ondateMancanti"
* @return
*/
public JLabel getOndateMancanti() {
return ondateMancanti;
}
/**
*Metodo utilizzato per il set della label "ondateMancanti"
* @param ondateMancanti
*/
public void setOndateMancanti(JLabel ondateMancanti) {
this.ondateMancanti = ondateMancanti;
}
/**
*Metodo utilizzato per aggiornare le label "vita" e "soldi" in base alle rispettive variabili di giocatore.
* @param giocatore
*/
public void update(Giocatore giocatore) {
vita.setText("Vita: " + giocatore.getVita());
soldi.setText("Soldi: " + giocatore.getSoldi());
}
/**
*Metodo che restituisce il valore di "ondManc"
* @return
*/
public int getOndManc() {
return ondManc;
}
/**
*Metodo utilizzato per il set di "ondManc"
* @param ondManc
*/
public void setOndManc(int ondManc) {
this.ondManc = ondManc;
}
}
| true |
bd5dbd1b914b13aa061feb00ff1fcd36e99c6810 | Java | felipesalesJ/LTP4 | /LTP4-Livraria/src/br/com/livraria/servlet/VendaServlet.java | UTF-8 | 746 | 1.898438 | 2 | [] | no_license | package br.com.livraria.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import br.com.livraria.modelo.Livro;
import br.com.livraria.bo.LivroBo;;
public class VendaServlet extends HttpServlet{
private String acao;
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
acao = req.getParameter("acao");
Livro livro = new Livro();
LivroBo livroBo = new LivroBo();
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
}
}
| true |
829f69cd6942870c3621d4eb93b690397c742b4e | Java | coignetp/jua | /src/main/java/jua/parser/IfStatementParser.java | UTF-8 | 1,985 | 2.921875 | 3 | [
"MIT"
] | permissive | package jua.parser;
import jua.ast.Expression;
import jua.ast.Statement;
import jua.ast.StatementIf;
import jua.token.Keyword;
import jua.token.Token;
import jua.token.TokenKeyword;
public class IfStatementParser implements StatementParser {
// nested should only be true when parsing an elseif statement inside a main if
// this argument tells parseIfStatement not to consume the only END keyword
@Override
public Statement parse(Parser parser) throws IllegalParseException {
return parseIfStatement(parser, false);
}
private Statement parseIfStatement(Parser parser, boolean nested) throws IllegalParseException {
// consumeKeyword.IF or Keyword.ELSEIF;
try {
parser.consume(Keyword.IF);
} catch (IllegalParseException e) {
parser.consume(Keyword.ELSEIF);
}
Expression condition = parser.parseExpression();
parser.consume(Keyword.THEN);
Statement consequence = parser.parseListStatement();
Token tok = parser.currentToken();
if (!parser.currentToken().isBlockEnd()) {
throw new IllegalParseException(
String.format("unexpected jua.token %s, expected end, else or elseif", tok));
}
Statement alternative = null;
TokenKeyword keyword = (TokenKeyword) tok;
switch (keyword.getKeyword()) {
case ELSEIF:
alternative = parseIfStatement(parser, true);
break;
case ELSE:
parser.consume(Keyword.ELSE);
alternative = parser.parseListStatement();
break;
}
tok = parser.currentToken();
if (!tok.isSubtype(Keyword.END)) {
throw new IllegalParseException(
String.format("unexpected jua.token %s, expected end", keyword));
}
if (!nested) {
// consume the END keyword
parser.consume(Keyword.END);
}
return new StatementIf(tok, condition, consequence, alternative);
}
@Override
public boolean matches(Parser parser) {
return parser.currentToken().isSubtype(Keyword.IF);
}
}
| true |
a7c509e064fdd2dead23dbec0bb3e854476825fc | Java | zhong2peng/dnight-framework | /dnight-leetcode/[0128][Longest Consecutive Sequence]/src/Solution.java | UTF-8 | 2,300 | 4.15625 | 4 | [
"MIT"
] | permissive | import java.util.HashSet;
import java.util.Set;
/**
* @author ZHONGPENG769
* @date 2019/9/9
*/
public class Solution {
/**
* Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
* <p>
* Your algorithm should run in O(n) complexity.
* <p>
* Example:
* <p>
* Input: [100, 4, 200, 1, 3, 2]
* Output: 4
* Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
* <p>
* 这道题要求求最长连续序列,并给定了O(n)复杂度限制,我们的思路是,使用一个集合HashSet存入所有的数字,
* 然后遍历数组中的每个数字,如果其在集合中存在,那么将其移除,然后分别用两个变量pre和next算出其前一个
* 数跟后一个数,然后在集合中循环查找,如果pre在集合中,那么将pre移除集合,然后pre再自减1,直至pre不在
* 集合之中,对next采用同样的方法,那么next-pre-1就是当前数字的最长连续序列,更新res即可。这里再说下,
* 为啥当检测某数字在集合中存在当时候,都要移除数字。这是为了避免大量的重复计算,就拿题目中的例子来说吧,
* 我们在遍历到4的时候,会向下遍历3,2,1,如果都不移除数字的话,遍历到1的时候,还会遍历2,3,4。同样,
* 遍历到3的时候,向上遍历4,向下遍历2,1,等等等。如果数组中有大量的连续数字的话,那么就有大量的重复计算,
* 十分的不高效,所以我们要从HashSet中移除数字
*
* @param nums
* @return
*/
public int longestConsecutive(int[] nums) {
int res = 0;
Set<Integer> set = new HashSet<>();
for (int i : nums) {
set.add(i);
}
for (int i : nums) {
if (set.remove(i)) {
int prev = i - 1;
int next = i + 1;
while (set.remove(prev)) {
--prev;
}
while (set.remove(next)) {
++next;
}
res = Math.max(res, next - prev - 1);
}
}
return res;
}
}
| true |
af39f7d295b1a70b9736f57900f8e8692a8495c5 | Java | mebbage/j4me | /J4ME/src/org/j4me/ui/components/CheckBox.java | UTF-8 | 6,013 | 3.265625 | 3 | [
"Apache-2.0"
] | permissive | package org.j4me.ui.components;
import javax.microedition.lcdui.*;
import org.j4me.ui.*;
/**
* The <code>CheckBox</code> component lets a user turn an option on or off.
* Multiple check box components can be placed sequentially to create
* a list of choices where zero or more can be chosen.
*/
public class CheckBox
extends Component
{
/**
* The ratio of the side of the checkbox square to the height of
* the current font.
*/
private static final double CHECKBOX_TO_FONT_RATIO = 0.70; // 70%
/**
* The text that appears to the right of the check box.
*/
private Label label = new Label();
/**
* If the item is checked this will be <code>true</code>. If the item
* is not this will be <code>false</code>.
*/
private boolean checked;
/**
* Constructs a <code>CheckBox</code> component.
*/
public CheckBox ()
{
}
/**
* Gets the value of the text that appears to the right of the check box.
*
* @return The text that appears next to the check box. It will
* never be <code>null</code> but may be the empty string "".
*/
public String getLabel ()
{
String l = label.getLabel();
if ( l == null )
{
l = "";
}
return l;
}
/**
* Sets the text that appears next to the check box.
*
* @param value is the text that appears to the right of the check box.
* A <code>null</code> is treated as the empty string "".
*/
public void setLabel (String value)
{
label.setLabel( value );
// The label may change the size requirements of this component.
invalidate();
}
/**
* Returns <code>true</code> if the box is checked or <code>false</code> if it is
* not.
*
* @return <code>true</code> if the box is checked or <code>false</code> if it is
* not.
*/
public boolean isChecked ()
{
return checked;
}
/**
* Checks or unchecks the box.
*
* @param checked when <code>true</code> checks the box; when <code>false</code>
* unchecks it.
*/
public void setChecked (boolean checked)
{
this.checked = checked;
}
/**
* An event raised whenever the component is made visible on the screen.
* This is called before the <code>paintComponent</code> method.
*/
protected void showNotify ()
{
label.visible( true );
super.showNotify();
}
/**
* An event raised whenever the component is removed from the screen.
*/
protected void hideNotify ()
{
label.visible( false );
super.hideNotify();
}
/**
* Paints the check box component.
*
* @see org.j4me.ui.components.Component#paintComponent(javax.microedition.lcdui.Graphics, org.j4me.ui.Theme, int, int, boolean)
*/
protected void paintComponent (Graphics g, Theme theme, int width, int height, boolean selected)
{
// Paint the check box.
int checkboxSide = checkboxSideSize( theme );
int y = (height - checkboxSide) / 2;
int offset = paintRect( g, theme, 0, y, checkboxSide, checkboxSide, selected );
// Paint the check in the box.
if ( checked )
{
int checkColor = theme.getHighlightColor();
g.setColor( checkColor );
int checkOffset = offset + 1;
int fillSide = checkboxSide - 2 * checkOffset;
g.fillRect( checkOffset, y + checkOffset, fillSide, fillSide );
}
// Paint the text to the side of the box.
int lx = (int)( checkboxSide * 1.5 );
int lw = width - lx;
int[] lDimensions = label.getPreferredSize( theme, lw, height );
int lh = lDimensions[1];
int ly = (height - lh) / 2;
label.paint( g, theme, getScreen(), lx, ly, lw, lh, selected );
}
/**
* Returns the size of the checkbox sides. It is a square so both sides have
* the same length.
*
* @param theme is the current application theme.
* @return The number of pixels each side of the checkbox is.
*/
private int checkboxSideSize (Theme theme)
{
int fontHeight = theme.getFont().getHeight();
int checkboxSide = (int)( fontHeight * CHECKBOX_TO_FONT_RATIO );
return checkboxSide;
}
/**
* Returns the dimensions of the check box.
*
* @see org.j4me.ui.components.Component#getPreferredComponentSize(org.j4me.ui.Theme, int, int)
*/
public int[] getPreferredComponentSize (Theme theme, int viewportWidth, int viewportHeight)
{
// Get the height of the checkbox.
int checkboxSide = checkboxSideSize( theme );
// Get the height of the label to the right of the checkbox.
int[] labelDimensions = label.getPreferredSize(
theme, viewportWidth - checkboxSide, viewportHeight );
// Return the bigger of the two heights.
int height = Math.max( checkboxSide, labelDimensions[1] );
// Make sure it is an even height. Makes the checkbox look better.
height += height % 2;
return new int[] { viewportWidth, height };
}
/**
* @return <code>true</code> because this component accepts user input.
*/
public boolean acceptsInput ()
{
return true;
}
/**
* Called when a key is pressed.
*
* @param keyCode is the key code of the key that was pressed.
*/
public void keyPressed (int keyCode)
{
// Was it an input character?
// Otherwise it was a menu button of special character.
if ( (keyCode > 0) || (keyCode == DeviceScreen.FIRE) )
{
// Flip the box.
checked = !checked;
repaint();
}
// Continue processing the key event.
super.keyPressed( keyCode );
}
/**
* Called when the pointer is pressed.
*
* @param x is the horizontal location where the pointer was pressed
* relative to the top-left corner of the component.
* @param y is the vertical location where the pointer was pressed
* relative to the top-left corner of the component.
*/
public void pointerPressed (int x, int y)
{
// Flip the box.
checked = !checked;
repaint();
// Continue processing the pointer event.
super.pointerPressed( x, y );
}
}
| true |
0152ce6016ecc7f3a46e02a95d27e4b533135b0e | Java | KeefeLaw/Java-MOOC | /week7-week7_04.ThingSuitcaseAndContainer/src/Suitcase.java | UTF-8 | 1,780 | 3.875 | 4 | [] | no_license | import java.util.ArrayList;
import java.util.List;
public class Suitcase {
private List<Thing> things;
private int maxWeight;
public Suitcase(int maxWeight) {
this.things = new ArrayList<Thing>();
this.maxWeight = maxWeight;
}
// Adds Thing to things if it does not exceed maxWeight
public void addThing(Thing thing) {
if (totalWeight() + thing.getWeight() <= maxWeight) {
things.add(thing);
}
}
public String toString() {
if (things.isEmpty()) {
return String.format("empty (0 kg)");
} else if (things.size() == 1) {
return String.format("1 thing (%d kg)", totalWeight());
} else {
// Tests fail with string formatter
//return String.format("%1$s things ($2$d kg)", things.size(), totalWeight());
return things.size() + " things (" + totalWeight() + " kg)";
}
}
// Print all Things in Suitcase
public void printThings() {
for (Thing t : things) {
System.out.println(t);
}
}
// Returns total weight of all Things in Suitcase
public int totalWeight() {
int weight = 0;
for (Thing t : things) {
weight += t.getWeight();
}
return weight;
}
// Returns the heaviest Thing in Suitcase
public Thing heaviestThing() {
if (things.size() == 0) {
return null;
} else {
Thing heaviestThing = things.get(0);
for (int i=1; i<things.size(); i++) {
if (things.get(i).getWeight() > heaviestThing.getWeight()) {
heaviestThing = things.get(i);
}
}
return heaviestThing;
}
}
}
| true |
339f92560cbbebe84518b1be13c5f3070f06bb39 | Java | frankfka/betterplate-android | /app/src/main/java/app/betterplate/betterplate/data/core/Nutrition.java | UTF-8 | 5,085 | 2.5625 | 3 | [] | no_license | package app.betterplate.betterplate.data.core;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Ignore;
import java.io.Serializable;
import java.util.Comparator;
import java.util.LinkedHashMap;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class Nutrition implements Serializable {
private double calories;
private double carbohydrates;
private double protein;
private double fat;
@ColumnInfo(name = "saturated_fat")
private double saturatedFat;
@ColumnInfo(name = "trans_fat")
private double transFat;
private double cholesterol;
private double sodium;
private double fiber;
private double sugar;
@ColumnInfo(name = "vit_a")
private double vitaminA;
@ColumnInfo(name = "vit_c")
private double vitaminC;
private double calcium;
private double iron;
@Ignore
private double healthScore;
public Nutrition(double calories, double carbohydrates, double protein, double fat, double saturatedFat, double transFat, double cholesterol, double sodium, double fiber, double sugar, double vitaminA,
double vitaminC, double calcium, double iron) {
this.calories = calories;
this.carbohydrates = carbohydrates;
this.protein = protein;
this.fat = fat;
this.saturatedFat = saturatedFat;
this.transFat = transFat;
this.cholesterol = cholesterol;
this.sodium = sodium;
this.fiber = fiber;
this.sugar = sugar;
this.vitaminA = vitaminA;
this.vitaminC = vitaminC;
this.calcium = calcium;
this.iron = iron;
}
public LinkedHashMap<String,String> getAvailableNutritionDetails() {
LinkedHashMap<String, String> availableNutritionDetailsMap = new LinkedHashMap<>();
availableNutritionDetailsMap.put("Calories", String.valueOf(this.calories).concat(" Cal"));
availableNutritionDetailsMap.put("Total Fat", String.valueOf(this.fat).concat(" g"));
availableNutritionDetailsMap.put("Saturated Fat", String.valueOf(this.saturatedFat).concat(" g"));
availableNutritionDetailsMap.put("Trans Fat", String.valueOf(this.transFat).concat(" g"));
availableNutritionDetailsMap.put("Cholesterol", String.valueOf(this.cholesterol).concat(" mg"));
availableNutritionDetailsMap.put("Sodium", String.valueOf(this.sodium).concat(" mg"));
availableNutritionDetailsMap.put("Carbohydrates", String.valueOf(this.carbohydrates).concat(" g"));
availableNutritionDetailsMap.put("Fiber", String.valueOf(this.fiber).concat(" g"));
availableNutritionDetailsMap.put("Sugar", String.valueOf(this.sugar).concat(" g"));
availableNutritionDetailsMap.put("Protein", String.valueOf(this.protein).concat(" g"));
availableNutritionDetailsMap.put("Calcium", String.valueOf(this.calcium).concat(" %"));
availableNutritionDetailsMap.put("Iron", String.valueOf(this.iron).concat(" %"));
availableNutritionDetailsMap.put("Vitamin A", String.valueOf(this.vitaminA).concat( "%"));
availableNutritionDetailsMap.put("Vitamin C", String.valueOf(this.vitaminC).concat( "%"));
return availableNutritionDetailsMap;
}
//TODO compile this with stuff in Constants
public static Comparator<Nutrition> SORT_BY_INC_CALS = new Comparator<Nutrition>() {
@Override
public int compare(Nutrition one, Nutrition other) {
double oneCalories = one.getCalories();
double otherCalories = other.getCalories();
return Double.compare(oneCalories, otherCalories);
}
};
public static Comparator<Nutrition> SORT_BY_DEC_PROTEIN = new Comparator<Nutrition>() {
@Override
public int compare(Nutrition one, Nutrition other) {
double oneProtein = one.getProtein();
double otherProtein = other.getProtein();
return Double.compare(otherProtein, oneProtein);
}
};
public static Comparator<Nutrition> SORT_BY_INC_CARBS = new Comparator<Nutrition>() {
@Override
public int compare(Nutrition one, Nutrition other) {
double oneCarbs = one.getCarbohydrates();
double otherCarbs = other.getCarbohydrates();
return Double.compare(oneCarbs, otherCarbs);
}
};
public static Comparator<Nutrition> SORT_BY_INC_FAT = new Comparator<Nutrition>() {
@Override
public int compare(Nutrition one, Nutrition other) {
double oneFat = one.getFat();
double otherFat = other.getFat();
return Double.compare(oneFat, otherFat);
}
};
public static Comparator<Nutrition> SORT_BY_DEC_HEALTH = new Comparator<Nutrition>() {
@Override
public int compare(Nutrition one, Nutrition other) {
double oneHealth = one.getHealthScore();
double otherHealth= other.getHealthScore();
return Double.compare(otherHealth, oneHealth);
}
};
}
| true |
020529f72e0db3063a4966798c6486d754edc9ba | Java | jikeMisma/Data_structure-algorithm | /src/Linkdelist/josepfu.java | GB18030 | 3,569 | 4.125 | 4 | [] | no_license | package Linkdelist;
public class josepfu {
public static void main(String[] args) {
//ԹбʾǷok
CircleSingleLinkedList circleSingleLinkedList=new CircleSingleLinkedList();
circleSingleLinkedList.addBoy(5);//5С
circleSingleLinkedList.showBoy();
System.out.println("~~~~~~~~~~~~~~~~~");
//СȦǷȷ
circleSingleLinkedList.countBoy(1,2,5);
//ȦӦΪ2-4-1-5-3
}
}
//һεĵ
class CircleSingleLinkedList{
//һfirst㣬ǰûб
private Boy first =null;
//С㣬ɻ
public void addBoy(int nums) {
//numsУ
if(nums <1) {
System.out.println("numsֵȷ");
return ;
}
Boy curBoy = null;//ָ룬
//ʹһforѭ
for(int i =1;i<=nums;i++) {
//ݱŴС
Boy boy = new Boy(i);
//ǵһС
if(i ==1) {
first = boy;
first.setNext(first);//ɻװ
curBoy =first;//ָһС
}else {
curBoy.setNext(boy);//
boy.setNext(first);
curBoy = boy;
}
}
}
//ǰ
public void showBoy() {
//жǷΪ
if(first == null) {
System.out.println("Ϊգ");
}
//ΪfirstܶȻʹøָɱ
Boy curBoy = first;
while(true) {
System.out.printf("С%d\n",curBoy.getNo());
if(curBoy.getNext() ==first) {//˵
break;
}
curBoy =curBoy.getNext();//curBoy
}
}
//ûȦ˳
/**
*
* @param startNo ʾӵڼСʼ
* @param countNo ʾ
* @param nums ʾɶСȦ
*/
public void countBoy(int startNo,int countNo,int nums) {
//ȶݽУ
if(first == null ||startNo < 1 || startNo >nums) {
System.out.print("~~~");
return ;
}
//ָ룬СȦ
Boy helper = first;
//һ㣨helperӦָһ
while(true) {
if(helper.getNext() == first) {//˵һ
break ;
}
helper = helper.getNext();
}
//Сǰfirsthelperƶk-1
for(int j =0;j < startNo -1;j++) {
first = first.getNext();
helper = helper.getNext();
}
//Сʱfirsthelperͬʱƶm-1,˺Ȧ
//һѭֱȦֻһ
while(true) {
if(helper == first) {//˵Ȧֻһ
break ;
}
//first helper ͬʱƶcountNum -1
for(int j =0;j < countNo -1;j++) {
first = first.getNext();
helper = helper.getNext();
}
//firstָĽdzȦĽ
System.out.printf("С%dȦ\n",first.getNo());
//firstָСȦ
first = first.getNext();
helper.setNext(first) ;//
}
System.out.printf("ȦСΪ%d",first.getNo());
}
}
//һboy࣬ʾһ
class Boy{
private int no;//
private Boy next;//ָһ㡣Ĭnull
public Boy(int no) {
this.no = no;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public Boy getNext() {
return next;
}
public void setNext(Boy next) {
this.next = next;
}
}
| true |
aa599c45d9b7f9a4938f27e02d1daa5d6ec123a2 | Java | SandeepNadella/Action | /app/src/main/java/com/rekam/action/SensorDBModule.java | UTF-8 | 18,924 | 2.421875 | 2 | [] | no_license | package com.rekam.action;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import androidx.annotation.Nullable;
import com.opencsv.CSVWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Database helper module for creating database, tables, for fetching and setting sensor readings in tables
*
* @author Sandeep Nadella
* @version 1.0
*/
public class SensorDBModule extends SQLiteOpenHelper {
public static String ACCELEROMETER = "accl";
public static String GYROSCOPE = "gyro";
public static String MAGNETOMETER = "mag";
//The column names in the database table
private String ACTION_UID = "action_uid";
private String TIME_STAMP_COL_NAME = "time_stamp";
private String X_VALUE_COL_NAME = "x_value";
private String Y_VALUE_COL_NAME = "y_value";
private String Z_VALUE_COL_NAME = "z_value";
private String ACTION_CLASS = "action_class";
private String ACCL_X_VALUE_COL_NAME = "accl_x_value";
private String ACCL_Y_VALUE_COL_NAME = "accl_y_value";
private String ACCL_Z_VALUE_COL_NAME = "accl_z_value";
private String GYRO_X_VALUE_COL_NAME = "gyro_x_value";
private String GYRO_Y_VALUE_COL_NAME = "gyro_y_value";
private String GYRO_Z_VALUE_COL_NAME = "gyro_z_value";
private String MAG_X_VALUE_COL_NAME = "mag_x_value";
private String MAG_Y_VALUE_COL_NAME = "mag_y_value";
private String MAG_Z_VALUE_COL_NAME = "mag_z_value";
private Context context;
private String tableName;
/**
* Create a helper object to create, open, and/or manage a database.
* This method always returns very quickly. The database is not actually
* created or opened until one of {@link #getWritableDatabase} or
* {@link #getReadableDatabase} is called.
*
* @param context to use to open or create the database
* @param name of the database file, or null for an in-memory database. Can be full path to
* the database file in case its stored on external storage like SDCARD
* @param version number of the database (starting at 1); if the database is older,
* {@link #onUpgrade} will be used to upgrade the database; if the database is
* newer, {@link #onDowngrade} will be used to downgrade the database
*/
public SensorDBModule(@Nullable Context context, @Nullable String name, int version) {
super(context, name, null, version);
this.context = context;
}
@Override
public void onOpen(SQLiteDatabase db) {
db.disableWriteAheadLogging();
super.onOpen(db);
}
/**
* Creates a table with the given name if it doesn't exist
*
* @param tableName
* @param sensorType
*/
public void createTable(String tableName, String sensorType) {
String uthTableName = sensorType + "_" + tableName;
try {
String s = "CREATE TABLE IF NOT EXISTS " + uthTableName + " (" +
ACTION_UID + " REAL, " +
TIME_STAMP_COL_NAME + " REAL, " +
X_VALUE_COL_NAME + " REAL, " +
Y_VALUE_COL_NAME + " REAL, " +
Z_VALUE_COL_NAME + " REAL);";
getWritableDatabase().execSQL(s);
Log.v(MainActivity.TAG, "Database table creation complete");
} catch (SQLException e) {
e.printStackTrace();
Log.e(MainActivity.TAG, "Database table creation failed!");
}
}
/**
* Creates a table with the given name if it doesn't exist
*
* @param tableName
*/
public void createTable(String tableName) {
String uthTableName = tableName;
try {
String s = "CREATE TABLE IF NOT EXISTS " + uthTableName + " (" +
ACCL_X_VALUE_COL_NAME + " REAL, " +
ACCL_Y_VALUE_COL_NAME + " REAL, " +
ACCL_Z_VALUE_COL_NAME + " REAL, " +
GYRO_X_VALUE_COL_NAME + " REAL, " +
GYRO_Y_VALUE_COL_NAME + " REAL, " +
GYRO_Z_VALUE_COL_NAME + " REAL, " +
MAG_X_VALUE_COL_NAME + " REAL, " +
MAG_Y_VALUE_COL_NAME + " REAL, " +
MAG_Z_VALUE_COL_NAME + " REAL, " +
ACTION_CLASS + " REAL)";
getWritableDatabase().execSQL(s);
Log.v(MainActivity.TAG, "Database table creation complete");
} catch (SQLException e) {
e.printStackTrace();
Log.e(MainActivity.TAG, "Database table creation failed!");
}
}
/**
* Drops/deletes the table with the table name used while creating the table
*/
public void delete(String tableName, String sensorType) {
String uthTableName = sensorType + "_" + tableName;
getWritableDatabase().execSQL("DROP TABLE IF EXISTS " + uthTableName);
}
/**
* Insert the sensor reading record into the table
*
* @param tableName
* @param sensorType
*/
public void insert(String tableName, String sensorType, long actionUID, long timeStamp, float xValue, float yValue, float zValue) {
String uthTableName = sensorType + "_" + tableName;
try {
String i = "INSERT INTO " + uthTableName + " VALUES(" + actionUID + ", " + timeStamp + ", " + xValue + ", " + yValue + ", " + zValue + ")";
getWritableDatabase().execSQL(i);
Log.v(MainActivity.TAG, "Database insertion complete");
} catch (Exception e) {
e.printStackTrace();
Log.e(MainActivity.TAG, "Database insertion failed!");
}
}
/**
* Insert the sensor reading record into the table
* 1-cop 2-hungry 3-headache 4-about
*
* @param tableName
*/
public void insert(String tableName, long actionClass, long timeStamp, float accl_xValue, float accl_yValue, float accl_zValue, float gyro_xValue, float gyro_yValue, float gyro_zValue, float mag_xValue, float mag_yValue, float mag_zValue) {
String uthTableName = tableName;
try {
String i = "INSERT INTO " + uthTableName + " VALUES(" + actionClass + ", " + timeStamp + ", " + accl_xValue + ", " + accl_yValue + ", " + accl_zValue + ", " + gyro_xValue + ", " + gyro_yValue + ", " + gyro_zValue + ", " + mag_xValue + ", " + mag_yValue + ", " + mag_zValue + ")";
getWritableDatabase().execSQL(i);
Log.v(MainActivity.TAG, i + "\n Database insertion complete");
} catch (Exception e) {
e.printStackTrace();
Log.e(MainActivity.TAG, "Database insertion failed!");
}
}
/**
* Insert the sensor reading record into the table
* 1-cop 2-hungry 3-headache 4-about
*
* @param tableName
*/
public void insert(String tableName, float accl_xValue, float accl_yValue, float accl_zValue, float gyro_xValue, float gyro_yValue, float gyro_zValue, float mag_xValue, float mag_yValue, float mag_zValue, long actionClass) {
String uthTableName = tableName;
try {
String i = "INSERT INTO " + uthTableName + " VALUES(" + accl_xValue + ", " + accl_yValue + ", " + accl_zValue + ", " + gyro_xValue + ", " + gyro_yValue + ", " + gyro_zValue + ", " + mag_xValue + ", " + mag_yValue + ", " + mag_zValue + ", " + actionClass + ")";
getWritableDatabase().execSQL(i);
Log.v(MainActivity.TAG, i + "\n Database insertion complete");
} catch (Exception e) {
e.printStackTrace();
Log.e(MainActivity.TAG, "Database insertion failed!");
}
}
/**
* Called when the database is created for the first time. This is where the
* creation of tables and the initial population of the tables should happen.
*
* @param db The database.
*/
@Override
public void onCreate(SQLiteDatabase db) {
// NOT needed
}
/**
* Called when the database needs to be upgraded. The implementation
* should use this method to drop tables, add tables, or do anything else it
* needs to upgrade to the new schema version.
*
* <p>
* The SQLite ALTER TABLE documentation can be found
* <a href="http://sqlite.org/lang_altertable.html">here</a>. If you add new columns
* you can use ALTER TABLE to insert them into a live table. If you rename or remove columns
* you can use ALTER TABLE to rename the old table, then create the new table and then
* populate the new table with the contents of the old table.
* </p><p>
* This method executes within a transaction. If an exception is thrown, all changes
* will automatically be rolled back.
* </p>
*
* @param db The database.
* @param oldVersion The old database version.
* @param newVersion The new database version.
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// NOT needed
}
public void deleteTableData(String tableName) {
getWritableDatabase().execSQL("DELETE FROM " + tableName + ";");
}
public void exportDB(String tableName) {
File exportDir = new File(context.getApplicationInfo().dataDir + "//databases//CSV//");
if (!exportDir.exists()) {
exportDir.mkdirs();
}
File file = new File(exportDir, tableName + ".csv");
try {
file.createNewFile();
CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
Cursor curCSV = getReadableDatabase().rawQuery("SELECT * FROM " + tableName, null);
csvWrite.writeNext(curCSV.getColumnNames());
while (curCSV.moveToNext()) {
if (!tableName.equals("Train") && !tableName.equals("Test") && !tableName.equals("Train_Mean_Features") && !tableName.equals("Test_Mean_Features")) {
String[] arrStr = {curCSV.getString(0), String.format("%d", curCSV.getLong(1)), curCSV.getString(2), curCSV.getString(3), curCSV.getString(4)};
csvWrite.writeNext(arrStr);
} else {
String label = "";
if ("0".equals(curCSV.getString(9))) {
label = "noaction";
continue;
} else if ("1".equals(curCSV.getString(9))) {
label = "cop";
} else if ("2".equals(curCSV.getString(9))) {
label = "hungry";
} else if ("3".equals(curCSV.getString(9))) {
label = "headache";
} else if ("4".equals(curCSV.getString(9))) {
label = "about";
} else {
label = "noaction";
continue;
}
String[] arrStr = {curCSV.getString(0), curCSV.getString(1), curCSV.getString(2), curCSV.getString(3), curCSV.getString(4), curCSV.getString(5), curCSV.getString(6), curCSV.getString(7), curCSV.getString(8), label};
csvWrite.writeNext(arrStr);
}
}
csvWrite.close();
curCSV.close();
} catch (Exception e) {
Log.e(MainActivity.TAG, "Error while exporting to CSV. Message: " + e.getMessage(), e);
}
}
public void calculateFeaturesForTrain(String tableName) {
String[] classes = {"0", "1", "2", "3", "4"};
List<String> list = Arrays.asList(classes);
Cursor curCSV = getReadableDatabase().rawQuery("SELECT * FROM " + tableName, null);
String prev = "0";
List<Float> accl_x_value = new ArrayList<>();
List<Float> accl_y_value = new ArrayList<>();
List<Float> accl_z_value = new ArrayList<>();
List<Float> gyro_x_value = new ArrayList<>();
List<Float> gyro_y_value = new ArrayList<>();
List<Float> gyro_z_value = new ArrayList<>();
List<Float> mag_x_value = new ArrayList<>();
List<Float> mag_y_value = new ArrayList<>();
List<Float> mag_z_value = new ArrayList<>();
this.deleteTableData(tableName + "_Mean_Features");
while (curCSV.moveToNext()) {
String class_label = curCSV.getString(9);
if (list.contains(class_label)) {
if (!prev.equals(class_label)) {
Float mean_accl_x = findMean(accl_x_value);
Float mean_accl_y = findMean(accl_y_value);
Float mean_accl_z = findMean(accl_z_value);
Float mean_gyro_x = findMean(gyro_x_value);
Float mean_gyro_y = findMean(gyro_y_value);
Float mean_gyro_z = findMean(gyro_z_value);
Float mean_mag_x = findMean(mag_x_value);
Float mean_mag_y = findMean(mag_y_value);
Float mean_mag_z = findMean(mag_z_value);
this.insert(tableName + "_Mean_Features", mean_accl_x, mean_accl_y, mean_accl_z, mean_gyro_x, mean_gyro_y, mean_gyro_z, mean_mag_x, mean_mag_y, mean_mag_z, Long.valueOf(prev));
accl_x_value.clear();
accl_y_value.clear();
accl_z_value.clear();
gyro_x_value.clear();
gyro_y_value.clear();
gyro_z_value.clear();
mag_x_value.clear();
mag_y_value.clear();
mag_z_value.clear();
accl_x_value.add(curCSV.getFloat(0));
accl_y_value.add(curCSV.getFloat(1));
accl_z_value.add(curCSV.getFloat(2));
gyro_x_value.add(curCSV.getFloat(3));
gyro_y_value.add(curCSV.getFloat(4));
gyro_z_value.add(curCSV.getFloat(5));
mag_x_value.add(curCSV.getFloat(6));
mag_y_value.add(curCSV.getFloat(7));
mag_z_value.add(curCSV.getFloat(8));
} else {
accl_x_value.add(curCSV.getFloat(0));
accl_y_value.add(curCSV.getFloat(1));
accl_z_value.add(curCSV.getFloat(2));
gyro_x_value.add(curCSV.getFloat(3));
gyro_y_value.add(curCSV.getFloat(4));
gyro_z_value.add(curCSV.getFloat(5));
mag_x_value.add(curCSV.getFloat(6));
mag_y_value.add(curCSV.getFloat(7));
mag_z_value.add(curCSV.getFloat(8));
}
prev = class_label;
}
}
}
public void calculateFeaturesForTest(String tableName) {
String[] classes = {"0", "1", "2", "3", "4"};
List<String> list = Arrays.asList(classes);
Cursor curCSV = getReadableDatabase().rawQuery("SELECT * FROM " + tableName, null);
String prev = "0";
List<Float> accl_x_value = new ArrayList<>();
List<Float> accl_y_value = new ArrayList<>();
List<Float> accl_z_value = new ArrayList<>();
List<Float> gyro_x_value = new ArrayList<>();
List<Float> gyro_y_value = new ArrayList<>();
List<Float> gyro_z_value = new ArrayList<>();
List<Float> mag_x_value = new ArrayList<>();
List<Float> mag_y_value = new ArrayList<>();
List<Float> mag_z_value = new ArrayList<>();
this.deleteTableData(tableName + "_Mean_Features");
while (curCSV.moveToNext()) {
String class_label = curCSV.getString(9);
if (list.contains(class_label)) {
if (!prev.equals(class_label)) {
Float mean_accl_x = findMean(accl_x_value);
Float mean_accl_y = findMean(accl_y_value);
Float mean_accl_z = findMean(accl_z_value);
Float mean_gyro_x = findMean(gyro_x_value);
Float mean_gyro_y = findMean(gyro_y_value);
Float mean_gyro_z = findMean(gyro_z_value);
Float mean_mag_x = findMean(mag_x_value);
Float mean_mag_y = findMean(mag_y_value);
Float mean_mag_z = findMean(mag_z_value);
this.insert(tableName + "_Mean_Features", mean_accl_x, mean_accl_y, mean_accl_z, mean_gyro_x, mean_gyro_y, mean_gyro_z, mean_mag_x, mean_mag_y, mean_mag_z, Long.valueOf(prev));
accl_x_value.clear();
accl_y_value.clear();
accl_z_value.clear();
gyro_x_value.clear();
gyro_y_value.clear();
gyro_z_value.clear();
mag_x_value.clear();
mag_y_value.clear();
mag_z_value.clear();
accl_x_value.add(curCSV.getFloat(0));
accl_y_value.add(curCSV.getFloat(1));
accl_z_value.add(curCSV.getFloat(2));
gyro_x_value.add(curCSV.getFloat(3));
gyro_y_value.add(curCSV.getFloat(4));
gyro_z_value.add(curCSV.getFloat(5));
mag_x_value.add(curCSV.getFloat(6));
mag_y_value.add(curCSV.getFloat(7));
mag_z_value.add(curCSV.getFloat(8));
} else {
accl_x_value.add(curCSV.getFloat(0));
accl_y_value.add(curCSV.getFloat(1));
accl_z_value.add(curCSV.getFloat(2));
gyro_x_value.add(curCSV.getFloat(3));
gyro_y_value.add(curCSV.getFloat(4));
gyro_z_value.add(curCSV.getFloat(5));
mag_x_value.add(curCSV.getFloat(6));
mag_y_value.add(curCSV.getFloat(7));
mag_z_value.add(curCSV.getFloat(8));
}
prev = class_label;
}
}
}
private Float findMean(List<Float> list) {
float sum = 0;
for (Float f : list) {
sum += f;
}
return (sum / list.size());
}
public void exportDBs(String[] tableNames) {
File exportDir = new File(context.getApplicationInfo().dataDir + "//databases//CSV//");
if (exportDir.exists()) {
String[] children = exportDir.list();
for (int i = 0; i < children.length; i++) {
new File(exportDir, children[i]).delete();
}
exportDir.mkdirs();
}
for (String table : tableNames) {
exportDB(table);
}
}
}
| true |
c2ed939bdca9d2178f05c68a3202f367a23c06e8 | Java | izydevs/QRBarCodeScanner | /app/src/main/java/com/amit/hexahash/ViewModel/AssetViewModel.java | UTF-8 | 1,881 | 2.1875 | 2 | [] | no_license | package com.amit.hexahash.ViewModel;
import android.app.Application;
import android.arch.lifecycle.AndroidViewModel;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.Observer;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import com.amit.hexahash.Model.Asset;
import com.amit.hexahash.Repository.AssetRepository;
import java.util.ArrayList;
import java.util.List;
public class AssetViewModel extends AndroidViewModel {
private AssetRepository repository;
private LiveData<List<Asset>> myAssetList;
private MutableLiveData<List<Asset>> mySearchAssetList;
public AssetViewModel(@NonNull Application application) {
super(application);
repository = new AssetRepository(application);
myAssetList = repository.getMyAssetDetails();
}
public LiveData<List<Asset>> getMyAssetList() {
if (myAssetList == null) {
myAssetList = new MutableLiveData<>();
}
return myAssetList;
}
public LiveData<List<Asset>> getSearchAssetList() {
if (mySearchAssetList == null) {
mySearchAssetList = new MutableLiveData<>();
}
return mySearchAssetList;
}
public void insertData(Asset asset) {
repository.insertAssetDetail(asset);
}
public void searchAsset(List<String> barCodeValues) {
repository.getSearchAssetDetails(barCodeValues).observeForever(new Observer<List<Asset>>() {
@Override
public void onChanged(@Nullable List<Asset> assets) {
if (assets != null) {
Log.d("asdf", "asset found " + assets);
mySearchAssetList.postValue(assets);
}
}
});
}
}
| true |
48e3eda856facd0c6dfef17037e5f8c44886e456 | Java | MarcelleBond/FIX-ME | /Router/src/main/java/ConnectionHandler.java | UTF-8 | 1,410 | 3.296875 | 3 | [
"MIT"
] | permissive | import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class ConnectionHandler implements Runnable {
private Socket socket = null;
private DataInputStream BrokerInput = null;
private DataOutputStream output = null;
public ConnectionHandler(Socket socket, int id) {
try {
this.socket = socket;
BrokerInput = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
output = new DataOutputStream(socket.getOutputStream());
output.writeUTF(String.valueOf(id));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
try {
String line = "";
// reads message from client until "Over" is sent
while (!line.equals("Over")) {
try {
line = BrokerInput.readUTF();
System.out.println(line);
} catch (IOException i) {
System.out.println(i);
}
}
System.out.println("Closing connection");
// close connection
socket.close();
BrokerInput.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| true |
aaeaf3c72d003d5bde36839cdde234bb5277f8b1 | Java | lauriavictor7/Gerenciador-Hotelaria | /src/dados/DAOFuncionario.java | UTF-8 | 467 | 1.6875 | 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 dados;
import basicas.Funcionario;
import javax.persistence.EntityManagerFactory;
/**
*
* @author lauriavictor
*/
public class DAOFuncionario extends DAOGenerico<Funcionario> {
public DAOFuncionario(EntityManagerFactory emf) {
super(emf);
}
}
| true |
ffafecb78675abf67a59cc69761805478d32d219 | Java | kapulkin/CodeSearching | /src/search_procedures/tests/SumDecompositionTest.java | UTF-8 | 2,311 | 2.75 | 3 | [] | no_license | package search_procedures.tests;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.Assert.*;
import search_tools.SumDecomposition;
public class SumDecompositionTest {
static final private Logger logger = LoggerFactory.getLogger(SumDecompositionTest.class);
@Test
public void sampleFor4By4() {
int sample[][] = new int [][]{
new int [] {4, 0, 0, 0},
new int [] {3, 1, 0, 0},
new int [] {2, 2, 0, 0},
new int [] {2, 1, 1, 0},
new int [] {1, 1, 1, 1}
};
SumDecomposition decomposition = new SumDecomposition(4, 4);
checkDecomposition(sample, decomposition);
}
@Test
public void sampleFor4By3() {
int decompositions[][] = new int [][]{
new int [] {4, 0, 0},
new int [] {3, 1, 0},
new int [] {2, 2, 0},
new int [] {2, 1, 1}
};
SumDecomposition decomposition = new SumDecomposition(4, 3);
checkDecomposition(decompositions, decomposition);
}
@Test
public void sampleFor8By3() {
int decompositions[][] = new int [][]{
new int [] {8, 0, 0},
new int [] {7, 1, 0},
new int [] {6, 2, 0},
new int [] {6, 1, 1},
new int [] {5, 3, 0},
new int [] {5, 2, 1},
new int [] {4, 4, 0},
new int [] {4, 3, 1},
new int [] {4, 2, 2},
new int [] {3, 3, 2}
};
SumDecomposition decomposition = new SumDecomposition(8, 3 );
checkDecomposition(decompositions, decomposition);
}
private void checkDecomposition(int[][] sample, SumDecomposition decomposition) {
logger.debug("number = " + decomposition.getNumber() + ", count = " + decomposition.getSumCount());
for (int i = 0; i < sample.length; ++i) {
assertTrue(decomposition.hasNext());
int items[] = decomposition.next();
logger.debug(i + ": " + arrayToString(items));
assertDeepEquals(sample[i], items);
}
assertFalse(decomposition.hasNext());
}
private void assertDeepEquals(int expected[], int actual[]) {
assertEquals(expected.length, actual.length);
for (int i = 0; i < expected.length; ++i) {
assertEquals(expected[i], actual[i]);
}
}
private String arrayToString(int array[]) {
if (array.length == 0) {
return "[]";
}
String str = "[" + array[0];
for (int i = 1; i < array.length; ++i) {
str += ", " + array[i];
}
str += "]";
return str;
}
}
| true |
6734d7defa2e685dc70436f4681e325c524c83bb | Java | alvaradoblancouribe/youthfulindrescretion | /AWSyouthfulindiscretion/src/test/java/player/handler/CreatePlaylistHandlerTest.java | UTF-8 | 1,340 | 2.328125 | 2 | [] | no_license | package player.handler;
import static org.junit.Assert.*;
import java.io.IOException;
import java.util.UUID;
import org.junit.Assert;
import org.junit.Test;
import com.google.gson.Gson;
import player.db.PlaylistDAO;
import player.handler.CreatePlaylistHandler;
import player.http.PlaylistRequest;
import player.model.Playlist;
import player.http.CreatePlaylistResponse;
public class CreatePlaylistHandlerTest extends LambdaTest{
void testSuccessInput(String incoming) throws IOException {
CreatePlaylistHandler handler = new CreatePlaylistHandler();
PlaylistRequest req = new Gson().fromJson(incoming, PlaylistRequest.class);
CreatePlaylistResponse resp = handler.handleRequest(req, createContext("create"));
Assert.assertEquals(200, resp.httpCode);
}
@Test
public void testShouldBeOk() {
PlaylistDAO dao = new PlaylistDAO();
PlaylistRequest ccr = new PlaylistRequest();
String SAMPLE_INPUT_STRING = new Gson().toJson(ccr);
try {
testSuccessInput(SAMPLE_INPUT_STRING);
dao.deletePlaylist(new Playlist(UUID.fromString(ccr.playlistName)));
} catch (IOException ioe) {
Assert.fail("Invalid: " + ioe.getMessage());
} catch (Exception e) {
Assert.fail("test failed: " + e.getMessage());
}
}
}
| true |
b79b6625321d262dcd5bcfa76ff436a7ac4f604f | Java | freebz/Effective-Java-3-E | /ch12/item_87/code87-2.java | UTF-8 | 335 | 2.375 | 2 | [] | no_license | // 코드 87-2 ㅣㄱ본 직렬화 형태에 적합하지 않은 클래스
public final class StringList implements Serializable {
private int size =0;
private Entry head = null;
private static class Entry impelements Serializable {
String data;
Entry next;
Entry previous;
}
... // 나머지 코드 생략
}
| true |
a62c2e30e9b4893a4cc24884147ce771724dac67 | Java | sbijukchhe/BookAppWithMethod | /src/BookApp.java | UTF-8 | 1,626 | 3.5625 | 4 | [] | no_license | import java.util.List;
import java.util.Scanner;
public class BookApp {
public static void main(String[] args) {
String title;
int numBooks;
String response = "";
Book book = new Book();
BookDatabase bd = new BookDatabase();
List<Book> myBooks = bd.getBooks();
bd.getDisplayText(myBooks);
System.out.println("\n*******************************************************");
System.out.println("Total Price of books in the list : " + bd.getPrice(myBooks));
System.out.println("********************************************************");
Scanner input = new Scanner(System.in);
System.out.println("Do you want to check the price of book? Y/N ");
response = input.nextLine();
while(!(response.equalsIgnoreCase("N"))) {
if (!(response.equalsIgnoreCase("N"))) {
System.out.println("Enter number of books");
numBooks = input.nextInt();
input.nextLine();
System.out.println("Enter book title - Head First Java, Thinking in Java, " +
"OCP: Oracle Certified Professional Java SE, Automate the Boring Stuff with Python");
title = input.nextLine();
double bPrice = numBooks * bd.getBookPrice(title);
System.out.println("Total price now is : " + bPrice);
System.out.println("--------------------------------");
}
System.out.println("\nDo you want to continue? Y/N");
response = input.nextLine();
}
}
}
| true |
1ca432b8078517a2093777137fb3c756c62c93ab | Java | gildurao/cdioil-2017-g003 | /core/src/main/java/cdioil/application/utils/CSVAnswerProbabilityReader.java | UTF-8 | 5,539 | 3.234375 | 3 | [] | no_license | package cdioil.application.utils;
import cdioil.files.FileReader;
import cdioil.files.InvalidFileFormattingException;
import java.io.File;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* Class used for reading Questions' probabilistic distribution functions from a
* .csv file.
*
* @author Antonio Sousa
*/
public class CSVAnswerProbabilityReader implements AnswerProbabilityReader {
/**
* Header used for identifying the row in which the Question's identifier
* values are to be inserted.
*/
private static final String QUESTION_IDENTIFIER = "QuestaoID";
/**
* Header used for identifying the row in which the function type values are
* to be inserted.
*/
private static final String DISTRIBUTION_IDENTIFIER = "TipoDist";
/**
* Header used for identifying the row in which the functions' values are to
* be inserted.
*/
private static final String PARAMETER_IDENTIFIER = "Parametros";
/**
* Index of the line containing all of the row definitions.
*/
private static final int IDENTIFIERS_LINE = 0;
/**
* Character used for splitting columns within the file.
*/
private static final String SPLITTER = ";";
/**
* Character used for splitting the function's values.
*/
private static final String FUNCTION_VALUE_SPLITTER = "=";
/**
* Number of columns expected to exist in the file.
*/
private static final int COLUMN_NUMBER = 3;
/**
* Message displayed if an <code>InvalidFileFormattingException</code>
* occurs.
*/
private static final String UNRECOGNIZED_FILE_FORMAT = "Unrecognized file formatting";
/**
* String identifying the distribution function as a Bernoulli distribution
* function.
*/
private static final String BERNOULLI_DISTRIBUTION = "Bernoulli";
/**
* String identifying the distribution function as a probabilistic
* distribution function.
*/
private static final String PROBABILISTIC_DISTRIBUTION = "FDP";
/**
* File currently being read.
*/
private final File file;
/**
* Creates a new instance of CSVAnswerProbabilityReader for a file with the
* given absolute path.
*
* @param file file being read.
*/
public CSVAnswerProbabilityReader(File file) {
this.file = file;
}
@Override
public Map<String, List<Double>> readProbabilities() {
List<String> fileContent = FileReader.readFile(file);
if (!isFileValid(fileContent)) {
throw new InvalidFileFormattingException(UNRECOGNIZED_FILE_FORMAT);
}
Map<String, List<Double>> result = new LinkedHashMap<>();
for (int i = IDENTIFIERS_LINE + 1; i < fileContent.size(); i++) {
String[] line = fileContent.get(i).trim().split(SPLITTER);
if (line.length == 0) {
continue;
}
String questionID = line[0];
List<Double> distributionValues = new LinkedList<>();
if (line[1].equalsIgnoreCase(BERNOULLI_DISTRIBUTION)) {
distributionValues.addAll(readBernoulliDistribution(line[2]));
} else if (line[1].equalsIgnoreCase(PROBABILISTIC_DISTRIBUTION)) {
distributionValues.addAll(readProbabilisticDistribution(line));
}
result.put(questionID, distributionValues);
}
return result;
}
/**
* Reads values for a Bernoulli function.
*
* @param row row being read
* @return function's list of probabilities
*/
private List<Double> readBernoulliDistribution(String row) {
List<Double> distributionValues = new LinkedList<>();
String[] rowContent = row.split(FUNCTION_VALUE_SPLITTER);
String valueString = rowContent[1];
Double value1 = new Double(valueString);
Double value2 = 1.0 - value1;
distributionValues.add(value1);
distributionValues.add(value2);
return distributionValues;
}
/**
* Reads values for a probabilistic distribution function.
*
* @param row row being read
* @return function's list of probabilities
*/
private List<Double> readProbabilisticDistribution(String[] line) {
List<Double> distributionValues = new LinkedList<>();
for (int i = 2; i < line.length; i++) {
String valueString = line[i].split(FUNCTION_VALUE_SPLITTER)[1];
valueString = valueString.replace("\"", "");
distributionValues.add(new Double(valueString));
}
return distributionValues;
}
/**
* Checks if the file being read is valid.
*
* @param fileContent file's content
* @return true - if the file's content is not null and the number of
* columns matches the expected value.
*/
private boolean isFileValid(List<String> fileContent) {
if (file == null) {
return false;
}
String[] identifierLineContent = fileContent.get(IDENTIFIERS_LINE).split(SPLITTER);
if (identifierLineContent.length != COLUMN_NUMBER) {
return false;
}
return identifierLineContent[0].equalsIgnoreCase(QUESTION_IDENTIFIER)
&& identifierLineContent[1].equalsIgnoreCase(DISTRIBUTION_IDENTIFIER)
&& identifierLineContent[2].equalsIgnoreCase(PARAMETER_IDENTIFIER);
}
}
| true |
6561f990bc9d8b7caa8d3544fbdc469ed4101537 | Java | Abrekov/JavaRushTasks | /2.JavaCore/src/com/javarush/task/task19/task1920/Solution.java | UTF-8 | 1,832 | 3.265625 | 3 | [] | no_license | package com.javarush.task.task19.task1920;
/*
Самый богатый
*/
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader fileReader = new BufferedReader(new FileReader(args[0]));
Map<String, Double> map = new HashMap<>();
while (fileReader.ready()) {
String[] line = fileReader.readLine().split("\\s+");
if (map.containsKey(line[0])) {
map.put(line[0], Double.parseDouble(line[1]) + map.get(line[0]));
} else {
map.put(line[0], Double.parseDouble(line[1]));
}
}
Double[] values = map.values().toArray(new Double[0]);
double maxValue = 0.0;
for (int i = 0; i < values.length - 1; i++) {
if (values[i] > maxValue) {
maxValue = values[i];
}
}
ArrayList<String> names = new ArrayList<>();
for (Map.Entry<String, Double> pair: map.entrySet()) {
String key = pair.getKey();
Double value = pair.getValue();
if (value == maxValue) {
names.add(key);
}
}
for (int i = 0; i < names.size() - 1; i++) {
for (int j = 1; j < names.size(); j++) {
if (names.get(j - 1).compareTo(names.get(j)) > 0) {
String temp = names.get(j);
names.set(j, names.get(j - 1));
names.set(j - 1, temp);
}
}
}
for (String name : names) {
System.out.println(name);
}
fileReader.close();
}
}
| true |
05c24bfb393de57c928bd368e64c920428ba7a8b | Java | FH-Thomas-Herzog/Java | /Semester 4/20150627_hands_on_7/swe-campina-rmi-impl/src/main/java/at/fh/ooe/swe4/campina/rmi/impl/RmiServerImpl.java | UTF-8 | 3,243 | 2.5625 | 3 | [] | no_license | package at.fh.ooe.swe4.campina.rmi.impl;
import java.rmi.AlreadyBoundException;
import java.rmi.NotBoundException;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import org.apache.log4j.Logger;
import at.fh.ooe.swe4.campina.rmi.api.rmi.RmiServer;
/**
* This is the RMI server implementation.
*
* @author Thomas Herzog <thomas.herzog@students.fh-hagenberg.at>
* @date Jun 15, 2015
*/
public class RmiServerImpl implements RmiServer {
private static final long serialVersionUID = 164219497553939223L;
private Registry serviceRegistry = null;
private int port;
private Set<String> registeredServiceNames = new HashSet<>();
private static final Logger log = Logger.getLogger(RmiServerImpl.class);
/**
* @param port
* the prot to host the beans on.
*/
public RmiServerImpl(int port) {
if ((port <= 1024) || (port >= 65535)) {
throw new IllegalArgumentException("port is invalid: " + port);
}
this.port = port;
}
@Override
public void start() throws RemoteException {
if (serviceRegistry != null) {
throw new IllegalStateException("The rmi server is already started");
}
log.info("Starting service regsitry on: 'rmi://localhost:" + port + "'");
serviceRegistry = LocateRegistry.createRegistry(port);
log.info("Service regsitry registered");
}
@Override
public void stop() throws RemoteException {
if (serviceRegistry == null) {
throw new IllegalStateException("The rmi server is not started");
}
try {
for (String name : registeredServiceNames) {
serviceRegistry.unbind(name);
log.info("Service '" + name + "' unbound");
}
} catch (NotBoundException e) {
throw new IllegalStateException("Should not happen :(");
}
serviceRegistry = null;
port = -1;
registeredServiceNames.clear();
}
@Override
public <T extends Remote> void bindBean(T service, Class<T> interfaceClazz) throws RemoteException {
Objects.requireNonNull(service);
Objects.requireNonNull(interfaceClazz);
final String name = interfaceClazz.getSimpleName();
if (registeredServiceNames.contains(name)) {
log.info("Service '" + name + "' will get bound");
}
try {
Remote rmiService = service;
if (!(service instanceof UnicastRemoteObject)) {
rmiService = UnicastRemoteObject.exportObject(service, port);
}
serviceRegistry.bind(name, rmiService);
registeredServiceNames.add(name);
} catch (AlreadyBoundException e) {
throw new IllegalStateException("Should not happen :(");
}
}
@Override
public <T extends Remote> void unbindBean(final Class<T> interfaceClazz) throws RemoteException {
Objects.requireNonNull(interfaceClazz);
if (registeredServiceNames.contains(interfaceClazz.getSimpleName())) {
log.info("Unbind Service: " + interfaceClazz.getName() + "");
try {
serviceRegistry.unbind(interfaceClazz.getSimpleName());
} catch (NotBoundException e) {
throw new IllegalStateException("Should not happen :(");
}
}
}
}
| true |
7cf28fcd2ba34c990d0b3f112b55e5076a49aa16 | Java | TernenceChen/OnePlusNews | /app/src/main/java/com/example/oneplus/opnew/util/ParseJsonUtils.java | UTF-8 | 2,127 | 2.296875 | 2 | [
"Apache-2.0"
] | permissive | package com.example.oneplus.opnew.util;
import android.util.Log;
import com.example.oneplus.opnew.bean.NewsListNormalBean;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class ParseJsonUtils {
private ArrayList<NewsListNormalBean.ResultBean.DataBean> mNewsListNormalBeanList = new ArrayList<>();
public ArrayList<NewsListNormalBean.ResultBean.DataBean> parseJson(String response) {
try {
if (response != null){
JSONObject jsonObjs = new JSONObject(response).getJSONObject("result");
JSONArray data = jsonObjs.optJSONArray("data");
final int itemCounts = data.length();
Log.i("out---------->", "" + itemCounts);
List<NewsListNormalBean.ResultBean.DataBean> tempList = new ArrayList<>();
for (int i = 0; i < itemCounts; i++) {
Log.i("out----------> i = ", "" + i);
JSONObject jsonObj = data.getJSONObject(i);
NewsListNormalBean.ResultBean.DataBean dataBean = new NewsListNormalBean.ResultBean.DataBean();
Log.i("out---------->", jsonObj.getString("title"));
dataBean.setTitle(jsonObj.getString("title"));
Log.i("out---------->", jsonObj.getString("author_name"));
dataBean.setAuthor_name(jsonObj.getString("author_name"));
dataBean.setDate(jsonObj.getString("date"));
dataBean.setUrl(jsonObj.getString("url"));
dataBean.setThumbnail_pic_s(jsonObj.getString("thumbnail_pic_s"));
dataBean.setThumbnail_pic_s02(jsonObj.optString("thumbnail_pic_s02", null));
dataBean.setThumbnail_pic_s03(jsonObj.optString("thumbnail_pic_s03", null));
tempList.add(dataBean);
}
mNewsListNormalBeanList.addAll(tempList);
}
} catch (Exception e) {
e.printStackTrace();
}
return mNewsListNormalBeanList;
}
}
| true |
6de8fa6a713451394eebe3cce3f076f348deed97 | Java | open-o/sdno-l2vpn | /model/src/main/java/org/openo/sdno/model/servicemodel/tp/CeTp.java | UTF-8 | 3,284 | 1.703125 | 2 | [
"CC-BY-4.0",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | permissive | /*
* Copyright 2016 Huawei Technologies Co., Ltd.
*
* 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.openo.sdno.model.servicemodel.tp;
import java.util.List;
import org.openo.sdno.model.common.NVString;
import org.openo.sdno.wanvpn.util.paradesc.ContainerSizeDesc;
import org.openo.sdno.wanvpn.util.paradesc.IPDesc;
import org.openo.sdno.wanvpn.util.paradesc.StringDesc;
import org.openo.sdno.model.servicemodel.AbstractSvcModel;
/**
* The service model class of CeTp.<br>
*
* @author
* @version SDNO 0.5 2016-6-6
*/
public class CeTp extends AbstractSvcModel {
@StringDesc(pattern = "[a-zA-Z0-9\\-\\_]{1,36}")
private String uuid;
@StringDesc(pattern = "[a-zA-Z0-9\\-\\_]{1,36}")
private String ceID;
@StringDesc(pattern = "[a-zA-Z0-9\\-\\_]{1,36}")
private String ceDirectNeID;
@StringDesc(pattern = "[a-zA-Z0-9\\-\\_]{1,36}")
private String ceDirectTPID;
// the customer site
@StringDesc(maxLen = 200)
private String siteName;
// CE device name
@StringDesc(maxLen = 200)
private String ceName;
@IPDesc(hasMask = false)
private String ceIfmasterIp;
@StringDesc(maxLen = 200)
private String location;
@ContainerSizeDesc(maxSize = 1000)
private List<NVString> addtionalInfo;
public String getCeDirectNeID() {
return ceDirectNeID;
}
public void setCeDirectNeID(String ceDirectNeID) {
this.ceDirectNeID = ceDirectNeID;
}
public String getCeDirectTPID() {
return ceDirectTPID;
}
public void setCeDirectTPID(String ceDirectTPID) {
this.ceDirectTPID = ceDirectTPID;
}
public String getSiteName() {
return siteName;
}
public void setSiteName(String siteName) {
this.siteName = siteName;
}
public String getCeName() {
return ceName;
}
public void setCeName(String ceName) {
this.ceName = ceName;
}
public String getCeIfmasterIp() {
return ceIfmasterIp;
}
public void setCeIfmasterIp(String ceIfmasterIp) {
this.ceIfmasterIp = ceIfmasterIp;
}
@Override
public String getUuid() {
return uuid;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public List<NVString> getAddtionalInfo() {
return addtionalInfo;
}
@Override
public void setUuid(final String uuid) {
this.uuid = uuid;
}
public void setAddtionalInfo(final List<NVString> addtionalInfo) {
this.addtionalInfo = addtionalInfo;
}
public String getCeID() {
return ceID;
}
public void setCeID(String ceID) {
this.ceID = ceID;
}
}
| true |
7a27afb285cbd30b20478fd4848fe6e9cb9561aa | Java | mps4dev/kodilla-tai | /src/main/java/pl/mps/kodilla/inheritance/Programmer.java | UTF-8 | 158 | 2.359375 | 2 | [] | no_license | package pl.mps.kodilla.inheritance;
public class Programmer extends Job {
public Programmer(int salary) {
super(salary, "programming");
}
}
| true |
3b8212d3d84c586c345da2fd214f79ece72e34ea | Java | zhangji92/PointerTrip | /app/src/main/java/yc/pointer/trip/bean/TaskBean.java | UTF-8 | 3,138 | 2.46875 | 2 | [] | no_license | package yc.pointer.trip.bean;
import java.util.List;
import yc.pointer.trip.base.BaseBean;
/**
* Created by 张继
* 2018/9/25
* 10:59
* 公司:
* 描述:
*/
public class TaskBean extends BaseBean{
/**
* data : [{"pic":"/Uploads/1514282498057.png","nickname":"Button","money":"0.20"}]
* user : {"money":"0","num":"0","end_time":1725,"type":0,"pic":"/Images/task_zan.png","tips":"温馨提示:每条视频仅可获取一次点赞收益,用户需在当天任务结束后24点之前手动领取相应收益,次日当前收益将清零。"}
*/
private UserBean user;
private List<DataBean> data;
public UserBean getUser() {
return user;
}
public void setUser(UserBean user) {
this.user = user;
}
public List<DataBean> getData() {
return data;
}
public void setData(List<DataBean> data) {
this.data = data;
}
public static class UserBean {
/**
* money : 0
* num : 0
* end_time : 1725
* type : 0
* pic : /Images/task_zan.png
* tips : 温馨提示:每条视频仅可获取一次点赞收益,用户需在当天任务结束后24点之前手动领取相应收益,次日当前收益将清零。
*/
private String money;
private String num;
private int end_time;
private int type;
private String pic;
private String tips;
public String getMoney() {
return money;
}
public void setMoney(String money) {
this.money = money;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
public int getEnd_time() {
return end_time;
}
public void setEnd_time(int end_time) {
this.end_time = end_time;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
public String getTips() {
return tips;
}
public void setTips(String tips) {
this.tips = tips;
}
}
public static class DataBean {
/**
* pic : /Uploads/1514282498057.png
* nickname : Button
* money : 0.20
*/
private String pic;
private String nickname;
private String money;
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getMoney() {
return money;
}
public void setMoney(String money) {
this.money = money;
}
}
}
| true |
b53fa55eb8fd6b4298b1bdd7703c4ba0b25df71d | Java | Trav1sT/tp | /src/main/java/chopchop/model/recipe/RecipeBook.java | UTF-8 | 2,914 | 3.203125 | 3 | [
"MIT"
] | permissive | package chopchop.model.recipe;
import static java.util.Objects.requireNonNull;
import java.util.List;
import javafx.collections.ObservableList;
public class RecipeBook implements ReadOnlyRecipeBook {
private final UniqueRecipeList entries;
public RecipeBook() {
entries = new UniqueRecipeList();
}
/**
* Creates an AddressBook using the Ingredients in the {@code toBeCopied}
*/
public RecipeBook(ReadOnlyRecipeBook toBeCopied) {
this();
resetData(toBeCopied);
}
//// list overwrite operations
/**
* Replaces the contents of the person list with {@code persons}.
* {@code persons} must not contain duplicate persons.
*/
public void setFoodEntries(List<Recipe> entries) {
this.entries.setRecipeEntries(entries);
}
/**
* Resets the existing data of this {@code AddressBook} with {@code newData}.
*/
public void resetData(ReadOnlyRecipeBook newData) {
requireNonNull(newData);
setFoodEntries(newData.getFoodEntryList());
}
/**
* Returns true if a person with the same identity as {@code person} exists in the address book.
*/
public boolean hasRecipe(Recipe entry) {
requireNonNull(entry);
return entries.contains(entry);
}
/**
* Adds a recipe to the recipe book.
* The recipe must not already exist in the recipe book.
*/
public void addRecipe(Recipe r) {
entries.add(r);
}
/**
* Replaces the given person {@code target} in the list with {@code editedPerson}.
* {@code target} must exist in the address book.
* The person identity of {@code editedPerson} must not be the same as another existing person in the address book.
*/
public void setRecipe(Recipe target, Recipe editedRecipe) {
requireNonNull(editedRecipe);
entries.setRecipe(target, editedRecipe);
}
/**
* Removes {@code key} from this {@code RecipeBook}.
* {@code key} must exist in the recipe book.
*/
public void removeRecipe(Recipe key) {
entries.remove(key);
}
//// util methods
@Override
public String toString() {
return entries.asUnmodifiableObservableList().size() + " persons";
// TODO: refine later
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof RecipeBook // instanceof handles nulls
&& entries.equals(((RecipeBook) other).entries));
}
@Override
public int hashCode() {
return entries.hashCode();
}
/**
* Returns an unmodifiable view of the recipes list.
* This list will not contain any duplicate recipes.
*/
@Override
public ObservableList<Recipe> getFoodEntryList() {
return entries.asUnmodifiableObservableList();
}
}
| true |
b72be519694d77ea538ffffa4a546b755c44ebdf | Java | rachit-goyal/CrimeMukhbir | /app/src/main/java/in/aaaonlineservice/crimemukhbir/VideoYou.java | UTF-8 | 12,851 | 1.820313 | 2 | [] | no_license | package in.aaaonlineservice.crimemukhbir;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.android.material.snackbar.Snackbar;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class VideoYou extends AppCompatActivity {
private ProgressDialog dialog;
String status;
LinearLayout noint;
TextView nointernet;
protected Handler handler;
Toolbar toolbar;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
DataAdapyouind adapter;
TextView nocon;
ArrayList<res> videoDetailsArrayList;
String url="https://www.googleapis.com/youtube/v3/search?part=snippet,id&order=date&channelId=UCEqcabBRv-aNwS8Wh-aoygw&maxResults=10&key=AIzaSyBLmodWQE2fYs2wqa_k03PIQ2yJrJiuff0";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_video_you);
videoDetailsArrayList=new ArrayList<>();
nocon=(TextView)findViewById(R.id.noccon);
toolbar = (Toolbar) findViewById(R.id.toolbar);
recyclerView=(RecyclerView)findViewById(R.id.recyle);
noint=(LinearLayout)findViewById(R.id.noint);
handler = new Handler();
nointernet=(TextView)findViewById(R.id.noin);
if (recyclerView != null) {
recyclerView.setHasFixedSize(true);
}
layoutManager = new LinearLayoutManager(VideoYou.this);
recyclerView.setLayoutManager(layoutManager);
dialog = new ProgressDialog(VideoYou.this);
if (isNetworkAvailable()) {
loadData();
} else {
Toast.makeText(VideoYou.this, "No Network", Toast.LENGTH_SHORT).show();
}
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
}
private void loadData() {
getdata();
}
private void getdata() {
dialog.setMessage("Please Wait...");
dialog.setCancelable(false);
dialog.show();
StringRequest str=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
dialog.dismiss();
try {
JSONObject jsonObject=new JSONObject(response);
if (jsonObject.has("nextPageToken")) {
status = jsonObject.getString("nextPageToken");
}
else{
status=null;
}
JSONArray jsonArray=jsonObject.getJSONArray("items");
if(jsonArray.length()==0){
nocon.setVisibility(View.VISIBLE);
}
else{
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
JSONObject jsonVideoId=jsonObject1.getJSONObject("id");
JSONObject jsonsnippet= jsonObject1.getJSONObject("snippet");
JSONObject jsonObjectdefault = jsonsnippet.getJSONObject("thumbnails").getJSONObject("medium");
res videoDetails=new res();
String vvv=jsonVideoId.getString("kind");
if(vvv.equals("youtube#video")){
String videoid = jsonVideoId.getString("videoId");
videoDetails.setUrl(jsonObjectdefault.getString("url"));
videoDetails.setVideoName(jsonsnippet.getString("title"));
videoDetails.setVideoDesc(jsonsnippet.getString("description"));
videoDetails.setVideoId(videoid);
videoDetailsArrayList.add(videoDetails);
}
}
}
adapter = new DataAdapyouind(videoDetailsArrayList, recyclerView);
// set the adapter object to the Recyclerview
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
adapter.setOnLoadMoreListener(new OnLoadMoreListener() {
@Override
public void onLoadMore() {
if(isNetworkAvailable()){
if(status!=null){
videoDetailsArrayList.add(null);
adapter.notifyItemInserted(videoDetailsArrayList.size() - 1);
handler.postDelayed(new Runnable() {
@Override
public void run() {
String urr="https://www.googleapis.com/youtube/v3/search?pageToken="+status+"&part=snippet,id&order=date&channelId=UCEqcabBRv-aNwS8Wh-aoygw&maxResults=10&key=AIzaSyBLmodWQE2fYs2wqa_k03PIQ2yJrJiuff0";
StringRequest stringRequest=new StringRequest(Request.Method.GET, urr, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
videoDetailsArrayList.remove(videoDetailsArrayList.size() - 1);
adapter.notifyItemRemoved(videoDetailsArrayList.size());
JSONObject jsonObject= null;
try {
jsonObject = new JSONObject(response);
if (jsonObject.has("nextPageToken")) {
status = jsonObject.getString("nextPageToken");
}
else{
status=null;
}
JSONArray jsonArray=jsonObject.getJSONArray("items");
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
JSONObject jsonVideoId=jsonObject1.getJSONObject("id");
JSONObject jsonsnippet= jsonObject1.getJSONObject("snippet");
JSONObject jsonObjectdefault = jsonsnippet.getJSONObject("thumbnails").getJSONObject("medium");
res videoDetails=new res();
String vvv=jsonVideoId.getString("kind");
if(vvv.equals("youtube#video")){
String videoid = jsonVideoId.getString("videoId");
videoDetails.setUrl(jsonObjectdefault.getString("url"));
videoDetails.setVideoName(jsonsnippet.getString("title"));
videoDetails.setVideoDesc(jsonsnippet.getString("description"));
videoDetails.setVideoId(videoid);
videoDetailsArrayList.add(videoDetails);
}
}
adapter.notifyItemInserted(videoDetailsArrayList.size());
} catch (JSONException e) {
e.printStackTrace();
}
adapter.setLoaded();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Snackbar.make(VideoYou.this.findViewById(android.R.id.content),
"Some error occurred.Please try after some time.", Snackbar.LENGTH_LONG).show();
}
});
AppController.getInstance().addToRequestQueue(stringRequest);
}
},2000);
}
else{
Snackbar.make(VideoYou.this.findViewById(android.R.id.content),
"No more content to show", Snackbar.LENGTH_LONG).show();
}
}
else{
videoDetailsArrayList.remove(videoDetailsArrayList.size() - 1);
adapter.notifyItemRemoved(videoDetailsArrayList.size());
noint.setVisibility(View.VISIBLE);
nointernet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(isNetworkAvailable()){
noint.setVisibility(View.GONE);
onLoadMore();
}
}
});
}
}
});
Log.d("videoDetailsArrayList", String.valueOf(videoDetailsArrayList.size()));
// create an Object for Adapter
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
Snackbar.make(VideoYou.this.findViewById(android.R.id.content),
"Some error occurred.Please try after some time.", Snackbar.LENGTH_LONG).show();
}
});
AppController.getInstance().addToRequestQueue(str);
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) VideoYou.this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
| true |
8b0dbf2becb92b8ba2957c398cc451a364246ba8 | Java | minileopard/CodeForJob2020 | /src/companytest/hw_525.java | UTF-8 | 1,350 | 3.203125 | 3 | [] | no_license | package companytest;
import java.util.Arrays;
public class hw_525 {
public static void main(String[] args) {
int[] nums = {5,7,7,8,8,8,8,10};
int target = 8;
hw_525 h = new hw_525();
System.out.println(Arrays.toString(h.searchRange(nums,target)));
}
public int[] searchRange(int[] nums, int target)
{
int[] res = {-1, -1};
if(nums == null || target < nums[0] || target > nums[nums.length-1])
{
return res;
}
int index = search(nums, target);
if(index == -1)
return res;
int left = index, right = index;
while(left >= 0 && nums[left] == target)
{
left--;
}
while(right < nums.length && nums[right] == target)
{
right++;
}
res[0] = left + 1;
res[1] = right - 1;
return res;
}
public int search(int[] nums, int target)
{
int left = 0, right = nums.length - 1;
while(left <= right)
{
int mid = (left + right) / 2;
if(nums[mid] == target)
return mid;
else if(nums[mid] > target)
{
right = mid - 1;
}else
{
left = mid + 1;
}
}
return -1;
}
}
| true |
75b76738b6fd31e33a7b327f77099b9895d5845b | Java | Abhishek-Shrivastav/mentor-on-demand | /mentro-on-demand/mentorondemand/src/main/java/com/mentorondemand/controller/SearchController.java | UTF-8 | 2,293 | 2.125 | 2 | [] | no_license | package com.mentorondemand.controller;
import java.util.LinkedList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.mentorondemand.entity.MentorSkill;
import com.mentorondemand.entity.MentorSlot;
import com.mentorondemand.entity.Search;
import com.mentorondemand.entity.SearchList;
import com.mentorondemand.entity.SkillList;
import com.mentorondemand.entity.SlotList;
import com.mentorondemand.entity.Technology;
import com.mentorondemand.entity.StatusResponse;
import com.mentorondemand.entity.User;
@RestController
@RequestMapping("/search")
public class SearchController {
@Autowired
private RestTemplate restTemp;
@RequestMapping("/{techId}")
public SearchList searchById(@PathVariable("techId") Integer techId)
{
List<Search> search = new LinkedList<Search>();
SkillList skillList = restTemp.getForObject("http://MENTOR-SKILL/mentorskill/getMentorSkillByTechId/"+techId,SkillList.class);
List<MentorSkill> skills = skillList.getListSkill();
for(MentorSkill skill : skills) {
Technology tech = restTemp.getForObject("http://TECHNOLOGY/technology/getById/"+skill.getTechnologyId(),Technology.class);
User user = restTemp.getForObject("http://USER/user/getById/"+skill.getMentorId(),User.class);
SlotList slotList = restTemp.getForObject("http://MENTOR-SLOT/mentorslot/getByMentorId/"+skill.getMentorId(),SlotList.class);
List<MentorSlot> slots = slotList.getListSlot();
for(MentorSlot slot : slots) {
StatusResponse status = restTemp.getForObject("http://TRAINING/training/checkSlot/"+slot.getId(),StatusResponse.class);
if(status.getStatus())
{
search.add(new Search(user.getId(),user.getFirstName(),user.getLastName(),user.getYearOfExp(),user.getLinkedInUrl(),tech.getId(),tech.getTechnologyName(),skill.getId(),skill.getToc(),skill.getPrerequisites(),skill.getFee(),slot.getId(),slot.getTimeFrom(),slot.getTimeTo()));
}
}
}
SearchList searchList = new SearchList(search);
return searchList;
}
}
| true |
d82bb69c5ab923b91dae8a2344aacb2659fb58ac | Java | z589533/http-coroutines | /src/main/java/org/coroutines/tool/http/support/builder/HttpClientBuilder.java | UTF-8 | 3,413 | 2.328125 | 2 | [] | no_license | package org.coroutines.tool.http.support.builder;
import org.coroutines.tool.http.support.HttpCoroutinesClient;
/**
* @Project:http-coroutines
* @PackageName:org.coroutines.tool.http.support.builder
* @Author:null z
* @DateTime:2017-09-03 20:23.
*/
public class HttpClientBuilder {
public static HttpClientBuilder create() {
return new HttpClientBuilder();
}
private int maxTotal = 10;
private int maxpPerroute = 5;
private int executionCountHttp = 0;
/**
* *返回请求连接时使用的超时(毫秒)
* *从连接管理器。 解释超时值为零
* *作为无限超时。
* *
* <p>
* <p>
* *超时值为零被解释为无限超时。
* *负值解释为未定义(系统默认值)。
* * p>
* *
* <p>
* <p>
* *默认值:`-1`
* * p>
*
*/
private int requestTimeout = -1;
/**
* *定义套接字超时(`SO_TIMEOUT`),单位为毫秒,
* *这是等待数据的超时时间,换句话说,
* *两个连续数据包之间的最长时间不活动)。
* *
* <p>
* <p>
* *超时值为零被解释为无限超时。
* *负值解释为未定义(系统默认值)。
* * p>
* *
* <p>
* <p>
* *默认值:`-1`
* * p>
*
*/
private int socketTimeout = -1;//
/**
* *确定连接建立之前的超时时间(以毫秒为单位)。
* *超时值为零被解释为无限超时。
* *
* <p>
* <p>
* *超时值为零被解释为无限超时。
* *负值解释为未定义(系统默认值)。
* * p>
* *
* <p>
* <p>
* *默认值:`-1`
* * p>
*
*/
private int connectTimeout = -1;//
public int getMaxTotal() {
return maxTotal;
}
public void setMaxTotal(int maxTotal) {
this.maxTotal = maxTotal;
}
public int getMaxpPerroute() {
return maxpPerroute;
}
public void setMaxpPerroute(int maxpPerroute) {
this.maxpPerroute = maxpPerroute;
}
public int getExecutionCountHttp() {
return executionCountHttp;
}
public void setExecutionCountHttp(int executionCountHttp) {
this.executionCountHttp = executionCountHttp;
}
public int getRequestTimeout() {
return requestTimeout;
}
public void setRequestTimeout(int requestTimeout) {
this.requestTimeout = requestTimeout;
}
public int getSocketTimeout() {
return socketTimeout;
}
public void setSocketTimeout(int socketTimeout) {
this.socketTimeout = socketTimeout;
}
public int getConnectTimeout() {
return connectTimeout;
}
public void setConnectTimeout(int connectTimeout) {
this.connectTimeout = connectTimeout;
}
public HttpCoroutinesClient build() {
return new HttpCoroutinesClient(maxTotal, maxpPerroute, executionCountHttp, requestTimeout, connectTimeout, socketTimeout);
}
}
| true |
84a129903dd6e0c57a41925c00f47ea751434066 | Java | thumb-tack/tt | /core/websockets/src/main/java/io/thorntail/websockets/WebSocketMetaData.java | UTF-8 | 309 | 1.984375 | 2 | [
"Apache-2.0"
] | permissive | package io.thorntail.websockets;
/**
* Created by bob on 4/13/18.
*/
public class WebSocketMetaData {
public WebSocketMetaData(Class<?> endpoint) {
this.endpoint = endpoint;
}
public Class<?> getEndpoint() {
return this.endpoint;
}
private final Class<?> endpoint;
}
| true |
b859490c9403418b889cd01ed3cc517dd0882290 | Java | sfu-cl-lab/exception-mining | /BayesBaseNew/src/edu2/cmu/tetrad/search/TestGraphConverter.java | UTF-8 | 3,541 | 2.578125 | 3 | [] | no_license | ///////////////////////////////////////////////////////////////////////////////
// For information as to what this class does, see the Javadoc, below. //
// Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, //
// 2007, 2008, 2009, 2010 by Peter Spirtes, Richard Scheines, Joseph Ramsey, //
// and Clark Glymour. //
// //
// 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. //
// //
// 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 edu.cmu.tetrad.search;
import edu.cmu.tetrad.graph.*;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Tests the GraphConverter class.
*
* @author Joseph Ramsey
*/
public class TestGraphConverter extends TestCase {
/**
* Standard constructor for JUnit test cases.
*/
public TestGraphConverter(String name) {
super(name);
}
/**
* Contructs a graph the long way and using the string spec converter and compares them.
*/
public void testStringSpecConverter() {
// Set up graph and node objects.
Graph graph = new EdgeListGraph();
Node x1 = new GraphNode("X1");
Node x2 = new GraphNode("X2");
Node x3 = new GraphNode("X3");
Node x4 = new GraphNode("X4");
Node x5 = new GraphNode("X5");
// Construct graph from nodes.
graph.addNode(x1);
graph.addNode(x2);
graph.addNode(x3);
graph.addNode(x4);
graph.addNode(x5);
graph.addDirectedEdge(x1, x2);
graph.addUndirectedEdge(x1, x3);
graph.addBidirectedEdge(x2, x4);
graph.addPartiallyOrientedEdge(x3, x4);
graph.addDirectedEdge(x1, x5);
graph.addNondirectedEdge(x5, x2);
graph.addPartiallyOrientedEdge(x3, x5);
Graph convertedGraph = GraphConverter.convert(
"X1-->X2,X1---X3,X2<->X4,X3o->X4," + "X5<--X1,X5o-oX2,X5<-oX3");
//
// System.out.println(graph);
// System.out.println(convertedGraph);
assertTrue(graph.equals(convertedGraph));
}
/**
* This method uses reflection to collect up all of the test methods from this class and return them to the test
* runner.
*/
public static Test suite() {
// Edit the name of the class in the parens to match the name
// of this class.
return new TestSuite(TestGraphConverter.class);
}
}
| true |
08fbbf67a38b51aff3767a693100f66541afd6de | Java | SebastianCelejewski/determine_car_speed_from_dashcam_video | /src/main/java/pl/sebcel/csfdv/gui/MainFrame.java | UTF-8 | 1,538 | 2.6875 | 3 | [] | no_license | package pl.sebcel.csfdv.gui;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
/**
* Main application window
*/
@Singleton
public class MainFrame extends JFrame {
@Inject
private MainMenu mainMenu;
@Inject
private NavigationPanel navigationPanel;
@Inject
private FrameDisplay frameDisplay;
@Inject
private DataPanel dataPanel;
@Inject
private ResultsTable resultsTable;
@Inject
private ResultsChart resultsChart;
@PostConstruct
public void initialize() {
this.setTitle("Determine car speed from dashcam video");
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
JPanel infoPanel = new JPanel();
infoPanel.setLayout(new BoxLayout(infoPanel, BoxLayout.Y_AXIS));
infoPanel.add(navigationPanel);
infoPanel.add(dataPanel);
JPanel viewPanel = new JPanel();
viewPanel.setLayout(new BoxLayout(viewPanel, BoxLayout.X_AXIS));
viewPanel.add(frameDisplay);
viewPanel.add(resultsTable);
viewPanel.add(resultsChart);
this.setLayout(new BorderLayout());
this.setJMenuBar(mainMenu);
this.add(infoPanel, BorderLayout.NORTH);
this.add(viewPanel, BorderLayout.CENTER);
}
} | true |
29ab49525ad4878e0964b0c2eb9fd9a62a805227 | Java | azkayasin/PBKK-Restaurant | /src/main/java/com/packtpub/dao/UserDAO.java | UTF-8 | 3,794 | 2.375 | 2 | [] | no_license | package com.packtpub.dao;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.packtpub.model.User;
import com.packtpub.repository.UserRepository;
@Service
public class UserDAO {
@Autowired
UserRepository userRepository;
public User save(User usr) {
return userRepository.save(usr);
}
public List<User> findAll()
{
return userRepository.findAll();
}
public User findById(Integer id)
{
User usr=userRepository.findByIduser(id);
if(usr!=null)
{
return new User(usr.getId(),usr.getName(),usr.getUserName(),usr.getRole(),usr.getStatus(),usr.getEmail());
}
return null;
}
public List<User> findCustomer(Integer id)
{
List <User> customers=new ArrayList<User>();
if(id!=null)
{
User usr=userRepository.findByIduser(id);
if(usr!=null&&usr.getRole()==1)
{
customers.add(new User(usr.getId(),usr.getName(),usr.getUserName(),usr.getRole(),usr.getStatus(),usr.getEmail()));
}
}
else
{
List<User> getCustomers=userRepository.findCustomer();
if(getCustomers!=null)
{
for(User usr:getCustomers)
{
customers.add(new User(usr.getId(),usr.getName(),usr.getUserName(),usr.getRole(),usr.getStatus(),usr.getEmail()));
}
}
}
return customers;
}
public List<User> findRestaurant(Integer id)
{
List <User> restaurants=new ArrayList<User>();
if(id!=null)
{
User usr=userRepository.findByIduser(id);
if(usr!=null&&usr.getRole()==2)
{
restaurants.add(new User(usr.getId(),usr.getName(),usr.getUserName(),usr.getRole(),usr.getStatus(),usr.getEmail()));
}
}
else
{
List<User> getCustomers=userRepository.findRestaurant();
if(getCustomers!=null)
{
for(User usr:getCustomers)
{
restaurants.add(new User(usr.getId(),usr.getName(),usr.getUserName(),usr.getRole(),usr.getStatus(),usr.getEmail()));
}
}
}
return restaurants;
}
public User login(String email,String password)
{
User user=userRepository.findByEmailandPassword(email, DigestUtils.sha256Hex(password));
if(user==null)
{
throw new IllegalArgumentException("Username or Password is Not Match");
}
return user;
}
public User login(Integer userId,String password)
{
User user=userRepository.findByUserIdandPassword(userId, DigestUtils.sha256Hex(password));
return user;
}
public boolean checkUsername(String userName)
{
User checkUser=userRepository.findByUsername(userName);
if(checkUser == null)
{
return true;
}
else
{
return false;
}
}
public boolean checkEmail(String email)
{
User checkUser=userRepository.findByEmail(email);
if(checkUser==null)
{
return true;
}
else
{
return false;
}
}
public void deleteUser(Integer userId)
{
User usr=userRepository.findByIduser(userId);
if(usr!=null)
{
usr.setStatus(0);
userRepository.save(usr);
}
}
public void updatePasswordUser(Integer userId,String password)
{
User usr=userRepository.findByIduser(userId);
if(usr!=null)
{
usr.setPassword(password);
userRepository.save(usr);
}
}
public void updateUser(Integer userId, String name, String userName, String email)
{
User usr=userRepository.findByIduser(userId);
if(usr!=null)
{
if(name != null && name != "") {
usr.setName(name);
}
if(userName != null && userName != "") {
usr.setUserName(userName);
}
if(email != null && email != "") {
usr.setEmail(email);
}
userRepository.save(usr);
}
}
}
| true |
e79c7cec632adbd95c4c372a2019696598ea617a | Java | Benjaminyuan/Book | /Ali_Coding/src/concurrency/DirtDataInThreadLocal.java | UTF-8 | 878 | 3.140625 | 3 | [] | no_license | package concurrency;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class DirtDataInThreadLocal {
public static ThreadLocal<String> threadLocal = new ThreadLocal<String>();
public static void main(String[] arg){
ExecutorService executorService = Executors.newFixedThreadPool(1);
for (int i=0; i<10; i++){
MyThread myThread = new MyThread();
executorService.execute(myThread);
int a[] = {};
}
}
private static class MyThread extends Thread{
private static boolean flag = true;
@Override
public void run(){
if (flag){
threadLocal.set(this.getName()+".session info.");
flag = false;
}
System.out.println(this.getName()+"线程"+threadLocal.get());
}
}
}
| true |
89174d56463b423d1abc362cbd81ea781c10d206 | Java | Yaswanth1616/EpamHomeTask2 | /project1/src/main/java/Sweets/Task.java | UTF-8 | 1,216 | 3.390625 | 3 | [] | no_license | package Sweets;
import java.util.ArrayList;
public class Task {
ArrayList<Sweet> l1 = new ArrayList<Sweet>();
public Task()
{
l1.add(new Sweet1("ladoo",3.6F,5.3F,3.6F,"yellow",10));
l1.add(new Sweet2("candy",3.1F,4.23F,1.6F,"red",15));
l1.add(new Sweet3("jalebi",1.6F,2.3F,2.16F,"pink",8));
l1.add(new Sweet1("Kulfy",7.23F,1.3F,2.3F,"white",6));
l1.add(new Sweet2("Basundi",3.12F,5.3F,2.2F,"white",1));
}
public int calculateTotalWeight() {
int value = 0;
for (Sweet s :l1) {
value+= s.getCount() * s.getWeight();
}
return value;
}
ArrayList<Sweet> l2 = new ArrayList<Sweet>();
public void sortbyCount()
{
for(Sweet s:l1)
{
int min=s.getCount();
Sweet obj1=s;
for(Sweet s1:l1)
{
if(s1.getCount()<min)
{
min=s1.getCount();
obj1=s1;
}
}
l2.add(obj1);
}
}
Task t1=new Task();
public void display()
{
System.out.println("Total weights of sweets is"+t1.calculateTotalWeight());
System.out.println("Sweets sorted according to sweet count is :");
for(Sweet s2:l2)
{
System.out.println(s2.getSweetName()+" "+s2.getSweetColor()+" "+s2.getSugarQuantity()+" "+s2.getSweetPrice()+" "+s2.getWeight()+" "+s2.getCount());
}
}
} | true |
dc66a2258aeade393b4af5d45b0db59f1a3e676a | Java | marcopala81/rbtmovies | /movies-comparator/movies-comparator-dao/src/main/java/ie/brandtone/moviescomparator/dao/Movie.java | UTF-8 | 1,531 | 2.921875 | 3 | [] | no_license | package ie.brandtone.moviescomparator.dao;
/**
* Describes a movie with the relevant getter methods and operations (as for the specifications for the Movies Comparator project).
*
* @author Marco Pala
*
* @version 1.0.0
*/
public interface Movie
{
/**
* Get the movie IMDb ID.
*
* @return The movie IMDb ID field
*
* @since v1.0.0
*/
String getImdbId();
/**
* Get the movie title.
*
* @return The movie title field
*
* @since v1.0.0
*/
String getTitle();
/**
* Get the movie rating.
*
* @return The movie rating field
*
* @since v1.0.0
*/
Float getRating();
/**
* Set the movie rating (for modifing local results).
*
* @param rating The new rating to set
*
* @since v1.0.0
*/
void setRating(Float rating);
/**
* Get the movie favourite flag.
*
* @return The favourite flag
*
* @since v1.0.0
*/
Boolean getFavourite();
/**
* Set the movie favourite flag (for pre-cooking results).
*
* @param favourite The favourite flag to set
*
* @since v1.0.0
*/
void setFavourite(Boolean favourite);
/**
* Format the {@link Movie}'s information as a JSON string for logging purposes.
*
* @return The Movie string representation
*
* @since v1.0.0
*/
String toString();
}
| true |
82563cae08963a08bc1c7071a3639bfd05f90598 | Java | mmppp/jenkins | /java/com/hanke/navi/skyair/service/AirSpaceWarningService.java | UTF-8 | 19,425 | 2.015625 | 2 | [] | no_license | package com.hanke.navi.skyair.service;
import android.app.IntentService;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import com.hanke.navi.skyair.MyApplication;
import com.hanke.navi.skyair.circle.OptionCircleView;
import com.hanke.navi.skyair.pop.bean.KongYuBean;
import com.hanke.navi.skyair.pop.bean.PlaneInfoBean;
import com.hanke.navi.skyair.pop.bean.WarningResultBean;
import com.hanke.navi.skyair.pop.msgpop.msgbean.HangBanGJBean;
import com.hanke.navi.skyair.pop.tcpop.XinXiPop;
import com.hanke.navi.skyair.ui.MainActivity;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
/**
* Created by mahao on 2017/9/15.
*/
public class AirSpaceWarningService extends IntentService {
public static Timer timer;
public OptionCircleView circle_deng;
private ArrayList<WarningResultBean> warningResultList;
public AirSpaceWarningService() {
super("AirSpaceWarningService");
}
//启动定时器,定时的检测当前飞机飞行的时候空域的状况.
@Override
protected void onHandleIntent(Intent intent) {
Log.i("hahaha", "airspaceservice启动了");
circle_deng = MainActivity.instence.circle_deng;
warningResultList = new ArrayList<>();
timer = new Timer();
timer.schedule(airSpaceWarningTask, 0, 800);
}
//需要的材料有维度,经度,高度,地速,升降速度,空域文件.
TimerTask airSpaceWarningTask = new TimerTask() {
@Override
public void run() {
PlaneInfoBean homePlane = MyApplication.getMyApplication().homePlane;
if (homePlane != null && homePlane.latLng != null) {
double lat = homePlane.latLng.latitude;
double lon = homePlane.latLng.longitude;
double flyHeight = homePlane.flyHeight;
double flySpeed = homePlane.flySpeed;
double upOrDownSpeed = homePlane.upOrDownSpeed;
double flyAngle = homePlane.flyAngle;
List<KongYuBean> data_ky = XinXiPop.instance.getData_ky();
//计算出来结果,空域预警信息
WarningResultBean kyWarningBean = new WarningResultBean();
byte resultKy = 0;
if (data_ky != null && data_ky.size() != 0) {
resultKy = MyApplication.getMyApplication().warnning.ky_warnning(lat, lon, flyHeight, flySpeed, upOrDownSpeed, 360 - flyAngle, data_ky);
kyWarningBean = getWarningLevel(resultKy);
kyWarningBean.warningTitle = "空域";
}
//这里需要询问一下,是否需要将角度减去90 180 270
String warningLevel_impact = "5";
int resultImpact = 0x10;
String adsb_plane_num = "";
HashMap<String, PlaneInfoBean> latLngHashMap = MyApplication.getMyApplication().latLngHashMap;
if (latLngHashMap != null && latLngHashMap.size() != 0) {
Set<Map.Entry<String, PlaneInfoBean>> entries = latLngHashMap.entrySet();
Iterator<Map.Entry<String, PlaneInfoBean>> iterator = entries.iterator();
while (iterator.hasNext()) {
Map.Entry<String, PlaneInfoBean> next = iterator.next();
PlaneInfoBean value = next.getValue();
String warningLevel = value.warningLevel;
if (!TextUtils.isEmpty(warningLevel)) {
if (Integer.parseInt(warningLevel) < Integer.valueOf(warningLevel_impact)) {
warningLevel_impact = warningLevel;
resultImpact = value.warningInfo;
adsb_plane_num = value.planeNum;
}
}
}
}
//碰撞预警的等级和文字
WarningResultBean impactWarningBean = new WarningResultBean();
impactWarningBean.warningLevel = Integer.valueOf(warningLevel_impact);
impactWarningBean.warningText = getImpactWarningText(resultImpact);
impactWarningBean.textColor = getImpactWarningTextColor(resultImpact);
impactWarningBean.adsbPlaneNum = adsb_plane_num;
impactWarningBean.warningTitle = "碰撞";
//撞地预警的等级和文字
WarningResultBean impactLandBean = new WarningResultBean();
boolean isImpactLandDanger = MyApplication.getMyApplication().isImpactLandDanger;
boolean isImpactLandDanger30 = MyApplication.getMyApplication().isImpactLandDanger30;
// int levelImpactLand = isImpactLandDanger ? 2 : 5;
int levelImpactLand = 5;
if (isImpactLandDanger30) {
levelImpactLand = 1;
} else if (isImpactLandDanger) {
levelImpactLand = 2;
}
impactLandBean.warningLevel = levelImpactLand;
if (levelImpactLand == 1) {
impactLandBean.warningText = "30s内即将撞地";
impactLandBean.textColor = Color.RED;
} else if (levelImpactLand == 2) {
impactLandBean.warningText = "60s内即将撞地";
impactLandBean.textColor = Color.parseColor("#FFE1C300");
} else {
impactLandBean.warningText = "";
}
impactLandBean.warningTitle = "撞地";
//添加到集合里面去
warningResultList.add(kyWarningBean);
warningResultList.add(impactWarningBean);
warningResultList.add(impactLandBean);
Collections.sort(warningResultList);
//这里用来控制灯
Message message = Message.obtain();
message.arg1 = warningResultList.get(0).warningLevel;
circle_deng_Handler.sendMessage(message);
// }
//这里用来控制文字,这里按照优先级来觉定用第几行来显示文字.
//优先级越高的显示在越上面
Message msg1 = new Message();
msg1.what = 1;
msg1.obj = warningResultList.get(0);
airspaceWarningHandler.sendMessage(msg1);
Message msg2 = new Message();
msg2.what = 2;
msg2.obj = warningResultList.get(1);
airspaceWarningHandler.sendMessage(msg2);
Message msg3 = new Message();
msg3.what = 3;
msg3.obj = warningResultList.get(2);
airspaceWarningHandler.sendMessage(msg3);
warningResultList.clear();
}
}
};
private boolean colorChange = false;
private int temp = 0;
Handler circle_deng_Handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
int level = msg.arg1;
if (level == 1) {
if (colorChange) {
colorChange = !colorChange;
circle_deng.setColorCircle(Color.RED);
} else {
colorChange = !colorChange;
circle_deng.setColorCircle(Color.TRANSPARENT);
}
} else if (level == 2) {
if (colorChange) {
colorChange = !colorChange;
circle_deng.setColorCircle(Color.parseColor("#FFE1C300"));
} else {
colorChange = !colorChange;
circle_deng.setColorCircle(Color.TRANSPARENT);
}
} else if (level == 3) {
circle_deng.setColorCircle(Color.parseColor("#FFE1C300"));
//绿闪
// if (colorChange) {
// colorChange = !colorChange;
// circle_deng.setColorCircle(Color.parseColor("#FFE1C300"));
// temp = 0;
// } else {
// temp = 0;
// colorChange = !colorChange;
// circle_deng.setColorCircle(Color.TRANSPARENT);
// }
} else if (level == 4) {
if (colorChange) {
colorChange = !colorChange;
circle_deng.setColorCircle(Color.GREEN);
temp = 0;
} else {
temp = 0;
colorChange = !colorChange;
circle_deng.setColorCircle(Color.TRANSPARENT);
}
} else if (level == 5) {
circle_deng.setColorCircle(Color.GREEN);
}
}
};
Handler airspaceWarningHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 1) {
WarningResultBean bean = (WarningResultBean) msg.obj;
MainActivity.instence.air_space_state.setTextColor(bean.textColor);
MainActivity.instence.air_space_state.setText(bean.warningText);
if (bean.warningTitle.equals("空域")) {
if (bean.warningLevel != 0xf) {
HangBanGJBean banGJBean = new HangBanGJBean();
banGJBean.hangbanhao_gj = "homeplane_ky";
banGJBean.jinggaoxinxi_gj = bean.warningText;
MyApplication.getMyApplication().homeplaneWarningInfoList.put("homeplane_ky", banGJBean);
} else {
MyApplication.getMyApplication().homeplaneWarningInfoList.remove("homeplane_ky");
}
} else if (bean.warningTitle.equals("碰撞")) {
if (bean.warningLevel != 0x10) {
HangBanGJBean banGJBean = new HangBanGJBean();
banGJBean.hangbanhao_gj = bean.adsbPlaneNum;
banGJBean.jinggaoxinxi_gj = bean.warningText;
MyApplication.getMyApplication().homeplaneWarningInfoList.put("adsb", banGJBean);
} else {
MyApplication.getMyApplication().homeplaneWarningInfoList.remove("adsb");
}
} else if (bean.warningTitle.equals("撞地")) {
if (bean.warningLevel == 1) {
HangBanGJBean banGJBean = new HangBanGJBean();
banGJBean.hangbanhao_gj = "本机";
banGJBean.jinggaoxinxi_gj = "30s内即将撞地";
MyApplication.getMyApplication().homeplaneWarningInfoList.put("impactland_ky", banGJBean);
} else if(bean.warningLevel == 2){
HangBanGJBean banGJBean = new HangBanGJBean();
banGJBean.hangbanhao_gj = "本机";
banGJBean.jinggaoxinxi_gj = "60s内即将撞地";
MyApplication.getMyApplication().homeplaneWarningInfoList.put("impactland_ky", banGJBean);
}else {
MyApplication.getMyApplication().homeplaneWarningInfoList.remove("impactland_ky");
}
}
} else if (msg.what == 2) {
//这里就是碰撞的
WarningResultBean bean = (WarningResultBean) msg.obj;
MainActivity.instence.impact_state.setTextColor(bean.textColor);
MainActivity.instence.impact_state.setText(bean.warningText);
if (bean.warningTitle.equals("空域")) {
if (bean.warningLevel != 0xf) {
HangBanGJBean banGJBean = new HangBanGJBean();
banGJBean.hangbanhao_gj = "homeplane_ky";
banGJBean.jinggaoxinxi_gj = bean.warningText;
MyApplication.getMyApplication().homeplaneWarningInfoList.put("homeplane_ky", banGJBean);
} else {
MyApplication.getMyApplication().homeplaneWarningInfoList.remove("homeplane_ky");
}
} else if (bean.warningTitle.equals("碰撞")) {
if (bean.warningLevel != 0x10) {
HangBanGJBean banGJBean = new HangBanGJBean();
banGJBean.hangbanhao_gj = bean.adsbPlaneNum;
banGJBean.jinggaoxinxi_gj = bean.warningText;
MyApplication.getMyApplication().homeplaneWarningInfoList.put("adsb", banGJBean);
} else {
MyApplication.getMyApplication().homeplaneWarningInfoList.remove("adsb");
}
} else if (bean.warningTitle.equals("撞地")) {
if (bean.warningLevel == 1) {
HangBanGJBean banGJBean = new HangBanGJBean();
banGJBean.hangbanhao_gj = "本机";
banGJBean.jinggaoxinxi_gj = "30s内即将撞地";
MyApplication.getMyApplication().homeplaneWarningInfoList.put("impactland_ky", banGJBean);
} else if(bean.warningLevel == 2){
HangBanGJBean banGJBean = new HangBanGJBean();
banGJBean.hangbanhao_gj = "本机";
banGJBean.jinggaoxinxi_gj = "60s内即将撞地";
MyApplication.getMyApplication().homeplaneWarningInfoList.put("impactland_ky", banGJBean);
}else {
MyApplication.getMyApplication().homeplaneWarningInfoList.remove("impactland_ky");
}
}
} else if (msg.what == 3) {
WarningResultBean bean = (WarningResultBean) msg.obj;
MainActivity.instence.impact_land_state.setTextColor(bean.textColor);
MainActivity.instence.impact_land_state.setText(bean.warningText);
if (bean.warningTitle.equals("空域")) {
if (bean.warningLevel != 0xf) {
HangBanGJBean banGJBean = new HangBanGJBean();
banGJBean.hangbanhao_gj = "homeplane_ky";
banGJBean.jinggaoxinxi_gj = bean.warningText;
MyApplication.getMyApplication().homeplaneWarningInfoList.put("homeplane_ky", banGJBean);
} else {
MyApplication.getMyApplication().homeplaneWarningInfoList.remove("homeplane_ky");
}
} else if (bean.warningTitle.equals("碰撞")) {
if (bean.warningLevel != 0x10) {
HangBanGJBean banGJBean = new HangBanGJBean();
banGJBean.hangbanhao_gj = bean.adsbPlaneNum;
banGJBean.jinggaoxinxi_gj = bean.warningText;
MyApplication.getMyApplication().homeplaneWarningInfoList.put("adsb", banGJBean);
} else {
MyApplication.getMyApplication().homeplaneWarningInfoList.remove("adsb");
}
} else if (bean.warningTitle.equals("撞地")) {
if (bean.warningLevel == 1) {
HangBanGJBean banGJBean = new HangBanGJBean();
banGJBean.hangbanhao_gj = "本机";
banGJBean.jinggaoxinxi_gj = "30s内即将撞地";
MyApplication.getMyApplication().homeplaneWarningInfoList.put("impactland_ky", banGJBean);
} else if(bean.warningLevel == 2){
HangBanGJBean banGJBean = new HangBanGJBean();
banGJBean.hangbanhao_gj = "本机";
banGJBean.jinggaoxinxi_gj = "60s内即将撞地";
MyApplication.getMyApplication().homeplaneWarningInfoList.put("impactland_ky", banGJBean);
}else {
MyApplication.getMyApplication().homeplaneWarningInfoList.remove("impactland_ky");
}
}
}
}
};
//碰撞
public int getImpactWarningTextColor(int info) {
int result = 0;
switch (info) {
case 0x01:
//红闪
result = Color.RED;
break;
case 0x04:
//黄闪
result = Color.parseColor("#FFE1C300");
break;
case 0x02:
result = Color.parseColor("#FFE1C300");
break;
case 0x10:
break;
case 0x08:
result = Color.GREEN;
break;
}
return result;
}
//碰撞
public String getImpactWarningText(int info) {
String result = "";
switch (info) {
case 0x01:
//红闪
result = "进入避碰区域";
break;
case 0x04:
//黄
result = "进入保护区域";
break;
case 0x02:
//黄闪
result = "即将进入避碰区域";
break;
case 0x10:
result = "";
break;
case 0x08:
//绿闪
result = "即将进入保护区域";
break;
}
return result;
}
//空域
public WarningResultBean getWarningLevel(byte info) {
WarningResultBean result = new WarningResultBean();
switch (info) {
case 1:
//黄闪
result.warningLevel = Integer.valueOf("2");
result.warningText = "飞出可飞空域";
result.textColor = Color.parseColor("#FFE1C300");
break;
case 4:
//绿闪
result.warningLevel = Integer.valueOf("4");
result.warningText = "即将飞出空域";
result.textColor = Color.GREEN;
break;
case 8:
//绿闪
result.warningLevel = Integer.valueOf("4");
result.warningText = "即将高度超限";
result.textColor = Color.GREEN;
break;
case 0x02:
//黄闪
result.warningLevel = Integer.valueOf("2");
result.warningText = "高度超限";
result.textColor = Color.parseColor("#FFE1C300");
break;
case 0xf:
//绿
result.warningLevel = Integer.valueOf("5");
result.warningText = "";
break;
}
return result;
}
}
| true |
952448e361a22ff9461a13efcef10d876da90707 | Java | verma87neha/TestAutomation | /src/main/java/com/pojo/ObjectRepository.java | UTF-8 | 1,427 | 2.328125 | 2 | [] | no_license | package com.pojo;
public class ObjectRepository {
//Object Repository
String field_Id;
String field_Name;
String field_Value;
String error_Msg;
String mandatory;
String type;
String xpath;
public String getField_Id() {
return field_Id;
}
public void setField_Id(String field_Id) {
this.field_Id = field_Id;
}
public String getField_Name() {
return field_Name;
}
public void setField_Name(String field_Name) {
this.field_Name = field_Name;
}
public String getField_Value() {
return field_Value;
}
public void setField_Value(String field_Value) {
this.field_Value = field_Value;
}
public String getError_Msg() {
return error_Msg;
}
public void setError_Msg(String error_Msg) {
this.error_Msg = error_Msg;
}
public String getMandatory() {
return mandatory;
}
public void setMandatory(String mandatory) {
this.mandatory = mandatory;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getXpath() {
return xpath;
}
public void setXpath(String xpath) {
this.xpath = xpath;
}
@Override
public String toString() {
return "ObjectRepository [field_Id=" + field_Id + ", field_Name=" + field_Name + ", field_Value="
+ field_Value + ", error_Msg=" + error_Msg + ", mandatory=" + mandatory + ", type=" + type
+ ", xpath=" + xpath + "]";
}
}
| true |
485b20d76743250e5c0080126e181a5e4d774e95 | Java | pmarchini/togethernet | /app/src/main/java/com/togethernet/togethernet/LocationDB/netsLocationList.java | UTF-8 | 1,055 | 2.125 | 2 | [] | no_license | package com.togethernet.togethernet.LocationDB;
import android.content.Context;
import com.google.android.gms.maps.model.LatLng;
import com.togethernet.togethernet.Firebase.FirebaseDataHandler;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Created by k1008014 on 12/01/2018.
*/
public class netsLocationList {
public com.togethernet.togethernet.LocationDB.firebaseHandler dataHandler;
public ArrayList<HashMap<String,String>> List;
public netsLocationList(){
dataHandler = new firebaseHandler();
}
public netsLocationList(LatLng XY, Context context){
dataHandler = new firebaseHandler();
dataHandler.SearchLocations(XY, 15, context);
}
public ArrayList<HashMap<String,String>> getLocations(){
return this.dataHandler.getLocationList();
}
public void UpdateLocations(LatLng XY, Context context){
dataHandler.SearchLocations(XY, 15, context);
}
public void SetLocations(ArrayList<HashMap<String,String>> List){
this.List = List;
}
}
| true |
ead69f544eed3ddbf283fc3bb46677d642a5440d | Java | titusjose/haikuvm | /haikuBench/src/main/java/haikuvm/bench/CodeVergleich.java | ISO-8859-1 | 2,239 | 3.421875 | 3 | [] | no_license | package haikuvm.bench;
public class CodeVergleich {
static final int T = 260;
static final int N = 20;
/*
http://www.rn-wissen.de/index.php/Codevergleich_AVR-Compiler
Summe der ersten n Zahlen
Berechnet wird die Summe der ersten n Zahlen:
Die Zahl n wird als 16-Bit Zahl angegeben und das Ergebnis als 16-Bit-Zahl berechnet.
Ein eventueller berlauf wird nicht beachtet.
Der Code wird jeweils als eigene Funktion implementiert, um Abhngigkeiten vom umliegenden Code zu vermeiden.
Fr diese Berechnung gibt es mehrere Mglichkeiten:
*/
//Aufsummieren in einer Schleife
static int sum_n_loop (int n)
{
int sum = 0;
int i;
for (i=n; i > 0; i--)
sum += i;
return sum;
}
//Berechnung mit rekursiver Funktion
static int sum_n_rekursiv (int n)
{
if (n == 0)
return 0;
return n + sum_n_rekursiv (n-1);
}
//Berechnung durch Formel
static int sum_n_formel (int n)
{
return n*(n+1) / 2;
}
public static void main(String[] args) {
long t1, t0, it=0;
int i,j,s=0;
int r=0;
System.out.printf("intra loop\n");
t0=System.currentTimeMillis();
for(i=0; i<T; i++) {
for(j=0; j<T; j++) {
r=j;
s+=i+j+r;
}
}
t1=System.currentTimeMillis();
System.out.printf("r=%d\t dt=%d ms (%d)\n", r, t1-t0-it, s);
it=t1-t0;
System.out.printf("Aufsummieren in einer Schleife\n");
t0=System.currentTimeMillis();
for(i=0; i<T; i++) {
for(j=0; j<T; j++) {
r=sum_n_loop(N);
s+=i+j+r;
}
}
t1=System.currentTimeMillis();
System.out.printf("r=%d\t dt=%d ms (%d)\n", r, t1-t0-it, s);
System.out.printf("Berechnung mit rekursiver Funktion\n");
t0=System.currentTimeMillis();
for(i=0; i<T; i++) {
for(j=0; j<T; j++) {
r=sum_n_rekursiv(N);
s+=i+j+r;
}
}
t1=System.currentTimeMillis();
System.out.printf("r=%d\t dt=%d ms (%d)\n", r, t1-t0-it, s);
System.out.printf("Berechnung durch Formel\n");
t0=System.currentTimeMillis();
for(i=0; i<T; i++) {
for(j=0; j<T; j++) {
r=sum_n_formel(j); //(j nicht N ! Damit sum_n_formel von C nicht weg optimiert wird)
s+=i+j+r;
}
}
t1=System.currentTimeMillis();
System.out.printf("r=%d\t dt=%d ms (%d)\n", r, t1-t0-it, s);
}
}
| true |
80706d462c77ecfd5bae068be4bb817c5a4654b4 | Java | vishnushelke/bridgelabzJavaPrograms | /javaprograms/bootcamp/src/com/bridgelabz/model/CustomerInfo.java | UTF-8 | 718 | 2.1875 | 2 | [] | no_license | package com.bridgelabz.model;
public class CustomerInfo {
private String symbol;
private String name;
private int availableshares;
private int rupeesavailable;
public String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAvailableshares() {
return availableshares;
}
public void setAvailableshares(int availableshares) {
this.availableshares = availableshares;
}
public int getRupeesavailable() {
return rupeesavailable;
}
public void setRupeesavailable(int rupeesavailable) {
this.rupeesavailable = rupeesavailable;
}
}
| true |
6b24514c23eaa702f724ccf7e73a4406cdd8336a | Java | noahwalsmits/GpsHelperBreda | /app/src/main/java/com/b/gpshelperbreda/activity/PointsAdapter.java | UTF-8 | 3,202 | 2.375 | 2 | [] | no_license | package com.b.gpshelperbreda.activity;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import com.b.gpshelperbreda.R;
import com.b.gpshelperbreda.data.Waypoint;
import java.util.List;
public class PointsAdapter extends RecyclerView.Adapter<PointsAdapter.ViewHolder> {
private List<Waypoint> dataset;
public PointsAdapter(List<Waypoint> waypoints) {
this.dataset = waypoints;
}
//Deze klasse geeft aan dat de recyclerview gevult moet worden met de mural
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_layout_waypoints, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
//Deze methode vult de mural met informatie
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
final Waypoint waypoint = dataset.get(position);
holder.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), WaypointDetailedActivity.class);
intent.putExtra("WAYPOINT", waypoint);
view.getContext().startActivity(intent);
}
});
TextView textTitle = holder.waypointTitle;
TextView textVisited = holder.waypointVisited;
ImageView imageView = holder.waypointImage;
textTitle.setText(waypoint.getName());
textVisited.setText(waypoint.isSeen() ? R.string.waypoint_check : R.string.waypoint_todo);
if (waypoint.getPhotoIDs()[0] == 0) {
imageView.setImageResource(R.drawable.photo_no_picture);
} else {
String name = "photo_" + waypoint.getPhotoIDs()[0];
int resid = holder.itemView.getResources().getIdentifier(name, "drawable", holder.itemView.getContext().getPackageName());
imageView.setImageResource(resid);
}
}
//Deze methode stuurt terug hoeveel waypoinst er zijn
@Override
public int getItemCount() {
return this.dataset.size();
}
//Deze klasse benoemd de objecten uit de mural xml
public class ViewHolder extends RecyclerView.ViewHolder {
TextView waypointTitle;
TextView waypointVisited;
ImageView waypointImage;
CardView cardView;
public ViewHolder(@NonNull View itemView) {
super(itemView);
cardView = itemView.findViewById(R.id.cardview);
waypointTitle = itemView.findViewById(R.id.waypoint_title);
waypointVisited = itemView.findViewById(R.id.waypoint_visited);
waypointImage = itemView.findViewById(R.id.waypoint_image);
}
}
}
| true |
6d989a82c39eb40c980fe12b00ad384fd85fb932 | Java | Zafarimam7032/Core_Java | /encapsulation/EncapusulationCall.java | UTF-8 | 234 | 2.640625 | 3 | [] | no_license | class EncapusulationCall
{
public static void main(String[] args)
{
System.out.println("main method");
Encapsulation e=new Encapsulation();
e.seta(10);
e.setb(20);
System.out.println("A:"+e.getA()+"\nB:"+e.getB());
}
}
| true |
fb5e92b1ab833f3510b067ef33847985fa2c87c0 | Java | zcc888/Java9Source | /java.xml.ws/com/sun/xml/internal/ws/server/sei/InvokerSource.java | UTF-8 | 700 | 1.6875 | 2 | [] | no_license | /*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package com.sun.xml.internal.ws.server.sei;
import com.sun.istack.internal.NotNull;
import com.sun.xml.internal.ws.api.message.Packet;
/**
* Interface for determining Invoker for a given request
*
* @since 2.2.6
*/
public interface InvokerSource<T extends Invoker> {
/**
* Returns Invoker for the given request
* @param request Packet for request
* @return Selected invoker
*/
public @NotNull T getInvoker(Packet request);
}
| true |
aec33a523cb4fd674db61782c68a413cc70b9f6c | Java | cgb-extjs-gwt/avgust-extjs-generator | /Trabajos/Sernanp/sources/SernanpApp/SernanpAppDao/src/main/java/sernanp/app/dao/domain/TParametroPlanillaExample.java | UTF-8 | 17,700 | 2.09375 | 2 | [] | no_license | package sernanp.app.dao.domain;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class TParametroPlanillaExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public TParametroPlanillaExample() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andSrl_id_parametro_planillaIsNull() {
addCriterion("srl_id_parametro_planilla is null");
return (Criteria) this;
}
public Criteria andSrl_id_parametro_planillaIsNotNull() {
addCriterion("srl_id_parametro_planilla is not null");
return (Criteria) this;
}
public Criteria andSrl_id_parametro_planillaEqualTo(Integer value) {
addCriterion("srl_id_parametro_planilla =", value, "srl_id_parametro_planilla");
return (Criteria) this;
}
public Criteria andSrl_id_parametro_planillaNotEqualTo(Integer value) {
addCriterion("srl_id_parametro_planilla <>", value, "srl_id_parametro_planilla");
return (Criteria) this;
}
public Criteria andSrl_id_parametro_planillaGreaterThan(Integer value) {
addCriterion("srl_id_parametro_planilla >", value, "srl_id_parametro_planilla");
return (Criteria) this;
}
public Criteria andSrl_id_parametro_planillaGreaterThanOrEqualTo(Integer value) {
addCriterion("srl_id_parametro_planilla >=", value, "srl_id_parametro_planilla");
return (Criteria) this;
}
public Criteria andSrl_id_parametro_planillaLessThan(Integer value) {
addCriterion("srl_id_parametro_planilla <", value, "srl_id_parametro_planilla");
return (Criteria) this;
}
public Criteria andSrl_id_parametro_planillaLessThanOrEqualTo(Integer value) {
addCriterion("srl_id_parametro_planilla <=", value, "srl_id_parametro_planilla");
return (Criteria) this;
}
public Criteria andSrl_id_parametro_planillaIn(List<Integer> values) {
addCriterion("srl_id_parametro_planilla in", values, "srl_id_parametro_planilla");
return (Criteria) this;
}
public Criteria andSrl_id_parametro_planillaNotIn(List<Integer> values) {
addCriterion("srl_id_parametro_planilla not in", values, "srl_id_parametro_planilla");
return (Criteria) this;
}
public Criteria andSrl_id_parametro_planillaBetween(Integer value1, Integer value2) {
addCriterion("srl_id_parametro_planilla between", value1, value2, "srl_id_parametro_planilla");
return (Criteria) this;
}
public Criteria andSrl_id_parametro_planillaNotBetween(Integer value1, Integer value2) {
addCriterion("srl_id_parametro_planilla not between", value1, value2, "srl_id_parametro_planilla");
return (Criteria) this;
}
public Criteria andVar_descrip_parametroIsNull() {
addCriterion("var_descrip_parametro is null");
return (Criteria) this;
}
public Criteria andVar_descrip_parametroIsNotNull() {
addCriterion("var_descrip_parametro is not null");
return (Criteria) this;
}
public Criteria andVar_descrip_parametroEqualTo(String value) {
addCriterion("var_descrip_parametro =", value, "var_descrip_parametro");
return (Criteria) this;
}
public Criteria andVar_descrip_parametroNotEqualTo(String value) {
addCriterion("var_descrip_parametro <>", value, "var_descrip_parametro");
return (Criteria) this;
}
public Criteria andVar_descrip_parametroGreaterThan(String value) {
addCriterion("var_descrip_parametro >", value, "var_descrip_parametro");
return (Criteria) this;
}
public Criteria andVar_descrip_parametroGreaterThanOrEqualTo(String value) {
addCriterion("var_descrip_parametro >=", value, "var_descrip_parametro");
return (Criteria) this;
}
public Criteria andVar_descrip_parametroLessThan(String value) {
addCriterion("var_descrip_parametro <", value, "var_descrip_parametro");
return (Criteria) this;
}
public Criteria andVar_descrip_parametroLessThanOrEqualTo(String value) {
addCriterion("var_descrip_parametro <=", value, "var_descrip_parametro");
return (Criteria) this;
}
public Criteria andVar_descrip_parametroLike(String value) {
addCriterion("var_descrip_parametro like", value, "var_descrip_parametro");
return (Criteria) this;
}
public Criteria andVar_descrip_parametroNotLike(String value) {
addCriterion("var_descrip_parametro not like", value, "var_descrip_parametro");
return (Criteria) this;
}
public Criteria andVar_descrip_parametroIn(List<String> values) {
addCriterion("var_descrip_parametro in", values, "var_descrip_parametro");
return (Criteria) this;
}
public Criteria andVar_descrip_parametroNotIn(List<String> values) {
addCriterion("var_descrip_parametro not in", values, "var_descrip_parametro");
return (Criteria) this;
}
public Criteria andVar_descrip_parametroBetween(String value1, String value2) {
addCriterion("var_descrip_parametro between", value1, value2, "var_descrip_parametro");
return (Criteria) this;
}
public Criteria andVar_descrip_parametroNotBetween(String value1, String value2) {
addCriterion("var_descrip_parametro not between", value1, value2, "var_descrip_parametro");
return (Criteria) this;
}
public Criteria andInt_tipo_parametroIsNull() {
addCriterion("int_tipo_parametro is null");
return (Criteria) this;
}
public Criteria andInt_tipo_parametroIsNotNull() {
addCriterion("int_tipo_parametro is not null");
return (Criteria) this;
}
public Criteria andInt_tipo_parametroEqualTo(Integer value) {
addCriterion("int_tipo_parametro =", value, "int_tipo_parametro");
return (Criteria) this;
}
public Criteria andInt_tipo_parametroNotEqualTo(Integer value) {
addCriterion("int_tipo_parametro <>", value, "int_tipo_parametro");
return (Criteria) this;
}
public Criteria andInt_tipo_parametroGreaterThan(Integer value) {
addCriterion("int_tipo_parametro >", value, "int_tipo_parametro");
return (Criteria) this;
}
public Criteria andInt_tipo_parametroGreaterThanOrEqualTo(Integer value) {
addCriterion("int_tipo_parametro >=", value, "int_tipo_parametro");
return (Criteria) this;
}
public Criteria andInt_tipo_parametroLessThan(Integer value) {
addCriterion("int_tipo_parametro <", value, "int_tipo_parametro");
return (Criteria) this;
}
public Criteria andInt_tipo_parametroLessThanOrEqualTo(Integer value) {
addCriterion("int_tipo_parametro <=", value, "int_tipo_parametro");
return (Criteria) this;
}
public Criteria andInt_tipo_parametroIn(List<Integer> values) {
addCriterion("int_tipo_parametro in", values, "int_tipo_parametro");
return (Criteria) this;
}
public Criteria andInt_tipo_parametroNotIn(List<Integer> values) {
addCriterion("int_tipo_parametro not in", values, "int_tipo_parametro");
return (Criteria) this;
}
public Criteria andInt_tipo_parametroBetween(Integer value1, Integer value2) {
addCriterion("int_tipo_parametro between", value1, value2, "int_tipo_parametro");
return (Criteria) this;
}
public Criteria andInt_tipo_parametroNotBetween(Integer value1, Integer value2) {
addCriterion("int_tipo_parametro not between", value1, value2, "int_tipo_parametro");
return (Criteria) this;
}
public Criteria andInt_id_estadoIsNull() {
addCriterion("int_id_estado is null");
return (Criteria) this;
}
public Criteria andInt_id_estadoIsNotNull() {
addCriterion("int_id_estado is not null");
return (Criteria) this;
}
public Criteria andInt_id_estadoEqualTo(Integer value) {
addCriterion("int_id_estado =", value, "int_id_estado");
return (Criteria) this;
}
public Criteria andInt_id_estadoNotEqualTo(Integer value) {
addCriterion("int_id_estado <>", value, "int_id_estado");
return (Criteria) this;
}
public Criteria andInt_id_estadoGreaterThan(Integer value) {
addCriterion("int_id_estado >", value, "int_id_estado");
return (Criteria) this;
}
public Criteria andInt_id_estadoGreaterThanOrEqualTo(Integer value) {
addCriterion("int_id_estado >=", value, "int_id_estado");
return (Criteria) this;
}
public Criteria andInt_id_estadoLessThan(Integer value) {
addCriterion("int_id_estado <", value, "int_id_estado");
return (Criteria) this;
}
public Criteria andInt_id_estadoLessThanOrEqualTo(Integer value) {
addCriterion("int_id_estado <=", value, "int_id_estado");
return (Criteria) this;
}
public Criteria andInt_id_estadoIn(List<Integer> values) {
addCriterion("int_id_estado in", values, "int_id_estado");
return (Criteria) this;
}
public Criteria andInt_id_estadoNotIn(List<Integer> values) {
addCriterion("int_id_estado not in", values, "int_id_estado");
return (Criteria) this;
}
public Criteria andInt_id_estadoBetween(Integer value1, Integer value2) {
addCriterion("int_id_estado between", value1, value2, "int_id_estado");
return (Criteria) this;
}
public Criteria andInt_id_estadoNotBetween(Integer value1, Integer value2) {
addCriterion("int_id_estado not between", value1, value2, "int_id_estado");
return (Criteria) this;
}
public Criteria andTsp_fecha_registroIsNull() {
addCriterion("tsp_fecha_registro is null");
return (Criteria) this;
}
public Criteria andTsp_fecha_registroIsNotNull() {
addCriterion("tsp_fecha_registro is not null");
return (Criteria) this;
}
public Criteria andTsp_fecha_registroEqualTo(Date value) {
addCriterion("tsp_fecha_registro =", value, "tsp_fecha_registro");
return (Criteria) this;
}
public Criteria andTsp_fecha_registroNotEqualTo(Date value) {
addCriterion("tsp_fecha_registro <>", value, "tsp_fecha_registro");
return (Criteria) this;
}
public Criteria andTsp_fecha_registroGreaterThan(Date value) {
addCriterion("tsp_fecha_registro >", value, "tsp_fecha_registro");
return (Criteria) this;
}
public Criteria andTsp_fecha_registroGreaterThanOrEqualTo(Date value) {
addCriterion("tsp_fecha_registro >=", value, "tsp_fecha_registro");
return (Criteria) this;
}
public Criteria andTsp_fecha_registroLessThan(Date value) {
addCriterion("tsp_fecha_registro <", value, "tsp_fecha_registro");
return (Criteria) this;
}
public Criteria andTsp_fecha_registroLessThanOrEqualTo(Date value) {
addCriterion("tsp_fecha_registro <=", value, "tsp_fecha_registro");
return (Criteria) this;
}
public Criteria andTsp_fecha_registroIn(List<Date> values) {
addCriterion("tsp_fecha_registro in", values, "tsp_fecha_registro");
return (Criteria) this;
}
public Criteria andTsp_fecha_registroNotIn(List<Date> values) {
addCriterion("tsp_fecha_registro not in", values, "tsp_fecha_registro");
return (Criteria) this;
}
public Criteria andTsp_fecha_registroBetween(Date value1, Date value2) {
addCriterion("tsp_fecha_registro between", value1, value2, "tsp_fecha_registro");
return (Criteria) this;
}
public Criteria andTsp_fecha_registroNotBetween(Date value1, Date value2) {
addCriterion("tsp_fecha_registro not between", value1, value2, "tsp_fecha_registro");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
} | true |
895b6dc5a1e6d741f7a1b9fec0375801978da7bd | Java | dante7qx/microservice-spirit | /project-getway-ui/src/main/java/com/spirit/project/getway/ui/prop/SpiritProperties.java | UTF-8 | 407 | 1.664063 | 2 | [] | no_license | package com.spirit.project.getway.ui.prop;
import org.springframework.boot.context.properties.ConfigurationProperties;
import lombok.Data;
@ConfigurationProperties(prefix = "spirit")
@Data
public class SpiritProperties {
/**
* 是否进行校验码验证
*/
private Boolean kaptcha;
/**
* 域服务器URL
*/
private String ldapurl;
/**
* 安全检查
*/
private Boolean safeCheck;
}
| true |
3f693bd8c9d921c84524f376068aa2a07d6d4714 | Java | sdnccu/106703057-2 | /src/jfacetutorial/DataModel.java | UTF-8 | 2,483 | 2.90625 | 3 | [
"MIT"
] | permissive | package jfacetutorial;
import java.util.ArrayList;
import java.util.List;
public class DataModel {
private static List<Article> articleList;
private static List<Department> departmentList;
private static List<AppMenu> appMenuList;
public static List<Article> getArticles() {
if (articleList == null) {
articleList = new ArrayList<Article>();
articleList.add(new Article("Java basic", "Tom", true));
articleList
.add(new Article("Hibernate for beginners", "Tran", true));
articleList.add(new Article("Maven for beginners", "Smith", false));
}
return articleList;
}
public static List<Department> getDepartments() {
if (departmentList == null) {
Employee emp11 = new Employee("E11", "Michael", "Smith");
Employee emp12 = new Employee("E12", "Susan", "Barker");
List<Employee> empList1 = new ArrayList<Employee>();
empList1.add(emp11);
empList1.add(emp12);
Department dept1 = new Department("D01", "Operation", empList1);
//
Employee emp21 = new Employee("E21", "Robert", "Tyler");
List<Employee> empList2 = new ArrayList<Employee>();
empList2.add(emp21);
Department dept2 = new Department("D02", "Adminstration", empList2);
//
departmentList = new ArrayList<Department>();
departmentList.add(dept1);
departmentList.add(dept2);
}
return departmentList;
}
public static List<AppMenu> getAppMenus() {
if (appMenuList == null) {
appMenuList = new ArrayList<AppMenu>();
AppMenu appMenu31 = new AppMenu("ErrorLog", "Error Log", null);
AppMenu appMenu32 = new AppMenu("ProjectExplorer",
"Project Explorer", null);
List<AppMenu> list3 = new ArrayList<AppMenu>();
list3.add(appMenu31);
list3.add(appMenu32);
AppMenu appMenu21 = new AppMenu("ShowView", "Show View", list3);
AppMenu appMenu22 = new AppMenu("ClosePerspective",
"Close perspective...", null);
List<AppMenu> list2 = new ArrayList<AppMenu>();
list2.add(appMenu21);
list2.add(appMenu22);
AppMenu appMenu1 = new AppMenu("Window", "Window", list2);
appMenuList.add(appMenu1);
}
return appMenuList;
}
} | true |
14a895597ce2538d1758eb749803287485167371 | Java | KimIlGu/lolBuild | /src/main/java/com/sbs/kig/lolBuild/LBuildApplication.java | UTF-8 | 313 | 1.65625 | 2 | [] | no_license | package com.sbs.kig.lolBuild;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class LBuildApplication {
public static void main(String[] args) {
SpringApplication.run(LBuildApplication.class, args);
}
}
| true |
7e7f297833ac4f6c923b15b0fbea45407500ae81 | Java | Volgofant/jenkinsConfigWW | /src/main/java/AccountPage.java | UTF-8 | 3,143 | 1.960938 | 2 | [] | no_license | import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class AccountPage {
WebDriver driver;
public AccountPage(WebDriver driver) {
this.driver = driver;
}
By updatePersonalDate = By.xpath("//a[@class=\"qaMyAccountCredentials\"]");
By updateAddress = By.xpath("//a[@class=\"qaMyAccountBillingAddress\"]");
By updateMailSpam = By.xpath("//a[@class=\"qaMyAccountNewsletters\"]");
By updateAddressDelivery = By.xpath("//a[@class=\"qaMyAccountShippingAddress\"]");
By accountSelMenu = By.xpath("//a[@class=\"account__sidebar__nav__list__link__item sel-menu-myaccount\"]");
By accountSelWishList = By.xpath("//a[@class=\"account__sidebar__nav__list__link__item sel-menu-wishlist\"]");
By accountSelOrders = By.xpath("//a[@class=\"account__sidebar__nav__list__link__item sel-menu-orders\"]");
By accountSelReviews = By.xpath("//a[@class=\"account__sidebar__nav__list__link__item sel-menu-reviews\"]");
By accountSelVouchers = By.xpath("//a[@class=\"account__sidebar__nav__list__link__item sel-menu-vouchers\"]");
By accountSelInfo = By.xpath("//a[@class=\"account__sidebar__nav__list__link__item sel-menu-info\"]");
By accountSelAddress = By.xpath("//a[@class=\"account__sidebar__nav__list__link__item sel-menu-addresses\"]");
By accountSelMailSpam = By.xpath("//a[@class=\"account__sidebar__nav__list__link__item sel-menu-newsletter\"]");
By helloMessage = By.xpath("//p[@class=\"accountStep1__header__text\"]");
By buttonChangePass = By.xpath("//a[@href=\"#passwordPopup\"]/p");
By actualPass = By.xpath("//input[@id=\"password_current-input\"]");
By newPass = By.xpath("//input[@id=\"password-input\"]");
By newPassConfirm = By.xpath("//input[@id=\"password2-input\"]");
By buttonSavePass = By.xpath("//button[@class=\"accountPopup__btn btn-primary\"]");
By textPassChange = By.xpath("//div[@class=\"message__text\"]");
By saveNewPass = By.xpath("//button[text()='Сохранить новый пароль']");
public AccountPage clickSaveNewPass() {
driver.findElement(saveNewPass).click();
return this;
}
public String getTextPassChange() {
return driver.findElement(textPassChange).getText();
}
public AccountPage inputActualPass (String AcPass) {
driver.findElement(actualPass).sendKeys(AcPass);
return this;
}
public AccountPage clickButtonChangePass() {
driver.findElement(buttonChangePass).click();
return this;
}
public String getHelloMessage() {
return driver.findElement(helloMessage).getText();
}
public AccountPage clickChangeDate() {
driver.findElement(accountSelInfo).click();
return this;
}
public AccountPage inputNewPass (String x) {
driver.findElement(newPass).sendKeys(x);
return this;
}
public AccountPage inputNewPassConfirm(String y) {
driver.findElement(newPassConfirm).sendKeys(y);
return this;
}
public AccountPage clickButtonSavePass() {
driver.findElement(buttonChangePass);
return this;
}
}
| true |
e936549af99370122ad1c62236723c7a6d07aa80 | Java | Paweloz/TravelAgency | /src/test/java/com/travel/agency/mapper/TravelMapperTestSuite.java | UTF-8 | 410 | 1.59375 | 2 | [] | no_license | package com.travel.agency.mapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
class TravelMapperTestSuite {
@Test
void mapFetchedTripsToTravelDto() {
}
@Test
void collectRightPlaceFromResponse() {
}
} | true |
42a2ccbac9eab72a8273eeebaed1b0ae468b14fd | Java | jwnichls/puc | /edu/cmu/hcii/puc/cio/TextFieldLinkedCIO.java | UTF-8 | 4,064 | 2.421875 | 2 | [
"MIT"
] | permissive | /**
* TextFieldLinkedCIO.java
*
* A sub-class of StateLinkedCIO.
*
* The concrete representation of a TextField widget.
*
* Revision History
* ----------------
* 10/02/2001: (JWN) Created file.
*/
// Package Definition
package edu.cmu.hcii.puc.cio;
// Import Declarations
import java.awt.FontMetrics;
import java.awt.Label;
import java.awt.Panel;
import java.awt.event.TextEvent;
import java.awt.event.TextListener;
import java.lang.*;
import edu.cmu.hcii.puc.Appliance;
import edu.cmu.hcii.puc.ApplianceObject;
import edu.cmu.hcii.puc.ApplianceState;
import edu.cmu.hcii.puc.PUC;
import edu.cmu.hcii.puc.StateListener;
import edu.cmu.hcii.puc.awt.TextField;
import edu.cmu.hcii.puc.registry.WidgetRegistry;
import com.maya.puc.common.Message;
// Class Definition
public class TextFieldLinkedCIO extends StateLinkedCIO {
//**************************
// Dynamic Loading Static
//**************************
static class TextFieldLinkedCIOFactory implements CIOFactory {
public ConcreteInteractionObject createCIO( Appliance a,
ApplianceObject ao ) {
return new TextFieldLinkedCIO( a, ao );
}
}
static {
// register the factory with the WidgetRegistry
WidgetRegistry.addCIOFactory( "TextFieldLinkedCIO", new TextFieldLinkedCIOFactory() );
}
//**************************
// Member Variables
//**************************
//**************************
// Constructor
//**************************
public TextFieldLinkedCIO( Appliance appl, ApplianceObject applObj ) {
super( appl, applObj, null );
m_Widget = new TextField( this );
ApplianceState s = (ApplianceState)applObj;
s.addStateListener( new StateListener() {
public void enableChanged( ApplianceObject obj ) {
m_Widget.setEnabled( m_ApplObj.isEnabled() );
}
public void labelChanged( ApplianceObject obj ) {
refreshDisplay();
}
public void typeChanged( ApplianceState obj ) {
refreshDisplay();
}
public void valueChanged( ApplianceState obj ) {
refreshDisplay();
}
});
((TextField)m_Widget).addTextListener( new TextListener() {
public void textValueChanged( TextEvent e ) {
String stateText = (String)((ApplianceState)m_ApplObj).m_Type.getValueSpace().getValue().toString();
String fieldText = ((TextField)e.getSource()).getText();
if ( stateText.equals( fieldText ) ) return;
Message msg = new Message.StateChangeRequest( TextFieldLinkedCIO.this.m_ApplObj.m_sName, fieldText );
try { TextFieldLinkedCIO.this.m_Appliance.m_pConnection.send( msg ); }
catch( Throwable t ) { }
}
});
refreshDisplay();
}
//**************************
// Protected Methods
//**************************
protected void refreshDisplay() {
ApplianceState s = (ApplianceState)m_ApplObj;
String sCurrentText = ((TextField)m_Widget).getText();
String sValueText = s.m_Type.getValueSpace().getValue().toString();
// BUG:JWN:Partially fixed problem where cursor moves
// irritatingly in the TextField on state updates (because the
// state updates continuously while you type). This is only a
// partial fix, because there is no guarantee that the state
// change rebounds will arrive faster than the user types.
// :-( The curse of I/O interaction objects, I guess...
if (! sCurrentText.equals( sValueText ) )
((TextField)m_Widget).setText( s.m_Type.getValueSpace().getValue().toString() );
}
//**************************
// Member Methods
//**************************
public void useMinimumLabel() { }
public boolean hasLabel() { return true; }
public ConcreteInteractionObject getLabelCIO() {
if ( m_ApplObj.m_Labels != null )
return new LabelCIO( m_ApplObj.m_Labels );
return null;
}
public void addNotify() {
refreshDisplay();
}
}
| true |
b7194ea2857fc737a1b6d5afc626b3649723a191 | Java | Renanzinth/clinica-veterinaria | /src/modelo/dao/TipoDAO.java | UTF-8 | 440 | 2.4375 | 2 | [] | no_license | package modelo.dao;
import java.util.List;
import modelo.dominio.Tipo;
public class TipoDAO extends JpaDAO<Tipo> {
@Override
public List<Tipo> lerTodos() {
List<Tipo> lista = super.lerTodos();
if (lista.isEmpty()) {
this.salvar(new Tipo("Cachorro"));
this.salvar(new Tipo("Gato"));
this.salvar(new Tipo("Periquito"));
this.salvar(new Tipo("Calopsyta"));
lista = super.lerTodos();
}
return lista;
}
}
| true |
570c14f2d37fadd59175adac2422bd03769525fd | Java | eclix-del/ioc | /src/com/l/testIoc/ioc/Money.java | UTF-8 | 174 | 2.28125 | 2 | [] | no_license | package com.l.testIoc.ioc;
import com.l.testIoc.annotation.C;
@C
public class Money {
public void speak(){
System.out.println("this is money speak");
}
}
| true |
0cd2b6da12501642f4e5c5637284ac1a2c69d59a | Java | Alen-Liu/SpringBootDemo | /src/main/java/com/alen/football/modules/user/jpa/UserJPA.java | UTF-8 | 541 | 1.867188 | 2 | [] | no_license | package com.alen.football.modules.user.jpa;
import com.alen.football.modules.user.entity.UserEntity;
import io.lettuce.core.dynamic.annotation.Param;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import java.io.Serializable;
/**
* @author liulun
*/
public interface UserJPA extends JpaRepository<UserEntity, Long>,
JpaSpecificationExecutor<UserEntity>, Serializable {
UserEntity findByUserName(@Param("user_name") String username);
}
| true |
1c78e35b29d24ff11fc1b2b032956287b2bedc1a | Java | iamwillzhu/beat-em-up | /src/Monster.java | UTF-8 | 652 | 2.953125 | 3 | [] | no_license | import javafx.scene.image.ImageView;
import javafx.animation.Timeline;
public class Monster {
public static int numberMonsters = 0;
private Game game;
private ImageView image;
private Timeline timeline;
public Monster(Game game, ImageView image, Timeline timeline) {
this.game = game;
this.image = image;
this.timeline = timeline;
numberMonsters += 1;
}
public ImageView getImage() {
return image;
}
public Timeline getTimeline() {
return timeline;
}
public void spawn() {
game.getRoot().getChildren().add(image);
timeline.play();
}
}
| true |
01ad8cf2f3dad51b87c75580943750481006dbf2 | Java | linhaosheng/- | /app/src/main/java/linhao/com/algorithmproject/algorithmUtil/顺时针打印矩阵.java | UTF-8 | 1,326 | 3.796875 | 4 | [] | no_license | package linhao.com.algorithmproject.algorithmUtil;
/**
* Created by reeman on 2017/11/8.
*/
public class 顺时针打印矩阵 {
/**
* 输入一个矩阵,按照从外向里以顺时针的顺序依次扫印出每一个数字。
*
* 把打印一圈分为四步:第一步从左到右打印一行,第二步从上到下打印一列,第三步从右到左打印一行,第四步从下到上打印一列。每一步我们根据起始坐标和终止坐标用一个循环就能打印出一行或者一列。
不过值得注意的是,最后一圈有可能退化成只有一行、只有一列,甚至只有一个数字,因此打印这样的一圈就不再需要四步。
因此我们要仔细分析打印时每一步的前提条件。第一步总是需要的, 因为打印一圈至少有一步。如果只有一行,那么就不用第二步了。
也就是需要第二步的前提条件是终止行号大于起始行号。需要第三步打印的前提条件是圈内至少有两行两列,也就是说除了要求终止行号大于起始行号之外,
还要求终止列号大于起始列号。同理,需要打印第四步的前提条件是至少有三行两列,因此要求终止行号比起始行号至少大2 , 同时终止列号大于起始列号。
*/
}
| true |
0b4e2dd5cae7cf9c84af46a4a0f267e448b28145 | Java | LordAjinkya/line-comparison-problem | /UC3.java | UTF-8 | 1,176 | 3.828125 | 4 | [] | no_license | import java.util.Scanner;
public class UC3 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the 1st coordinates of 1st line");
int x1=sc.nextInt();
int y1=sc.nextInt();
System.out.println("Enter the 2nd coordinates of 1st line");
int x2=sc.nextInt();
int y2=sc.nextInt();
System.out.println("Enter the 1st coordinates of 2nd line");
int x3=sc.nextInt();
int y3=sc.nextInt();
System.out.println("Enter the coordinates of 4th line");
int x4=sc.nextInt();
int y4=sc.nextInt();
double length1 = Math. sqrt( ( ( x2 - x1 ) * ( x2 - x1 ) ) + ( ( y2 - y1 ) * ( y2 - y1 ) ) );
System.out.println("Length of first line" + length1 );
double length2 = Math. sqrt( ( ( y4 - y3 ) * ( y4 - y3 ) ) + ( ( y4 - y3 ) * ( y4 - y3 ) ) );
System.out.println("length of 2nd line"+length2);
if (length1 < length2) {
System.out.println("Line 2 length is greater than line 1 length");
} else if (length1>length2) {
System.out.println("Line 2 length is smaller than line 1 length");
} else {
System.out.println("Line 1 length is equal to line 2 length");
}
}
}
| true |
efc73645a0a840a8e357ea7b17bc4ae7f98be8c3 | Java | bhatshravan/ChatApp | /src/java/inc/bs/chataroo/induv_chat/MessageAdapter.java | UTF-8 | 6,079 | 2.109375 | 2 | [] | no_license | package inc.bs.chataroo.induv_chat;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.squareup.picasso.Picasso;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import inc.bs.chataroo.R;
import inc.bs.chataroo.activiti.SinglePhotoView;
import inc.bs.chataroo.models.Messages;
/**
* Created by AkshayeJH on 24/07/17.
*/
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.MessageViewHolder>{
private Context context;
private List<Messages> mMessageList;
private DatabaseReference mUserDatabase;
private String user1,user2,date="",date2="",n="",date3="";
String url="";
public MessageAdapter(Context context,List<Messages> mMessageList ,String user1,String user2) {
this.context = context;
this.mMessageList = mMessageList;
this.user1=user1;
this.user2=user2;
}
@Override
public MessageViewHolder onCreateViewHolder(ViewGroup parent, int viewType ) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.induv_chat_message_single3 ,parent, false);
return new MessageViewHolder(v);
}
public class MessageViewHolder extends RecyclerView.ViewHolder {
public TextView messageText,messageTextMe;
// public CircleImageView profileImage;
// public TextView displayName;
// public ImageView messageImage;
public TextView time,timeme,datet;
private ImageView im,imme;
public MessageViewHolder(View view) {
super(view);
messageText = (TextView) view.findViewById(R.id.text_message_body33);
messageTextMe = (TextView) view.findViewById(R.id.text_message_bodyme33);
time = (TextView) view.findViewById(R.id.text_message_time33);
timeme = (TextView) view.findViewById(R.id.text_message_timeme33);
datet = (TextView) view.findViewById(R.id.datet);
// profileImage = (CircleImageView) view.findViewById(R.id.message_profile_layout);
// displayName = (TextView) view.findViewById(R.id.name_text_layout);
// messageImage = (ImageView) view.findViewById(R.id.message_image_layout);
// time = view.findViewById(R.id.time_text_layout);
im = (ImageView) view.findViewById(R.id.message_image_layout33);
imme = (ImageView) view.findViewById(R.id.message_image_layout_me33);
}
}
@Override
public void onBindViewHolder(final MessageViewHolder viewHolder, int i) {
// Log.d("Here",String.valueOf(i));
String current_user_id= FirebaseAuth.getInstance().getCurrentUser().getUid();
Messages c = mMessageList.get(i);
String from_user = c.getFrom();
String message_type = c.getType();
SimpleDateFormat sfd = new SimpleDateFormat("hh:mm a");
n = sfd.format(new Date(c.getTime()));
SimpleDateFormat sfd2 = new SimpleDateFormat("dd-MM-yyyy");
date2 = sfd2.format(new Date(c.getTime()));
date3=date2;
if(!date.equals(date3))
{
date=date3;
viewHolder.datet.setText(date);
viewHolder.datet.setVisibility(View.VISIBLE);
}
if(message_type.equals("text"))
{
if(from_user.equals(current_user_id)) {
viewHolder.messageTextMe.setText(c.getMessage());
viewHolder.messageText.setVisibility(View.GONE);
viewHolder.messageTextMe.setVisibility(View.VISIBLE);
viewHolder.timeme.setVisibility(View.VISIBLE);
viewHolder.time.setVisibility(View.GONE);
viewHolder.timeme.setText(n);
}
else
{
viewHolder.messageText.setText(c.getMessage());
viewHolder.messageTextMe.setVisibility(View.GONE);
viewHolder.messageText.setVisibility(View.VISIBLE);
viewHolder.time.setText(n);
viewHolder.timeme.setVisibility(View.GONE);
viewHolder.time.setVisibility(View.VISIBLE);
}
}
else
{
url=c.getMessage();
if (from_user.equals(current_user_id))
{
viewHolder.imme.setVisibility(View.VISIBLE);
Picasso.with(context).load(c.getMessage()).placeholder(R.mipmap.ic_launcher).into(viewHolder.imme);
viewHolder.imme.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(context, SinglePhotoView.class);
i.putExtra("url",url);
context.startActivity(i);
}
});
}
else
{
viewHolder.im.setVisibility(View.VISIBLE);
Picasso.with(context).load(c.getMessage()).placeholder(R.mipmap.ic_launcher).into(viewHolder.im);
viewHolder.im.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(context, SinglePhotoView.class);
i.putExtra("url",url);
context.startActivity(i);
}
});
}
}
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getItemViewType(int position) {
return position;
}
@Override
public int getItemCount() {
return mMessageList.size();
}
}
| true |
e8d3ef963879d13ad69ac9ccd5d3f4dfb7313970 | Java | wustlcse237sp20/project-elementarytaskmanager | /src/taskmanager/Student.java | UTF-8 | 3,948 | 3.484375 | 3 | [] | no_license | package taskmanager;
import java.util.LinkedList;
import java.util.List;
import javax.swing.DefaultListModel;
import java.io.File;
public class Student {
private Schedule schedule;
String name;
List<Achievement> possibleAchievements;
public Student(String name) {
this.name = name;
this.schedule = new Schedule(name);
possibleAchievements = new LinkedList<Achievement>();
possibleAchievements.add(new Juggler());
possibleAchievements.add(new Pyramid());
}
public Schedule getSchedule() {
return this.schedule;
}
/**
* adds a single task to the student's schedule
* @param task the task to add
*/
public void addTask(Task task) {
schedule.addTask(task);
}
/**
* prints out each task on a new line
*/
public void viewTasks() {
List<Task> tasks = schedule.getTasks();
for (Task task : tasks) {
System.out.println(task);
}
}
/**
* used by the gui to return tasks in a particular category
* @param category the desired category
* @return a default list model of those tasks
*/
public DefaultListModel<Task> getTasksByCategory(Categories category) {
return schedule.getTasksByListCategory(category);
}
/**
* used by the gui to return tasks in a particular day
* @param day the desired day
* @return a default list model of those tasks
*/
public DefaultListModel<Task> getTasksByDay(Days day) {
return schedule.getTasksByListDay(day);
}
/**
* writes the current list of tasks to the schedule
*/
public void saveSchedule() {
this.schedule.writeTasks();
}
/**
* updates the task with the same name as the param
* @param task the updated task
*/
public void updateTask(Task task) {
this.schedule.updateTask(task);
}
public static void main(String[] args) {
String username = UserInputUtils
.promptUser("Please type your username and hit Enter to login to Elementary Task Manager");
addStudentToRoster(username);
Student thisStudent = new Student(username);
String userFirstChoice = UserInputUtils
.promptUser("Welcome, " + username + "! Type 'v' to view your tasks, , or 'q' to quit");
if (userFirstChoice.equals("v")) {
thisStudent.viewTasks();
}
}
/**
* adds this student to the text file roster of students
* @param username name of student to add
*/
private static void addStudentToRoster(String username) {
File userFile = new File("./studentUsers.txt");
FileReaderHandler reader = new FileReaderHandler(userFile);
boolean usernameAlreadyInFile = reader.containsLine(username);
if (!usernameAlreadyInFile) {
FileWriterHandler usernameWriter = new FileWriterHandler(userFile, true);
usernameWriter.writeLine(username);
System.out.println("User " + username + " created");
}
}
/**
* determines what level of accomplishment the student is at based on the tasks
* @return a level enum based on number of tasks IP/Done
*/
public Levels calculateLevel() {
DefaultListModel<Task> completedTasks = getTasksByCategory(Categories.Done);
DefaultListModel<Task> inProgressTasks = getTasksByCategory(Categories.InProgress);
if(completedTasks.getSize() > 10) {
return Levels.TaskMaster;
}
else if(completedTasks.getSize() + inProgressTasks.getSize() > 10) {
return Levels.Novice;
}
else {
return Levels.Beginner;
}
}
/**
* checks whether or not a student has accomplished certain achievements
* @return a list of all achievements the student has earned
*/
public DefaultListModel<Achievement> checkAcheivements() {
DefaultListModel<Achievement> achievements = new DefaultListModel<Achievement>();
for(Achievement a : possibleAchievements) {
if(a.isCompleted(this)) {
achievements.addElement(a);
}
}
return achievements;
}
@Override
public String toString() {
return this.name;
}
}
| true |