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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
228927405c18e98133594a5c1b2751c971a71204
|
Java
|
dggodi/Funboats-app
|
/funboats-spring/src/main/java/com/funboats/repositories/ItemOfferingRepositoryImpl.java
|
UTF-8
| 6,337
| 2.4375
| 2
|
[] |
no_license
|
package com.funboats.repositories;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import com.funboats.model.ItemOffering;
import com.funboats.model.SearchObject;
import com.funboats.repositories.maps.ItemOfferingRowMapper;
@Controller
public class ItemOfferingRepositoryImpl implements ItemOfferingRepository{
@Autowired
private JdbcTemplate jdbcTemplate;
/**
* return id of object is search for object in DB is successful
* @return Long
*/
public Long getCount(){
String sql = "SELECT COUNT(*) FROM itemofferings";
return jdbcTemplate.queryForObject(sql, Long.class);
}
/**
* return list off all ItemOffering objects searched for
* @return List<ItemOffering>
*/
public List<ItemOffering> findAll() {
String sql = "SELECT * FROM items, itemofferings where "
+ "item_offering_id = item_id";
return jdbcTemplate.query(sql, new ItemOfferingRowMapper());
}
/**
* return ItemOffering if the object is found by id
* @return ItemOffering
*/
public ItemOffering searchById(SearchObject obj){
String sql = "SELECT * FROM items, itemofferings where item_offering_id = ? and "
+ "item_offering_id = items.item_id";
Object[] params = {obj.getId()};
return this.jdbcTemplate.queryForObject(sql, params, new ItemOfferingRowMapper() );
}
/**
* return list off all ItemOffering objects searched by location
* @return List<ItemOffering>
*/
public List<ItemOffering> searchByLocation(SearchObject obj) {
String sql = "SELECT * FROM items, itemofferings where item_offering_id = items.item_id and "
+ "location = ?";
Object[] params = {obj.getSearch()};
return jdbcTemplate.query(sql, params, new ItemOfferingRowMapper());
}
/**
* return list off all ItemOffering objects searched by brand, year, cost, category
* @return List<ItemOffering>
*/
public List<ItemOffering> searchByFilter(ItemOffering itemOffering){
String sql = "SELECT * FROM items, itemofferings where item_offering_id = items.item_id AND "
+ "brand = ? AND year = ? AND cost = ? AND category = ?";
Object[] params = {
itemOffering.getBrand(),
itemOffering.getYear(),
itemOffering.getCost(),
itemOffering.getItem().getCategory()
};
return jdbcTemplate.query(sql, params, new ItemOfferingRowMapper());
}
/**
* return list off all ItemOffering objects searched for using LIKE
* @return List<ItemOffering>
*/
public List<ItemOffering> searchByLike(SearchObject obj){
String sql = "SELECT * FROM items, itemofferings where item_offering_id = items.item_id AND "
+ "brand LIKE ? OR model LIKE ? OR location LIKE ? OR color LIKE ? OR category LIKE ?";
Object[] params = {
"%" + obj.getSearch() + "%",
"%" + obj.getSearch() + "%",
"%" + obj.getSearch() + "%",
"%" + obj.getSearch() + "%",
"%" + obj.getSearch() + "%"
};
return jdbcTemplate.query(sql, params, new ItemOfferingRowMapper());
}
/**
* return true if object is successfully deleted by id
* @return boolean
*/
@Transactional
public boolean delete(SearchObject obj){
String sql = "DELETE FROM itemofferings WHERE item_offering_id = ?";
jdbcTemplate.update(sql, obj.getId());
sql = "DELETE FROM items WHERE item_id = ?";
return (jdbcTemplate.update(sql, obj.getId())) > 0;
}
/**
* return true if save was successful
* @return boolean
*
* note: construct save query and calls saveAndFlush to save to DB
*/
public boolean save(ItemOffering itemOffering){
String sqlItems = "INSERT INTO items (hours, displacement, color, category, seating,";
sqlItems +=" vinNo, engine, pumpType, fuelcap) VALUES (?,?,?,?,?,?,?,?,?)";
String sqlItemofferings = "INSERT INTO itemofferings (brand, model, year, cost, descript, location, user_name) ";
sqlItemofferings += " VALUES (?,?,?,?,?,?,?)";
return saveAndFlush(itemOffering, sqlItemofferings, sqlItems, null);
}
/**
* return true if update was successful
* @return boolean
*
* note: construct update query and calls saveAndFlush to save to DB
*/
public boolean update(ItemOffering itemOffering){
String sqlItems = "UPDATE items SET hours=?, displacement=?, color=?, category=?, seating=?, ";
sqlItems+= "vinNo=?, engine=?, pumpType=?, fuelCap=? WHERE item_id=?";
String sqlItemofferings = "UPDATE itemofferings SET brand=?, model=?, year=?, cost=?, ";
sqlItemofferings+= "descript=?, location=?, user_name=? WHERE item_offering_id=?";
Object id = itemOffering.getItemOfferingId();
return saveAndFlush(itemOffering, sqlItemofferings, sqlItems, id);
}
/**
* return true if save was successful
* @param itemOffering object to save to DB
* @param sqlItemofferings query for ItemOfferings
* @param sqlItems query for Items
* @param id id for update or null for insert operation
* @return true
*/
@Transactional
public boolean saveAndFlush(ItemOffering itemOffering, String sqlItemofferings, String sqlItems, Object id){
List<Object> list = new ArrayList<>();
list.add(itemOffering.getItem().getHours());
list.add(itemOffering.getItem().getDisplacement());
list.add(itemOffering.getItem().getColor());
list.add(itemOffering.getItem().getCategory());
list.add(itemOffering.getItem().getSeating());
list.add(itemOffering.getItem().getVinNo());
list.add(itemOffering.getItem().getEngine());
list.add(itemOffering.getItem().getPumpType());
list.add(itemOffering.getItem().getFuelcapacity());
if(id != null)
list.add(id);
Object[] params = list.toArray(new Object[list.size()]);
jdbcTemplate.update(sqlItems, params);
list = new ArrayList<>();
list.add(itemOffering.getBrand());
list.add(itemOffering.getModel());
list.add(itemOffering.getYear());
list.add(itemOffering.getCost());
list.add(itemOffering.getDescript());
list.add(itemOffering.getLocation());
list.add(itemOffering.getUsername());
if(id != null)
list.add(id);
params = list.toArray(new Object[list.size()]);
return (jdbcTemplate.update(sqlItemofferings, params)) > 0;
}
}
| true
|
0db2970b0d2fbcce0a753cfc5a7ff760071367c9
|
Java
|
LiuHongMing/im
|
/im-startup/src/main/java/com/im/netty/xmpp/smack/stanza/StanzaEvent.java
|
UTF-8
| 1,213
| 2.109375
| 2
|
[] |
no_license
|
package com.im.netty.xmpp.smack.stanza;
import com.google.common.eventbus.Subscribe;
import com.im.netty.session.Connection;
import com.im.netty.session.ConnectionManager;
import com.im.netty.xmpp.handler.NegotiationHandler;
import io.netty.channel.Channel;
import org.jivesoftware.smack.packet.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class StanzaEvent {
private static final Logger logger = LoggerFactory.getLogger(NegotiationHandler.class);
private ConnectionManager connectManager;
public StanzaEvent(ConnectionManager connectManager) {
this.connectManager = connectManager;
}
@Subscribe
public void message(Message message) {
logger.info("StanzaEvent[message] -> {}", message.toXML().toString());
String id = message.getStanzaId();
String to = message.getTo();
Message.Type type = message.getType();
Connection toConnection = connectManager.get(to);
if (toConnection != null) {
Channel toChannel = toConnection.getChannel();
if (type == Message.Type.chat) {
toChannel.writeAndFlush(message.toXML().toString());
}
}
}
}
| true
|
b8c10d64043bcd89fe63468d21ed33a3b2685916
|
Java
|
gonzapico/OnTruckTT
|
/presentation/src/main/java/xyz/gonzapico/ontrucktt/showUsers/adapter/UsersAdapter.java
|
UTF-8
| 1,413
| 2.3125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package xyz.gonzapico.ontrucktt.showUsers.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.Collections;
import java.util.List;
import xyz.gonzapico.ontrucktt.R;
import xyz.gonzapico.ontrucktt.showUsers.User;
/**
* Created by gfernandez on 6/12/16.
*/
public class UsersAdapter extends RecyclerView.Adapter<UserViewHolder> {
private final LayoutInflater layoutInflater;
private List<User> listOfUsers;
public UsersAdapter(Context context) {
this.layoutInflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.listOfUsers = Collections.emptyList();
}
@Override public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final View view = this.layoutInflater.inflate(R.layout.row_user, parent, false);
return new UserViewHolder(view);
}
@Override public void onBindViewHolder(UserViewHolder holder, int position) {
holder.tvFullName.setText(listOfUsers.get(position).fullName);
holder.tvId.setText(listOfUsers.get(position).id);
holder.tvToken.setText(listOfUsers.get(position).token);
}
@Override public int getItemCount() {
return listOfUsers.size();
}
public void setListOfUsers(List<User> userList) {
this.listOfUsers = userList;
}
}
| true
|
9717a95e585305ff75f96c152f6488b298e7336d
|
Java
|
MahdiDavoodi/JK
|
/Java/Exercism/06GigaSecond/Gigasecond.java
|
UTF-8
| 498
| 3.203125
| 3
|
[] |
no_license
|
import java.time.LocalDate;
import java.time.LocalDateTime;
public class Gigasecond {
private final LocalDateTime time;
public Gigasecond(LocalDate date) {
this.time = date.atStartOfDay();
}
public Gigasecond(LocalDateTime date) {
this.time = date;
}
public LocalDateTime getDateTime() {
return time.plusSeconds(1_000_000_000L);
}
}
/*
* This is a challenge on Exercism.
* Link ---> https://exercism.org/tracks/java/exercises/gigasecond
*/
| true
|
f6f172f8ae0b45e4899d977e7b917982830de33b
|
Java
|
blindlp/Barber
|
/app/src/main/java/gt/com/irc/barber/splash/DI/SplashComponent.java
|
UTF-8
| 397
| 1.867188
| 2
|
[] |
no_license
|
package gt.com.irc.barber.splash.DI;
import javax.inject.Singleton;
import dagger.Component;
import gt.com.irc.barber.AppModule;
import gt.com.irc.barber.lib.DI.LibModule;
import gt.com.irc.barber.splash.SplashActivity;
@Singleton
@Component(modules = {AppModule.class, LibModule.class, SplashModule.class})
public interface SplashComponent {
void inject(SplashActivity splashActivity);
}
| true
|
0666a24466555f7ec1fbee1bf357ed5434f751e1
|
Java
|
fixrhee/mpos
|
/mpos/src/main/java/com/jpa/mpos/data/Channel.java
|
UTF-8
| 1,222
| 2.109375
| 2
|
[] |
no_license
|
package com.jpa.mpos.data;
import java.math.BigDecimal;
import java.util.Date;
public class Channel {
private Integer id;
private Merchant merchant;
private String name;
private String description;
private BigDecimal fixedFee;
private double percentageFee;
private Date createdDate;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Merchant getMerchant() {
return merchant;
}
public void setMerchant(Merchant merchant) {
this.merchant = merchant;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public BigDecimal getFixedFee() {
return fixedFee;
}
public void setFixedFee(BigDecimal fixedFee) {
this.fixedFee = fixedFee;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public double getPercentageFee() {
return percentageFee;
}
public void setPercentageFee(double percentageFee) {
this.percentageFee = percentageFee;
}
}
| true
|
75eea77664b48c9b18c84db2aaed91ab1c024601
|
Java
|
BambangTampubolon/backendtest
|
/api.test/src/spring/test/UserControllerTest.java
|
UTF-8
| 3,862
| 1.945313
| 2
|
[] |
no_license
|
package spring.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import com.google.gson.Gson;
import spring.controller.UserController;
import spring.manager.impl.UserManagerImpl;
import spring.util.ErrorDetail;
import spring.viewmodel.MasterViewModel;
@RunWith(SpringRunner.class)
@WebMvcTest(UserController.class)
public class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@Mock
private UserManagerImpl userManager;
@Test
public void isNotExistMobileNumber() throws Exception{
Mockito.when(userManager.isExistEmail(Mockito.anyString())).thenReturn(true);
RequestBuilder requestBuilder = MockMvcRequestBuilders.get("http://localhost:8081/api.test/v1/User/082133999623")
.accept(MediaType.ALL_VALUE);
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
/*
* expected returned json
{
"content": {
"status": 204,
"message": "NO_CONTENT",
"detailmessage": null,
"executiontime": 0,
"detailInfo": "NO_CONTENT"
}
}
*/
MasterViewModel expectedReturnedData = new MasterViewModel();
ErrorDetail info = new ErrorDetail();
info.setMessage(HttpStatus.OK.name());
info.setStatus(HttpStatus.OK.value());
info.setDetailInfo(HttpStatus.OK);
expectedReturnedData.setContent(info);
Gson gson = new Gson();
String expectedJson = gson.toJson(expectedReturnedData);
JSONAssert.assertEquals(expectedJson, result.getResponse().getContentAsString(), false);
}
@Test
public void isExistMobileNumber() throws Exception{
Mockito.when(userManager.isExistEmail(Mockito.anyString())).thenReturn(false);
RequestBuilder requestBuilder = MockMvcRequestBuilders.get("http://localhost:8081/api.test/v1/User/082133999623")
.accept(MediaType.ALL_VALUE);
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
/*excpected return json
* {
"content": {
"status": 200,
"message": "OK",
"detailmessage": null,
"executiontime": 0,
"detailInfo": "OK"
}
}
*/
MasterViewModel expectedReturnedData = new MasterViewModel();
ErrorDetail info = new ErrorDetail();
info.setMessage(HttpStatus.NO_CONTENT.name());
info.setStatus(HttpStatus.NO_CONTENT.value());
info.setDetailInfo(HttpStatus.NO_CONTENT);
expectedReturnedData.setContent(info);
Gson gson = new Gson();
String expectedJson = gson.toJson(expectedReturnedData);
JSONAssert.assertEquals(expectedJson, result.getResponse().getContentAsString(), false);
}
// @Test
// public void saveNewUser(){
// ErrorDetail expectedInfo = new ErrorDetail();
// expectedInfo.setStatus(HttpStatus.OK.value());
// expectedInfo.setMessage(HttpStatus.OK.name());
// expectedInfo.setDetailInfo(HttpStatus.OK);
// expectedInfo.setDetailmessage(1);
//
// Mockito.when(userManager.isExistEmail(Mockito.anyString())).thenReturn(false);
// Mockito.when(userManager.isExistMobileNumber(Mockito.anyString())).thenReturn(false);
//
// Mockito.when(userManager.getInfo()).thenReturn(expectedInfo);
// MasterViewModel
// Gson gson = new Gson();
// String expectedJson = gson.
// }
}
| true
|
d7121491b09d6afb4c8cb2db038220b464a62bcd
|
Java
|
emergon/SalesCompanySpringMVC
|
/src/main/java/com/emergon/service/SuperService.java
|
UTF-8
| 258
| 1.96875
| 2
|
[] |
no_license
|
package com.emergon.service;
import java.util.List;
/* @author emergon */
public interface SuperService<T> {
List<T> findAll();
T findById(int id);
void save(T t);
void remove(int id);
List<T> search(String searchName);
}
| true
|
fad9e1be7071b610ab17710d842e75bd3601d99d
|
Java
|
shyamkalariya/Automatic_ememo_generation
|
/src/com/VO/LocationVO.java
|
UTF-8
| 1,026
| 2.296875
| 2
|
[] |
no_license
|
package com.VO;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="Location")
public class LocationVO {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int locationId;
@Column(name="Location_name")
private String locationName;
@Column(name="Description")
private String locationDescription;
public int getLocationId() {
return locationId;
}
public void setLocationId(int locationId) {
this.locationId = locationId;
}
public String getLocationName() {
return locationName;
}
public void setLocationName(String locationName) {
this.locationName = locationName;
}
public String getLocationDescription() {
return locationDescription;
}
public void setLocationDescription(String locationDescription) {
this.locationDescription = locationDescription;
}
}
| true
|
5fd14561dcd4a57f4c1d33b08e191f2de509d793
|
Java
|
acanedairri/StrasaWeb
|
/src/main/java/org/strasa/middleware/mapper/DistributionAndExtensionMapper.java
|
UTF-8
| 9,263
| 1.710938
| 2
|
[] |
no_license
|
package org.strasa.middleware.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.DeleteProvider;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.annotations.UpdateProvider;
import org.apache.ibatis.type.JdbcType;
import org.strasa.middleware.model.DistributionAndExtension;
import org.strasa.middleware.model.DistributionAndExtensionExample;
public interface DistributionAndExtensionMapper {
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table distributionandextension
* @mbggenerated Wed Mar 12 09:07:47 SGT 2014
*/
@SelectProvider(type = DistributionAndExtensionSqlProvider.class, method = "countByExample")
int countByExample(DistributionAndExtensionExample example);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table distributionandextension
* @mbggenerated Wed Mar 12 09:07:47 SGT 2014
*/
@DeleteProvider(type = DistributionAndExtensionSqlProvider.class, method = "deleteByExample")
int deleteByExample(DistributionAndExtensionExample example);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table distributionandextension
* @mbggenerated Wed Mar 12 09:07:47 SGT 2014
*/
@Delete({ "delete from distributionandextension",
"where id = #{id,jdbcType=INTEGER}" })
int deleteByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table distributionandextension
* @mbggenerated Wed Mar 12 09:07:47 SGT 2014
*/
@Insert({
"insert into distributionandextension (programid, projectid, ",
"germplasmname, yearextension, ",
"locationextension, countryextension, ",
"plantingarea, datasource, ",
"seedavailability, amountseeddistributed, ",
"numfarmersadopted, amountseedsproduced, ",
"userid)",
"values (#{programid,jdbcType=INTEGER}, #{projectid,jdbcType=INTEGER}, ",
"#{germplasmname,jdbcType=VARCHAR}, #{yearextension,jdbcType=VARCHAR}, ",
"#{locationextension,jdbcType=VARCHAR}, #{countryextension,jdbcType=VARCHAR}, ",
"#{plantingarea,jdbcType=DOUBLE}, #{datasource,jdbcType=VARCHAR}, ",
"#{seedavailability,jdbcType=INTEGER}, #{amountseeddistributed,jdbcType=INTEGER}, ",
"#{numfarmersadopted,jdbcType=INTEGER}, #{amountseedsproduced,jdbcType=DOUBLE}, ",
"#{userid,jdbcType=INTEGER})" })
@Options(useGeneratedKeys = true, keyProperty = "id")
int insert(DistributionAndExtension record);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table distributionandextension
* @mbggenerated Wed Mar 12 09:07:47 SGT 2014
*/
@InsertProvider(type = DistributionAndExtensionSqlProvider.class, method = "insertSelective")
@Options(useGeneratedKeys = true, keyProperty = "id")
int insertSelective(DistributionAndExtension record);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table distributionandextension
* @mbggenerated Wed Mar 12 09:07:47 SGT 2014
*/
@SelectProvider(type = DistributionAndExtensionSqlProvider.class, method = "selectByExample")
@Results({
@Result(column = "id", property = "id", jdbcType = JdbcType.INTEGER, id = true),
@Result(column = "programid", property = "programid", jdbcType = JdbcType.INTEGER),
@Result(column = "projectid", property = "projectid", jdbcType = JdbcType.INTEGER),
@Result(column = "germplasmname", property = "germplasmname", jdbcType = JdbcType.VARCHAR),
@Result(column = "yearextension", property = "yearextension", jdbcType = JdbcType.VARCHAR),
@Result(column = "locationextension", property = "locationextension", jdbcType = JdbcType.VARCHAR),
@Result(column = "countryextension", property = "countryextension", jdbcType = JdbcType.VARCHAR),
@Result(column = "plantingarea", property = "plantingarea", jdbcType = JdbcType.DOUBLE),
@Result(column = "datasource", property = "datasource", jdbcType = JdbcType.VARCHAR),
@Result(column = "seedavailability", property = "seedavailability", jdbcType = JdbcType.INTEGER),
@Result(column = "amountseeddistributed", property = "amountseeddistributed", jdbcType = JdbcType.INTEGER),
@Result(column = "numfarmersadopted", property = "numfarmersadopted", jdbcType = JdbcType.INTEGER),
@Result(column = "amountseedsproduced", property = "amountseedsproduced", jdbcType = JdbcType.DOUBLE),
@Result(column = "userid", property = "userid", jdbcType = JdbcType.INTEGER) })
List<DistributionAndExtension> selectByExample(
DistributionAndExtensionExample example);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table distributionandextension
* @mbggenerated Wed Mar 12 09:07:47 SGT 2014
*/
@Select({
"select",
"id, programid, projectid, germplasmname, yearextension, locationextension, countryextension, ",
"plantingarea, datasource, seedavailability, amountseeddistributed, numfarmersadopted, ",
"amountseedsproduced, userid", "from distributionandextension",
"where id = #{id,jdbcType=INTEGER}" })
@Results({
@Result(column = "id", property = "id", jdbcType = JdbcType.INTEGER, id = true),
@Result(column = "programid", property = "programid", jdbcType = JdbcType.INTEGER),
@Result(column = "projectid", property = "projectid", jdbcType = JdbcType.INTEGER),
@Result(column = "germplasmname", property = "germplasmname", jdbcType = JdbcType.VARCHAR),
@Result(column = "yearextension", property = "yearextension", jdbcType = JdbcType.VARCHAR),
@Result(column = "locationextension", property = "locationextension", jdbcType = JdbcType.VARCHAR),
@Result(column = "countryextension", property = "countryextension", jdbcType = JdbcType.VARCHAR),
@Result(column = "plantingarea", property = "plantingarea", jdbcType = JdbcType.DOUBLE),
@Result(column = "datasource", property = "datasource", jdbcType = JdbcType.VARCHAR),
@Result(column = "seedavailability", property = "seedavailability", jdbcType = JdbcType.INTEGER),
@Result(column = "amountseeddistributed", property = "amountseeddistributed", jdbcType = JdbcType.INTEGER),
@Result(column = "numfarmersadopted", property = "numfarmersadopted", jdbcType = JdbcType.INTEGER),
@Result(column = "amountseedsproduced", property = "amountseedsproduced", jdbcType = JdbcType.DOUBLE),
@Result(column = "userid", property = "userid", jdbcType = JdbcType.INTEGER) })
DistributionAndExtension selectByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table distributionandextension
* @mbggenerated Wed Mar 12 09:07:47 SGT 2014
*/
@UpdateProvider(type = DistributionAndExtensionSqlProvider.class, method = "updateByExampleSelective")
int updateByExampleSelective(
@Param("record") DistributionAndExtension record,
@Param("example") DistributionAndExtensionExample example);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table distributionandextension
* @mbggenerated Wed Mar 12 09:07:47 SGT 2014
*/
@UpdateProvider(type = DistributionAndExtensionSqlProvider.class, method = "updateByExample")
int updateByExample(@Param("record") DistributionAndExtension record,
@Param("example") DistributionAndExtensionExample example);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table distributionandextension
* @mbggenerated Wed Mar 12 09:07:47 SGT 2014
*/
@UpdateProvider(type = DistributionAndExtensionSqlProvider.class, method = "updateByPrimaryKeySelective")
int updateByPrimaryKeySelective(DistributionAndExtension record);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table distributionandextension
* @mbggenerated Wed Mar 12 09:07:47 SGT 2014
*/
@Update({
"update distributionandextension",
"set programid = #{programid,jdbcType=INTEGER},",
"projectid = #{projectid,jdbcType=INTEGER},",
"germplasmname = #{germplasmname,jdbcType=VARCHAR},",
"yearextension = #{yearextension,jdbcType=VARCHAR},",
"locationextension = #{locationextension,jdbcType=VARCHAR},",
"countryextension = #{countryextension,jdbcType=VARCHAR},",
"plantingarea = #{plantingarea,jdbcType=DOUBLE},",
"datasource = #{datasource,jdbcType=VARCHAR},",
"seedavailability = #{seedavailability,jdbcType=INTEGER},",
"amountseeddistributed = #{amountseeddistributed,jdbcType=INTEGER},",
"numfarmersadopted = #{numfarmersadopted,jdbcType=INTEGER},",
"amountseedsproduced = #{amountseedsproduced,jdbcType=DOUBLE},",
"userid = #{userid,jdbcType=INTEGER}",
"where id = #{id,jdbcType=INTEGER}" })
int updateByPrimaryKey(DistributionAndExtension record);
}
| true
|
9271efe93678c6db564ff63fc388a3cec80ef174
|
Java
|
umangupta992018/JAVA-PROGRAMS
|
/subarray_check.java
|
UTF-8
| 958
| 3.46875
| 3
|
[] |
no_license
|
import java.util.*;
public class subarray_check
{
public static boolean subarraycheck(int arr1[],int n1,int arr[],int n)
{
int i=0,j=0;
for(i=0;i<n;i++)
{
for(j=0;j<n1;j++)
{
if(arr[i]==arr1[j])
{
break;
}
}
if(j==n1)
return false;
}
return true;
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter The Size Of The Array : ");
int n2=sc.nextInt();
int arr[]=new int[n2];
System.out.println("\n\nArray Elements Are : ");
for(int i=0;i<n2;i++)
{
arr[i]=sc.nextInt();
}
System.out.println("Enter The Size Of The SubArray : ");
int n3=sc.nextInt();
int arr1[]=new int[n3];
for(int j=0;j<n3;j++)
{
arr1[j]=sc.nextInt();
}
if(n3<=n2)
{
if(subarraycheck(arr,n2,arr1,n3))
{
System.out.println("Yes SubArray");
}
else
{
System.out.println("No SubArray");
}
}}
}
| true
|
5e4163ffaa7c11d85433c0559f9510d191fc2ef8
|
Java
|
nibill/ch.bfh.bti7301.superstartrek2
|
/src/ch/bfh/bti7301/superstartrek/state/GameState.java
|
UTF-8
| 13,570
| 2.5
| 2
|
[] |
no_license
|
package ch.bfh.bti7301.superstartrek.state;
import ch.bfh.bti7301.superstartrek.graphics.*;
import ch.bfh.bti7301.superstartrek.misc.*;
import ch.bfh.bti7301.superstartrek.misc.MsgCharacter;
import ch.bfh.bti7301.superstartrek.model.*;
import ch.bfh.bti7301.superstartrek.sounds.SoundBoard;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
/**
* Created by florianauderset on 02.12.16.
*/
public class GameState extends State {
private SubPanel mainPanel;
private WeaponPanel weaponPanel;
private StatusPanel statusPanel;
private MessagePanel messagePanel;
private InfoPanel infoPanel;
private MessageGenerator msgGenerator;
private BorderLayout layout = new BorderLayout();
private Level[][] levels;
private Level currentLevel;
private ArrayList<SpaceObject> spaceobjects;
private ArrayList<Background> backgrounds = new ArrayList<Background>();
private int score = 0;
private StarFleetShip player;
private BufferedImage background;
private Boolean initialized = false;
private LevelStateMachine lsm;
private int msgTimer = 0;
private int missionTimer = 0;
private Boolean missionTold = false;
/**
* overloaded constructor
* @param stateMachine StateMachine object
*/
public GameState(StateMachine stateMachine) {
super(stateMachine);
lsm = new LevelStateMachine(this);
mainPanel = new MainPanel(this, 640, 480);
weaponPanel = new WeaponPanel(this, 192, 480);
statusPanel = new StatusPanel(this, 192, 480);
messagePanel = new MessagePanel(this, 1024, 200);
infoPanel = new InfoPanel(this, 1024, 88);
mainPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
statusPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
weaponPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
infoPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
messagePanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
/* add panels */
getPanels().add(mainPanel);
getPanels().add(weaponPanel);
getPanels().add(statusPanel);
getPanels().add(messagePanel);
getPanels().add(infoPanel);
/* Initialize variables defined on top of the class */
backgrounds.add(new Background("background_black.jpg", 0.1));
backgrounds.add(new Background("background_blue.jpg", 0.1));
backgrounds.add(new Background("background_purple.jpg", 0.1));
backgrounds.add(new Background("background_darkpurple.jpg", 0.1));
msgGenerator = new MessageGenerator();
/* initialize game */
initGame();
}
public void initGame(){
initlevels(GamePanel.GAMESIZE);
/* Initialize game objects */
player = new StarFleetShip(98, 75, ((640 / 2) - (98 / 2)), 480 / 3 * 2, 1, 0, 0, 100, 100);
/* initialize spaceobjects with meteors, enemies and spacestations */
spaceobjects = currentLevel.getCurrentquardant().getSpaceobjects();
}
private void initlevels(int size) {
levels = new LevelGenerator(size).getLevels();
currentLevel = levels[0][0];
}
/**
* Handles the input
*/
public void input() {
/* check input of all spaceobjects */
player.input();
for (SpaceObject so : spaceobjects) {
so.input();
}
}
/**
* Updates the GameState
*/
public void update() {
/* check if mission has already told */
if (!missionTold){
if (missionTimer < 35*GamePanel.FPS){
missionTimer++;
} else{
missionTold = true;
}
}
/* check if mission goal is reached */
Boolean gameover = true;
Quadrant[][] quadrants = currentLevel.getQuadrants();
for (int i = 0; i < quadrants.length; i++){
for (int j = 0; j < quadrants[i].length; j++){
for (SpaceObject so : quadrants[i][j].getSpaceobjects()){
if (so instanceof EnemyShip){
gameover = false;
}
}
}
}
if (gameover || player.isDead()){
getStateMachine().change("gameover");
}
/* Check collisions and update position */
player.update();
player.checkAttackCollisions(spaceobjects);
for(SpaceObject so: spaceobjects){
if(so instanceof SpaceStation && player.intersects(so)){
player.setHealth(player.getHealthMax());
player.setShield(player.getShieldMax());
}
}
for (int i = 0; i < spaceobjects.size(); i++){
SpaceObject so = spaceobjects.get(i);
so.checkAttackCollisions(spaceobjects);
if (so instanceof EnemyShip) {
((EnemyShip) so).update(player);
if(((EnemyShip) so).isDead()){
score += 100;
spaceobjects.add(new Explosion(so.getX(), so.getY()));
spaceobjects.remove(so);
}
if (missionTold){
if (msgTimer < 10)
{
msgGenerator.createMessage(MsgCharacter.KLINGON, MessageType.ALERT, 5, "bortaS bIr jablu'DI' reH\nQaQqu' nay'!");
}
msgTimer++;
}
} else if (so instanceof Meteor) {
so.update();
} else if (so instanceof Explosion) {
so.update();
if(so.shouldRemove()){
spaceobjects.remove(so);
i--;
}
}else {
so.update();
}
}
// check if levels user leaves quadrant
// check if player leaves right
if (player.getX() >= 640) {
if (currentLevel.getCurrentquardant().getQuadrantnr() % GamePanel.GAMESIZE == 0) {
msgGenerator.createMessage(MsgCharacter.SPOCK, MessageType.NORMAL, 3, "This is not part of our\nmission, Captain!");
player.setSpeed(0);
player.setX(580);
} else {
currentLevel.getCurrentquardant().setVisited(true);
lsm.changeQuadrant(currentLevel.getQuadrantByNr(currentLevel.getCurrentquardant().getQuadrantnr() + 1));
player.setX(0);
msgTimer = 0;
}
}
// check if player leaves left
if (player.getX() < -20) {
if (currentLevel.getCurrentquardant().getQuadrantnr() % GamePanel.GAMESIZE == 1) {
msgGenerator.createMessage(MsgCharacter.SPOCK, MessageType.NORMAL, 3, "This is not part of our\nmission, Captain!");
player.setSpeed(0);
player.setX(20);
} else {
currentLevel.getCurrentquardant().setVisited(true);
lsm.changeQuadrant(currentLevel.getQuadrantByNr(currentLevel.getCurrentquardant().getQuadrantnr() -1));
player.setX(640);
msgTimer = 0;
}
}
// check if player leaves top
if (player.getY() < -50) {
if (currentLevel.getCurrentquardant().getQuadrantnr() <= GamePanel.GAMESIZE) {
msgGenerator.createMessage(MsgCharacter.SPOCK, MessageType.NORMAL, 3, "This is not part of our\nmission, Captain!");
player.setSpeed(0);
player.setY(30);
} else {
currentLevel.getCurrentquardant().setVisited(true);
lsm.changeQuadrant(currentLevel.getQuadrantByNr(currentLevel.getCurrentquardant().getQuadrantnr() - GamePanel.GAMESIZE));
player.setY(479);
msgTimer = 0;
}
}
// check if player leaves bottom
if (player.getY() >= 480) {
if (currentLevel.getCurrentquardant().getQuadrantnr() > (GamePanel.GAMESIZE * (GamePanel.GAMESIZE -1))) {
msgGenerator.createMessage(MsgCharacter.SPOCK, MessageType.NORMAL, 3, "This is not part of\nour mission, Captain!");
player.setSpeed(0);
player.setY(460);
} else {
currentLevel.getCurrentquardant().setVisited(true);
lsm.changeQuadrant(currentLevel.getQuadrantByNr(currentLevel.getCurrentquardant().getQuadrantnr() + GamePanel.GAMESIZE));
player.setY(0);
msgTimer = 0;
}
}
/* Update scores etc if necessary */
// update backgrounds
for (Background bg : backgrounds) {
bg.update(player);
}
}
/**
* Create mission message
*/
public void tellMission(){
msgGenerator.createMessage(MsgCharacter.SCOTT, MessageType.NORMAL, 30, "Captain, we have to\nneutralize all Klingons in\nthe Galaxy " + currentLevel.getName() + "\nTake care of the Enterprise Kirk!");
}
/**
* Handles the state entering
*/
public void enter() {
/* do stuff when entering this state */
initialized = true;
spaceobjects = currentLevel.getCurrentquardant().getSpaceobjects();
layout.setVgap(0);
getGamePanel().setLayout(layout);
getGamePanel().add(mainPanel, BorderLayout.CENTER);
getGamePanel().add(statusPanel, BorderLayout.LINE_START);
getGamePanel().add(weaponPanel, BorderLayout.LINE_END);
getGamePanel().add(infoPanel, BorderLayout.PAGE_START);
getGamePanel().add(messagePanel, BorderLayout.PAGE_END);
SoundBoard.BACKGROUND.play();
tellMission();
}
/**
* Handles the exiting of the State
*/
public void exit() {
/* do stuff when exiting this state */
SoundBoard.BACKGROUND.pause();
}
/**
* Handles the user input
* @param e KeyEvent
*/
public void keyPressed(KeyEvent e) {
/* do something with the input */
int key = e.getKeyCode();
if (key == KeyEvent.VK_P) {
getStateMachine().change("paused");
}
if (key == KeyEvent.VK_M) {
getStateMachine().change("map");
}
if (key == KeyEvent.VK_ESCAPE) {
getStateMachine().change("menu");
}
if (key == KeyEvent.VK_SPACE) {
if(player.shieldUp()){
msgGenerator.createMessage(MsgCharacter.SCOTT, MessageType.ALERT, 3, "Lower the shields to\nuse the Phaser, Captain!");
}
else {
player.fire(0);
}
}
if (key == KeyEvent.VK_S) {
if (player.getShield() > 0){
player.toggleShield();
SoundBoard.BUTTON2.play();
if (player.shieldUp()){
msgGenerator.createMessage(MsgCharacter.SCOTT, MessageType.NORMAL, 3, "Shields up!");
}
else{
msgGenerator.createMessage(MsgCharacter.SCOTT, MessageType.ALERT, 3, "Shields down!");
}
}
else{
msgGenerator.createMessage(MsgCharacter.SCOTT, MessageType.ALERT, 3, "Shields severely damaged,\nCaptain!");
}
}
if (key == KeyEvent.VK_G) {
if (player.getWeapons().get(1).getCapacity() > 0){
if(player.shieldUp()){
msgGenerator.createMessage(MsgCharacter.SCOTT, MessageType.ALERT, 3, "We can't shoot through the\nshield, Captain!");
}
else {
player.fire(1);
}
}
else{
msgGenerator.createMessage(MsgCharacter.SCOTT, MessageType.NORMAL, 3, "We're out of grenades,\nCaptain!");
SoundBoard.NOTIFICATION.play();
}
}
if (key == KeyEvent.VK_UP) {
player.speedUp();
}
if (key == KeyEvent.VK_DOWN) {
player.slowDown();
}
if (key == KeyEvent.VK_LEFT) {
player.turnLeft();
}
if (key == KeyEvent.VK_RIGHT) {
player.turnRight();
}
}
@Override
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public Level[][] getLevels() {
return levels;
}
public Level getCurrentLevel() {
return currentLevel;
}
public void setCurrentLevel(Level currentLevel) {
this.currentLevel = currentLevel;
}
public ArrayList<SpaceObject> getSpaceobjects() {
return spaceobjects;
}
public void setSpaceobjects(ArrayList<SpaceObject> spaceobjects) {
this.spaceobjects = spaceobjects;
}
public ArrayList<Background> getBackgrounds() {
return backgrounds;
}
public StarFleetShip getPlayer() {
return player;
}
public BufferedImage getBackground() {
return background;
}
public Boolean isInitialized() {
return initialized;
}
public MessageGenerator getMsg() {
return msgGenerator;
}
public void setMsg(MessageGenerator msg) {
this.msgGenerator = msg;
}
}
| true
|
9adfb98fb5ee7038470c26ccbaf2c5e5fc1be344
|
Java
|
Kevin-Mok/kogito-apps
|
/explainability/explainability-core/src/test/java/org/kie/kogito/explainability/utils/RandomChoiceTest.java
|
UTF-8
| 4,870
| 2.609375
| 3
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2021 Red Hat, Inc. and/or its affiliates.
*
* 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.kie.kogito.explainability.utils;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import static org.junit.jupiter.api.Assertions.*;
class RandomChoiceTest {
List<String> obj = List.of("a", "b", "c", "d", "e");
@ParameterizedTest
@ValueSource(ints = { 0, 1, 2 })
void testOnlyOneWeight(int seed) {
Random rn = new Random();
rn.setSeed(seed);
// if only one weight is nonzero, all samples should be equal to the object corresponding to that weight
List<String> output = List.of("c", "c", "c");
List<Double> weights = List.of(0., 0., 1., 0., 0.);
RandomChoice<String> rc = new RandomChoice<>(obj, weights);
assertEquals(output, rc.sample(3, rn));
}
@ParameterizedTest
@ValueSource(ints = { 0, 1, 2 })
void testTwoWeight(int seed) {
Random rn = new Random();
rn.setSeed(seed);
// if two weights are nonzero, all samples should correspond to one of those two objects
List<Double> weights = List.of(1., 0., 1., 0., 0.);
RandomChoice<String> rc = new RandomChoice<>(obj, weights);
List<String> sample = rc.sample(5, rn);
for (int i = 0; i < sample.size(); i++) {
assertTrue((sample.get(i).equals("a") || sample.get(i).equals("c")));
}
;
}
@Test
void weightMismatch() {
// if the weights don't match, raise error
List<Double> weights = List.of(1., 1., 0.);
assertThrows(IllegalArgumentException.class, () -> new RandomChoice<>(obj, weights));
}
@ParameterizedTest
@ValueSource(ints = { 0, 1, 2 })
void testUniform(int seed) {
RandomChoice<String> rc = new RandomChoice<>(obj);
Random rn = new Random();
rn.setSeed(seed);
for (int test = 0; test < 100; test++) {
List<String> sample = rc.sample(1000, rn);
//find the total number of samples of each object
HashMap<String, Integer> results = new HashMap<>();
for (String ith : sample) {
results.putIfAbsent(ith, 0);
results.put(ith, results.get(ith) + 1);
}
// assuming the above samples are drawn from a uniform binomial distribution,
// the counts of each object will fall outside these bounds only once every 1e30 tests.
// if we ran one test a second, it'd take an octillion years for a single one to fail
for (String ith : obj) {
assertTrue(results.get(ith) > 70);
assertTrue(results.get(ith) < 324);
}
}
}
@ParameterizedTest
@ValueSource(ints = { 0, 1, 2 })
void testMultiWeight(int seed) {
List<Double> weights = List.of(5., 4., 3., 2., 1.);
RandomChoice<String> rc = new RandomChoice<>(obj, weights);
Random rn = new Random();
rn.setSeed(seed);
for (int test = 0; test < 100; test++) {
List<String> sample = rc.sample(1000, rn);
//find the total number of samples of each object
HashMap<String, Integer> results = new HashMap<>();
for (String ith : sample) {
results.putIfAbsent(ith, 0);
results.put(ith, results.get(ith) + 1);
}
// assuming the above samples are drawn from a binomial distribution,
// the counts of each object will fall outside these bounds only once every 1e30 tests.
// if we ran one test a second, it'd take an octillion years for a single one to fail
assertTrue(results.get("a") > 171);
assertTrue(results.get("a") < 475);
assertTrue(results.get("b") > 118);
assertTrue(results.get("b") < 401);
assertTrue(results.get("c") > 70);
assertTrue(results.get("c") < 324);
assertTrue(results.get("d") > 28);
assertTrue(results.get("d") < 242);
assertTrue(results.get("e") > 28);
assertTrue(results.get("e") < 151);
}
}
}
| true
|
7e49b0f2bea717ee91a42de26bb63520d67f1472
|
Java
|
vasskob/Facebook-GPlusSDK
|
/app/src/main/java/com/task/vasskob/facebookgplussdk/helper/profile/GoogleUserProfileHelper.java
|
UTF-8
| 2,998
| 2.0625
| 2
|
[] |
no_license
|
package com.task.vasskob.facebookgplussdk.helper.profile;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.plus.Plus;
import com.google.android.gms.plus.PlusShare;
import com.google.android.gms.plus.model.people.Person;
import com.task.vasskob.facebookgplussdk.model.User;
import static com.task.vasskob.facebookgplussdk.aplication.Application.mGoogleApiClient;
public class GoogleUserProfileHelper extends UserProfileHelper {
private final static String TAG = GoogleUserProfileHelper.class.getSimpleName();
private static final int SHARE_PHOTO_TO_GOOGLE_PLUS = 0;
private static final String PERSON_WARN = "User can`t be loaded";
private final Fragment mFragment;
public GoogleUserProfileHelper(Fragment fragment) {
mFragment = fragment;
}
@Override
public void loadUserProfile(OnUserLoadedListener loadedListener) {
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
Person currentPerson = Plus.PeopleApi
.getCurrentPerson(mGoogleApiClient);
String uName = currentPerson.getDisplayName();
String uPhotoUrl = currentPerson.getImage().getUrl();
String uBirthday = currentPerson.getBirthday();
String uEmail = Plus.AccountApi.getAccountName(mGoogleApiClient);
Log.d(TAG, "loadUserProfile: userName = " + uName + " uEmail=" + uEmail +
" uBirthday=" + currentPerson.getBirthday() + " uPhotoUrl =" + uPhotoUrl);
User user = new User(uName, uEmail, uBirthday, uPhotoUrl);
loadedListener.onLoadSuccess(user);
} else {
Log.e(TAG, "getUser user = null");
Toast.makeText(mFragment.getActivity(), PERSON_WARN, Toast.LENGTH_LONG).show();
}
}
@Override
public void logout(OnLogoutListener listener) {
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
@Override
public void onResult(@NonNull Status status) {
Log.d(TAG, "signOutGPlus onResult:" + status);
}
});
listener.onLogoutSuccess();
}
@Override
public void postMedia(Uri media) {
if (media != null) {
Intent share = new PlusShare.Builder(mFragment.getActivity())
.setText(POST_TITLE)
.addStream(media)
.setContentDeepLinkId("Hello!") //does not work without this
.getIntent();
mFragment.startActivityForResult(share, SHARE_PHOTO_TO_GOOGLE_PLUS);
}
}
}
| true
|
34376a2fef3e068a1bcfc350b1f3b84f69273061
|
Java
|
lastvirgo266/AlgorithmProblem
|
/Programmers/비밀지도_v1.java
|
UTF-8
| 1,548
| 3.21875
| 3
|
[] |
no_license
|
class Solution {
public String[] solution(int n, int[] arr1, int[] arr2) {
String[] answer = new String[n];
for(int i=0; i<arr1.length; i++){
String result = binaryChange(arr1[i], n);
String subAns = "";
for(int j=0; j<result.length(); j++){
if(result.charAt(j) == '1')
subAns += "#";
else
subAns += " ";
}
answer[i] = subAns;
}
for(int i=0; i<arr2.length; i++){
String result = binaryChange(arr2[i], n);
StringBuilder builder = new StringBuilder(answer[i]);
for(int j=0; j<result.length(); j++){
if(result.charAt(j) == '1')
builder.setCharAt(j, '#');
}
answer[i] = builder.toString();
}
//System.out.println(binaryChange(0,5));
return answer;
}
public String binaryChange(int number, int n){
String result = "";
while(number != 0){
result += Integer.toString(number%2);
number /= 2;
}
if(result.length() < n){
int remind = n-result.length();
for(int i=0; i<remind; i++)
result +="0";
}
return ( new StringBuffer(result) ).reverse().toString();
}
}
| true
|
0bd578eeffdc274660fa710752cbf78b37261dc2
|
Java
|
gargimk/CarTracker
|
/api/src/main/java/com/egenSolution/CarTracker/database/DatabaseService.java
|
UTF-8
| 2,802
| 2.40625
| 2
|
[] |
no_license
|
package com.egenSolution.CarTracker.database;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import com.egenSolution.CarTracker.modules.Alert;
import com.egenSolution.CarTracker.modules.Readings;
import com.egenSolution.CarTracker.modules.Tires;
import com.egenSolution.CarTracker.modules.Vehicle;
public class DatabaseService {
ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringMongoConfig.class);
MongoOperations mongoOperation = (MongoOperations) ctx.getBean("mongoTemplate");
public void saveVehicles(List<Vehicle> vehicleList) {
for (Vehicle vehicle : vehicleList)
mongoOperation.save(vehicle);
}
public void saveReadings(Readings readings) {
mongoOperation.save(readings);
}
public void generateAlert(Readings readings) {
Alert alert;
Vehicle vehicle = mongoOperation.findOne(new Query(Criteria.where("vin").is(readings.getVin())), Vehicle.class);
if (readings.getEngineRpm() > vehicle.getReadlineRpm()) {
alert = new Alert();
alert.setMessage("High priority:engineRpm is greater than readLineRpm");
alert.setVin(readings.getVin());
alert.setRule("engineRpm is greater than readLineRpm");
alert.setPriority("HIGH");
mongoOperation.save(alert);
}
if (readings.getFuelVolume() < 0.1 * vehicle.getMaxFuelVolume()) {
alert = new Alert();
alert.setMessage("Medium priority:fuelVolume is less than 10% of maxFuelVolume");
alert.setVin(readings.getVin());
alert.setRule("fuelVolume is less than 10% of maxFuelVolume");
alert.setPriority("MEDIUM");
mongoOperation.save(alert);
}
if (isTirePressureOutOfLimit(readings)) {
alert = new Alert();
alert.setMessage("Low priority:tire pressure out of limit");
alert.setVin(readings.getVin());
alert.setRule("tire pressure of any tire < 32psi or >36psi");
alert.setPriority("LOW");
mongoOperation.save(alert);
}
if (readings.isEngineCoolantLow() || readings.isCheckEngineLightOn()) {
alert = new Alert();
alert.setMessage("Low priority:engineCoolantLow or engineLightOn");
alert.setVin(readings.getVin());
alert.setRule("engineCoolantLow or engineLightOn");
alert.setPriority("LOW");
mongoOperation.save(alert);
}
}
public boolean isTirePressureOutOfLimit(Readings readings){
Tires tires = readings.getTires();
return tires.getFrontLeft()<32||tires.getFrontLeft()>36||tires.getFrontRight()<32||tires.getFrontRight()>36||tires.getRearLeft()<32||tires.getRearLeft()>36||tires.getRearRight()<32||tires.getRearRight()>36;
}
}
| true
|
8eb09fe969cc5d1979c1a50f23443577edffa49a
|
Java
|
kovalevivan/library-management
|
/src/main/java/com/ikoval/libman/server/service/BookService.java
|
UTF-8
| 2,738
| 2.671875
| 3
|
[] |
no_license
|
package com.ikoval.libman.server.service;
import com.ikoval.libman.server.domain.Book;
import com.ikoval.libman.server.exception.BadRequestException;
import com.ikoval.libman.server.exception.BookNotFoundException;
import com.ikoval.libman.server.repository.BookRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import java.util.Optional;
/**
* Validates parameters and retrieves books from the database.
*
*/
@Service
public class BookService {
private BookRepository bookRepository;
public BookService(BookRepository bookRepository) {
this.bookRepository = bookRepository;
}
/**
* Retrieve a {@link Page} of the {@link Book} matching the given {@link Specification}
*
* @param specification can be {@literal null}.
* @param pageRequest must not be {@literal null}.
* @return page, never {@literal null}.
* @throws BadRequestException when pageRequest is null.
*/
public Page<Book> findAll(Specification<Book> specification, PageRequest pageRequest) throws BadRequestException {
if(pageRequest == null) throw new BadRequestException("Request must not be null");
return bookRepository.findAll(specification,pageRequest);
}
/**
* Retrieve a {@link Book} by its id.
*
* @param id must not be {@literal null}.
* @return Book with the given id.
* @throws BookNotFoundException in case the given id wasn't found.
*/
public Book findById(Long id) throws BookNotFoundException {
if(id == null) throw new IllegalArgumentException("Field id must not be null");
Optional<Book> opt = bookRepository.findById(id);
return opt.orElseThrow(() -> new BookNotFoundException("Book not found"));
}
/**
* Save the given book.
*
* @param book must not be {@literal null}.
* @return the saved book will never be {@literal null}.
* @throws IllegalArgumentException in case the given book is {@literal null}.
*/
public Book save( Book book) throws IllegalArgumentException {
if(book == null) throw new IllegalArgumentException("Book must not be null");
return bookRepository.save(book);
}
/**
* Delete a book by its id.
*
* @param id must not be {@literal null}.
* @throws IllegalArgumentException in case the given id is {@literal null}.
*/
public void delete(Long id) throws IllegalArgumentException {
if(id == null) throw new IllegalArgumentException("Field id must not be null");
bookRepository.deleteById(id);
}
}
| true
|
61f03c374d9f273468884c4bd8b9a53103d7546b
|
Java
|
EdersonSouza02/WorkspaceEtec
|
/src/br/com/sp/gov/vetor/Ex03Vet.java
|
ISO-8859-1
| 594
| 3.078125
| 3
|
[
"Apache-2.0"
] |
permissive
|
package br.com.sp.gov.vetor;
import java.util.Scanner;
public class Ex03Vet {
public static void main(String[] args) {
int num[] = new int[20];
Scanner teclado = new Scanner(System.in);
for (int i = 0; i < num.length; i++) {
System.out.println("Insira o :" + ( i + 1 ) + " nmero : " );
num[i] = teclado.nextInt();
}
for (int i = 10; i < num.length; i--) {
System.out.println(num[i]);
}
for (int i = 10; i < num.length; i--) {
System.out.println(num[i]);
teclado.close();
System.exit(0);
}
}
}
| true
|
fbf18e1432292fb3062d05d3797daae75f2edabb
|
Java
|
CorreaArturo/BasicSecuritySpring
|
/src/main/java/com/indra/security/request/MadRequestHeader.java
|
UTF-8
| 1,042
| 2.609375
| 3
|
[] |
no_license
|
package com.indra.security.request;
/**
* MadRequestHeader.
* @author INDRA
* @since 11/05/2020
*/
public class MadRequestHeader
{
private String min;
private String wvName;
private String wvVersion;
private String uuid;
/**
* Constructor
*/
public MadRequestHeader()
{
super();
}
public MadRequestHeader(String min, String wvName, String wvVersion, String uuid)
{
super();
this.min = min;
this.wvName = wvName.startsWith("/") ? wvName.substring(1) : wvName;
this.wvVersion = wvVersion;
this.uuid = uuid;
}
public String getMin()
{
return min;
}
public String getWvName()
{
return wvName;
}
public String getWvVersion()
{
return wvVersion;
}
public String getUuid()
{
return uuid;
}
@Override
public String toString()
{
return "min: " + min + " - wvVersion: " + wvVersion + " - uuid: " + uuid;
}
}
| true
|
3227a67597a74025a83e9446814bfa80dd97c57d
|
Java
|
Lola1995/prod
|
/GetAplot/app/src/main/java/com/getaplot/getaplot/adapters/UsersProfilePagerAdapter.java
|
UTF-8
| 1,293
| 2.3125
| 2
|
[] |
no_license
|
package com.getaplot.getaplot.adapters;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.getaplot.getaplot.fragments.Profile.HomeFragment;
import com.getaplot.getaplot.fragments.Profile.PostsFragment;
public class UsersProfilePagerAdapter extends FragmentPagerAdapter {
public UsersProfilePagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
HomeFragment topUsersFragment = new HomeFragment();
return topUsersFragment;
case 1:
PostsFragment findUsersFragment = new PostsFragment();
return findUsersFragment;
default:
return null;
}
}
@Override
public int getCount() {
return 2;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Home";
case 1:
return "Posts";
default:
return super.getPageTitle(position);
}
}
}
| true
|
82ec388123cfe74849aa9a6bf3a9ecf82b09ea60
|
Java
|
abhinavmishra14/AlfrescoJMeterLoadTestPlugin
|
/src/com/github/abhinavmishra14/alfresco/utils/Constants.java
|
UTF-8
| 3,878
| 1.765625
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Created By: Abhinav Kumar Mishra
* Copyright © 2014. Abhinav Kumar Mishra.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.abhinavmishra14.alfresco.utils;
/**
* The Class Constants.
*
* @author Abhinav Kumar Mishra
* @since 2014
*/
public final class Constants {
/** The Constant JMETER_HOME. */
public static final String JMETER_HOME = "JMETER_HOME";
/** The Constant EMPTY. */
public static final String EMPTY = "";
/** The Constant LINE_BR. */
public static final String LINE_BR = "\n";
/** The Constant SERVER. */
public static final String SERVER = "server";
/** The Constant BASEPATH. */
public static final String BASEPATH = "baseurl";
/** The Constant LOGIN_PATH. */
public static final String LOGIN_PATH = "authURI";
/** The Constant UPLOAD_PATH. */
public static final String UPLOAD_PATH = "uploadURI";
/** The Constant INPUT_PATH. */
public static final String INPUT_PATH = "inputPath";
/** The Constant DESC. */
public static final String DESC = "description";
/** The Constant USER_PARAM. */
public static final String USER_PARAM = "u";
/** The Constant PASSWORD_PARAM. */
public static final String PASSWORD_PARAM = "pw";
/** The Constant USERNAME. */
public static final String USERNAME = "username";
/** The Constant PASSWORD. */
public static final String PASSWORD = "password";
/** The Constant ENCODING. */
public static final String ENCODING = "UTF-8";
/** The Constant SERVER_ERR. */
public static final String SERVER_ERR = "500";
/** The Constant EQL. */
public static final String EQL = "=";
/** The Constant QUES. */
public static final String QUES = "?";
/** The Constant AMPERSND. */
public static final String AMPERSND = "&";
/** The Constant RESP_BODY. */
public static final String RESP_BODY = "responsebody";
/** The Constant CONTENT_TYPE. */
public static final String CONTENT_TYPE = "content-type";
/** The Constant STATUS_CODE. */
public static final String STATUS_CODE = "statuscode";
/** The Constant CONTENT_TYPE_HDR. */
public static final String CONTENT_TYPE_HDR = "Content-Type";
/** The Constant MIME_TYPE. */
public static final String MIME_TYPE = "application/json";
/** The Constant CONFIG. */
public static final String CONFIG = "config.properties";
/** The Constant TICKET_QRY. */
public static final String TICKET_QRY = "alf_ticket";
/** The Constant SITE_ID. */
public static final String SITE_ID = "siteid";
/** The Constant DESTINATION. */
public static final String DESTINATION = "destination";
/** The Constant CONTAINER_ID. */
public static final String CONTAINER_ID = "containerid";
/** The Constant UPLOAD_DIR. */
public static final String UPLOAD_DIR = "uploaddirectory";
/** The Constant FTP_HOST. */
public static final String FTP_HOST = "ftpHost";
/** The Constant FTP_PORT. */
public static final String FTP_PORT = "ftpPort";
/** The Constant LOCAL_FILE_OR_DIR. */
public static final String LOCAL_FILE_OR_DIR = "localDirectoryPath";
/** The Constant REMOTE_FILE_OR_DIR. */
public static final String REMOTE_FILE_OR_DIR = "remoteDirectoryPath";
/**
* Instantiates a new constants.
*/
private Constants() {
super();
}
}
| true
|
668f051b34cde9f5a1e9898fdec727ce479727a8
|
Java
|
AdorkDean/111_yao_app_mobile
|
/serviceuri/com/rc/openapi/serviceuriV2/AddPrescriptionURIService.java
|
UTF-8
| 7,507
| 1.914063
| 2
|
[] |
no_license
|
package com.rc.openapi.serviceuriV2;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import com.rc.commons.security.BASE64Decoder;
import com.rc.openapi.service.TPrescriptionImageManager;
import com.rc.openapi.service.TPrescriptionManager;
import com.rc.openapi.service.impl.TMemberManagerImpl;
import com.rc.openapi.serviceuri.BaseURIService;
import com.rc.openapi.util.ConstantUtil;
import com.rc.openapi.util.InfoUtil;
import com.rc.openapi.vo.TMember;
import com.rc.openapi.vo.TPrescription;
import com.rc.openapi.vo.TPrescriptionImage;
/**
* 添加病例接口
*
* @author user00
* @createTime 2015-7-23 上午11:23:53
*/
public class AddPrescriptionURIService extends BaseURIService {
private static final long serialVersionUID = 3810393917175631043L;
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map<String, Object> map = new HashMap<String, Object>();
String statusCode = "0";
String message = "";
try {
String sessionid = request.getParameter("sessionid");
String diseaseDescrip = request.getParameter("diseaseDescrip");// 病情描述
// String phone = request.getParameter("phone");
String ifhelp = request.getParameter("ifhelp");// 是否寻求医师帮助
// 病情描述
// final String img1 = request.getParameter("img1");// 图片1
// final String img2 = request.getParameter("img2");// 图片2
// final String img3 = request.getParameter("img3");// 图片3
// final String img4 = request.getParameter("img4");// 图片4
// final String img5 = request.getParameter("img5");// 图片5
// final String img6 = request.getParameter("img6");// 图片6
// final String img7 = request.getParameter("img7");// 图片7
// final String img8 = request.getParameter("img8");// 图片8
// final String img9 = request.getParameter("img9");// 图片9
List<String> imgDataList = new ArrayList<String>();
for (int i = 1; i <= 9; i++) {
if (request.getParameter("img" + (i)) != null && !"".equals(request.getParameter("img" + (i)))) {
imgDataList.add(request.getParameter("img" + (i)));
}
}
TMemberManagerImpl man = (TMemberManagerImpl) getSpringBean("tmembermanager");
TPrescriptionImageManager tPrescriptionImageManager = (TPrescriptionImageManager) getSpringBean("tprescriptionimagemanager");
TPrescriptionManager tPrescriptionManager = (TPrescriptionManager) getSpringBean("tprescriptionmanager");
if (sessionid != null && !"".equals(sessionid.trim())) {
long userId = man.getMemberId(sessionid);
if (userId > 0) {// 存在
List<String> imgUrl = new ArrayList<String>();
if (imgDataList != null && imgDataList.size() > 0) {
imgUrl = uploadImages(imgDataList);
}
TPrescription tPrescription = new TPrescription();
tPrescription.setCreateDate(new Date());
tPrescription.setModifyDate(new Date());
tPrescription.setDiseaseDescrip(diseaseDescrip);
tPrescription.setImageUrl((imgUrl == null || imgUrl.size() <= 0) ? null : imgUrl.get(0));
// 是否需要医师咨询;
TMember tMember = man.getTmemberdao().selectByPrimaryKey(userId);
// 需要医师咨询
if (ifhelp != null && !"".equals(ifhelp) && ifhelp.equals("1")) {
tPrescription.setIfhelp(1);
} else {
tPrescription.setIfhelp(0);
}
if (tMember != null) {
tPrescription.setUserName(tMember.getUserName());
// 联系方式,字段phone不存在的话匹配用户名是否是手机号
if (tMember.getPhone() != null) {
tPrescription.setPhone(tMember.getPhone());
} else if (tMember.getUserName() != null) {
Pattern p = Pattern.compile("^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$");
Matcher m = p.matcher(tMember.getUserName());
tPrescription.setPhone(m.matches() ? tMember.getUserName() : null);
}
}
tPrescription.setStatus(0);
tPrescription.setUploadTime(new Date());
tPrescription.setUserId(userId);
Long prescriptionId = tPrescriptionManager.insertSelective(tPrescription);
TPrescriptionImage tPrescriptionImage = null;
for (String string : imgUrl) {
tPrescriptionImage = new TPrescriptionImage();
tPrescriptionImage.setCreateDate(new Date());
tPrescriptionImage.setModifyDate(new Date());
tPrescriptionImage.setPath(string);
tPrescriptionImage.setPrescriptionId(prescriptionId);
tPrescriptionImageManager.insertSelective(tPrescriptionImage);
}
statusCode = "1";
message = "保存成功";
} else {
message = "请正常登陆";
}
} else {
message = "请先登录";
}
} catch (SQLException e) {
e.printStackTrace();
message = e.getMessage();
}
map.put("statusCode", statusCode);
map.put("message", message);
JSONObject json4 = JSONObject.fromObject(map);
ConstantUtil.reJSON(json4.toString(), request, response);
}
/**
* 上传图片
*
* @param imgDataList
* @return
* @throws IOException
*/
private List<String> uploadImages(List<String> imgDataList) throws IOException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssms");
BASE64Decoder decoder = new BASE64Decoder();
List<String> returnPaths = new ArrayList<String>();
for (int i = 0; i < imgDataList.size(); i++) {
// 此处拼图片的路径
String _subPath = sdf.format(new Date());
String diskPath = InfoUtil.getInstance().getInfo("config", "image.prescription.path");
String savePath = this.getServletContext().getRealPath(diskPath) + "/" + _subPath + "/";
File f = new File(savePath);
if (!f.exists() && !f.isDirectory()) {
f.mkdirs();
}
String str = DigestUtils.md5Hex(String.valueOf(System.currentTimeMillis() + i)) + ".jpg";
byte[] b = decoder.decodeBuffer(imgDataList.get(i));
for (int j = 0; j < b.length; ++j) {
if (b[j] < 0) {// 调整异常数据
b[j] += 256;
}
}
// 生成jpeg图片
OutputStream out = new FileOutputStream(savePath + str);
out.write(b);
out.flush();
out.close();
returnPaths.add(diskPath + "/" + _subPath + "/" + str);
}
return returnPaths;
}
public static void main(String[] args) throws IOException {
String string = "iVBORw0KGgoAAAANSUhEUgAAACAAAAAbCAIAAACSpRrNAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAJMElEQVRIiQXBWW8cBwEA4Lnv2Zndndnbezp27MSJHdtJkzg9CUnTQCqhQo8HShAvgJDKA4+IFySu9g8gJCiiAlWlaZMmBQQoD0Di3LaTOL72Xu81szOzO/fsDN8HvveDN/Y29zr7/VPHz0iSykfEXl/G6NDx06d2qrVnu3vZUimejEE+gKLw2HVDIQbHMVnqEQgsRMMw6JMkLst9x7WOH1/2Ag+EoVa7nogLCAJFIjE4kwxBAfLciVONap2hQ92OFIoIXDhSbbezxRJM4bMLC6mJic0nm37g9yRJEMREKunYTjD2URQd+15UEHmOk5QBTpDtTgfFcYIgSYJotTr1egv+yY+/Xyk3Hq89yRVKCIq3On0QxbLFSZRhAAyJJpKqrqsjTRAEhqYs27IsUxRihXzedpxWs8WyIQRBKYqeyOZ6PYliGCCAUAQzDSvMRVPJNAwB9tzcfL3V1k3XdH1FN2OZdL3dyU9NwgRpuc5AVUmSKhYKe7t7pWLBG48ZigFAMJ1M6qbJc7wPBK1m2x2PJVnKZfNBAFIENXbHlumgEAYvHz+6V290FVU1rHqvn5+aosORZHZiHIBDXec5XlGUZ5ubvV4vEgk7jvvahVer5QrLMoo8YGi63elajmtbDh+N5gtFbxwMtRGBUTiMhTm+1dyHdNdr9eUxjByYPwIQ+PTc3L4kVRrNSrMuxmIMw8AA6NlOu93OZrOVSuXPH/1ldnZW7smWZW1uboEgyHPhXLGQyWRJklXVIYrgEITAEF6rNKORODR0XdWyupqGklQkFpNUjeX4K59/trS4DIIgBIKtZsOxra+8/HKtVms1ao1aVZFkwBtTOBF4Y9/3c7mcbpiGadI0feDANM9HAh+UenLgBXJPhsr1ViSWUFQdQYl0aiKVymSz2V/+4lcQBJmGgSAwBEEoilIU0e92CAwv5rOGNgSC8R8//HA0VLOZzN7eHkmS9Xpd07R+vy/LsmkYwNgPxj4EgHAoJfgeAAUIz/Cvnj2PgDCB4KZhIBDMhtjt7e3nX3xBjAmqIt9dvZ0QxZPHl23d+P3vftuo1S5+7WIsHtNGw8WlxaXlYxvra7ZhOLaFw7AmyyGGpUgK0nVze3Nv5eRpa2Tt11qapFAYrsmKpioYjMhy/9mzp48fr0+kku/96IcJIUphmK4Oth4/eeWll4q5rCz1Fo7MXf38yuXL74ZCDEFifIh1HSvMh4KxO9IUCPahUydOThWnZqamAT+wDFMdKCSODVVNH2ksTT5dX5ubObi9ubn28P7F8+dHyuDp+hoKgdOlojUauqZh6MN4XLx5898jXRtpamVvR5UlMHAhcBwALvit77zLUCEIxCicMk3TsRzdNDguRNNks90c6VqpVCoU8ndXbxUncmIkGlhWeWf38rff7fV6kibbYy+RS8VSac9z9htNBIbiEbHbaAKOx1CUbpoQ5AFSV1IUpbbfbLTbDgB4QFCp1zRNE8MRaBygfhDjOBojKuXdiWQCgcG/Xf/CNEY0RYjRiKoNcBQt72wjCKxqSuB7/tjLF7LJlIjjsONakKbqMErqltPY73oAeHv1bqVSG2ojRVZ1bThVLBVz+SfrG5Y+ojAcBoIPfvP+O2+/7ft+t9f75JNPWJYFAGBvd2ekaSeWFiMcTxEYx3EQBOVLxaPz83AiP71VqXckdQxChum4jht4QTIas/URAkEMTcdF8UBp0receCTabLSajaYoxHYqe5vbWwiONJrN6alpQRRwFHMMK8zyjm0NBgOcIJXR0At8GKbCnCAWSsVcLl8qlYaKFmZDsUgEg6GNtUcEhlm2icLwsYV5DEVrtZrU7x+aO3zk6PzplTOnzqysrt4Z+978kaPVShnHMAgEGZpt7TcxHF+9e+fWrTvwocXjBEWk0inXcW3LODw93ahXSAwp7+4CgWeZuihEy5VdwzJHhhGLxQ9Oz+Tzhf39VjgSbnfaDx48GCiDfKkIBkAoxO3s7uQKeZqiu91OvlDw/QACIb+Qz6IIAEP+g3t3srkUx1IQCPBhplYte547kHoIgjx89AhB0V9/8L7l2ARB4Dj54N79G9duXLp06cKFizRBf/zxxyRJ0gx7/fr1nfJeKpXi2NBrr16AuZjw4gsvnjz13EQqYZl6rVKmcbRa3uU4ZvbglCCGURy1XVtIJizHq9fqAAAyFLWxtt7p7B+cmk4n0wSOUTRdrdUUZTA5OSnJciQS1oeaqqoAAMLHlpefO7FUrZSfbqyffeUlTZYYmvIcGwD8fH4CJ9B4Iq6N9OLk5PrGBkVRGAi8+cY3YTDIZ7KWYSYTCRiGQAD46tlXCJK4d+9eOBxeW1ujSXL24IwkD+DMRPrcubP1ahkFoblDs3OHZp9srNuuEQTe3fv3Xv/G614wzuZypdKBVqP1r3/8PR1PChzf3W9tPd2cmZ7a3doaqYptW9VKNRqOMDT14P798+fOtVrNfq+nakM4m0nQBGkbBkXgz54+QUDAsHRVVQaKPHvkMBNiV+/eJSgqLiaeX1nxbefY/NG0IN679b/CRLZVr4mRSAD4cTGGYWgmnbZtW4gKQ01bXFjgOC6ZSsM//9lPKQwfKsq1K1fWHj4EQIBh6Farubm99fXXLxEM3ZXkgzMzhqoFjrM0Py/w3LW/fqr0e0qvP3twmqFpIcwLkWijUd3d2U4m4lOTkxzPgSDoOI5lO/DJhYWNR48yyVSIZmzD5HgOw7Gjx+ZJhu5Ifd20as1GiOWKmeyD23fS8dgXn35mDrXvXf5uvVI5UCrqw+HI0MM8ByPI1WvXeI7zg8A0DJYL9Xo9EILh5dnD/7l5E/SDRqX81ltv1upVbTRiee7Uyko4KoxMu9VuZ1ITkOP/88aXYBD0O11zNNLV4dLisW63k8lkfNDv9bvVetV2XdfzMAIPcRyKYaIoDhQVPrOwOFU6wLGhE8sn1tYeHj22UK3Xk+k0hGCuH2TzBYpiVv97OxERlZ40NTlZ3tl59mSTpsh6ox6LxyAUMW3T8fywKPogkMnmYQRFUcxxHcuxe90+tHL6eYakbN0IUfRIGX30hz/hEKIpQ7k/sAz7y6s3kkLynbfe2W+1GZYjaXZhccmHQMcfUyzL8mHDcUmeRygqW5osTk1n8vmZuTmMotKZLIqiqVTq/4Moz4XxI4CVAAAAAElFTkSuQmCC";
// 对字节数组字符串进行Base64解码并生成图片
BASE64Decoder decoder = new BASE64Decoder();
try {
// Base64解码
byte[] b = decoder.decodeBuffer(string);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {// 调整异常数据
b[i] += 256;
}
}
// 生成jpeg图片
String imgFilePath = "E:\\temp\\a.jpg";// 新生成的图片
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true
|
61dc5813b42323bb43a4ea5828ec8a5e1b797ede
|
Java
|
Insswer/OpenGLESTest
|
/app/src/main/java/com/example/insswer/myapplication/GLRenderES2.java
|
UTF-8
| 721
| 2.234375
| 2
|
[] |
no_license
|
package com.example.insswer.myapplication;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
/**
* Created by insswer on 2016/4/29.
*/
public class GLRenderES2 implements GLSurfaceView.Renderer {
@Override
public void onSurfaceCreated(GL10 gl10, EGLConfig eglConfig) {
GLES20.glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
}
@Override
public void onSurfaceChanged(GL10 gl10, int i, int i1) {
GLES20.glViewport(0, 0, i, i1);
}
@Override
public void onDrawFrame(GL10 gl10) {
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
}
}
| true
|
8dc8b9c1c9b2420dee24eec7ea9a06f3c51cc024
|
Java
|
Saildrone/WhirlyGlobe-3
|
/android/library/maply/src/main/java/com/mousebird/maply/MBTileFetcher.java
|
UTF-8
| 7,161
| 2.21875
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* MBTileFetcher.java
* WhirlyGlobeLib
*
* Created by jmnavarro on 3/21/19.
* Copyright 2011-2019 mousebird consulting
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mousebird.maply;
import java.io.File;
import java.util.HashMap;
import java.util.TreeSet;
import java.util.concurrent.Semaphore;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;
/**
* MBTiles tile fetcher.
* <br>
* This tile fetcher focuses on a single MBTiles file. You mate this
* with a QuadImageLoader to do the actual work.
* <br>
* Will work for image or vector MBTiles files.
*/
public class MBTileFetcher extends SimpleTileFetcher
{
/**
* Coordinate system (probably Spherical Mercator)
*/
CoordSystem coordSys = null;
/**
* Construct with the location of an MBTiles file.
*/
public MBTileFetcher(File mbTileFile)
{
super("MBTiles Fetcher");
neverFail = true;
coordSys = new SphericalMercatorCoordSystem();
if (mbTileFile == null || !mbTileFile.exists() || !mbTileFile.canRead()) {
String message = String.format("MBTileSource must be initialized with an existing file. \"%s\" does not exists or is null...",
(mbTileFile == null ? "#NULL" : mbTileFile.getAbsolutePath())) ;
Log.e(TAG, message);
assert true : message;
}
this.init(mbTileFile);
// Kicks off our thread
valid = true;
start();
}
/** SQLite interface logic below **/
// Query parameters and such
private static String TAG = MBTiles.class.getSimpleName();
private static String BOUNDS = "bounds";
private static String MINZOOM = "minzoom";
private static String MAXZOOM = "maxzoom";
private static String MINZOOMLEVEL = "minZoomLevel";
private static String MAXZOOMLEVEL = "maxZoomLevel";
private static String TYPE = "type";
private static String DESCRIPTION = "description";
private static String FORMAT = "format";
private static String NAME = "name";
private static String VALUE = "value";
private static String PNG = "png";
private static String JPG = "jpg";
private static String JPEG = "jpeg";
private static String GET_TILE_SQL = "SELECT tile_data from tiles where zoom_level = ? AND tile_column = ? AND tile_row= ?;";
private static String TILE_DATA = "tile_data";
private SQLiteDatabase mbTileDb;
private boolean initialized; // Have we been correctly initialized
private boolean oldStyleDB; // Are we managing an old style database
private boolean isJpg; // Are we containing jpg tiles (or png tiles)
private String name = "UNSET"; // Name of the tile dataset
private String description = "UNSET"; // Description of the tile dataset
private String type = "UNSET"; // Type of tile (overlay | baselayer)
/**
* Initializes the MBTilesSource with an SQLite database.
* @param sqliteDb a File mapped to an <b>existing</b> SQLite database. The file must exists beforehand.
*/
private void init(File sqliteDb)
{
mbTileDb = SQLiteDatabase.openDatabase(sqliteDb.getAbsolutePath(), null, SQLiteDatabase.OPEN_READONLY);
// We read metadata
String sql = "SELECT name, value FROM metadata;";
Cursor c = mbTileDb.rawQuery(sql, null);
if (c.getCount() > 0) {
c.moveToFirst();
int nameIdx = c.getColumnIndexOrThrow(NAME);
int valueIdx = c.getColumnIndexOrThrow(VALUE);
while (!c.isAfterLast()) {
// What parameter are we reading
String meta = c.getString(nameIdx);
if (MAXZOOM.equals(meta)) {
maxZoom = c.getInt(valueIdx);
} else if (MAXZOOMLEVEL.equals(meta)) {
maxZoom = c.getInt(valueIdx);
}
if (MINZOOM.equals(meta)) {
minZoom = c.getInt(valueIdx);
} else if (MINZOOMLEVEL.equals(meta)) {
minZoom = c.getInt(valueIdx);
}
if (FORMAT.equals(meta)) {
String format = c.getString(valueIdx);
if (JPG.equals(format)) {
isJpg = true;
} else if (JPEG.equals(format)) {
isJpg = true;
}
}
if (NAME.equals(meta)) {
name = c.getString(valueIdx);
}
if (DESCRIPTION.equals(meta)) {
description = c.getString(valueIdx);
}
c.moveToNext();
}
}
c.close();
// If we did not get a minZoom and maxZoom, we need to get them the hard way
if (minZoom == -1 || maxZoom == -1) {
sql = "SELECT MIN(zoom_level) AS minzoom, MAX(zoom_level) as maxzoom FROM tiles;";
c = mbTileDb.rawQuery(sql, null);
if (c.getCount() > 0) {
c.moveToFirst();
minZoom = c.getInt(c.getColumnIndexOrThrow(MINZOOM));
maxZoom = c.getInt(c.getColumnIndexOrThrow(MAXZOOM));
}
c.close();
Log.i(TAG, "Got MIN & MAX zoom the hard way...");
}
Log.v(TAG, String.format("Initialized MBTilesSource %s (%s)", name, description));
Log.v(TAG, String.format(" > Zoom %d -> %d", minZoom, maxZoom));
Log.v(TAG, String.format(" > Type \"%s\"", type));
Log.v(TAG, String.format(" > Format \"%s\"", (isJpg ? "jpg" : "png")));
}
/**
* Fetch the data blog for a given tile. This blocks.
*/
@Override public byte[] dataForTile(Object fetchInfo,TileID tileID)
{
String[] params = new String[3];
params[0] = Integer.toString(tileID.level);
params[1] = Integer.toString(tileID.x);
params[2] = Integer.toString(tileID.y);
Cursor c = mbTileDb.rawQuery(GET_TILE_SQL, params);
int tileDataIdx = c.getColumnIndex(TILE_DATA);
if (c.getCount() > 0) {
c.moveToFirst();
byte[] data = c.getBlob(tileDataIdx);
c.close();
return data;
// Log.v(TAG, String.format("Returned tile for Z=%s, X=%d, Y=%d", tileID.level, tileID.x, tileID.y));
}
c.close();
return null;
}
}
| true
|
e1ce871b102657e1b94ab997a0996af9839f1305
|
Java
|
nj219/excel
|
/src/main/java/com/nj/excledemo/ExcleApplication.java
|
UTF-8
| 445
| 1.570313
| 2
|
[] |
no_license
|
package com.nj.excledemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
/**
* @Author 牛杰
* @Date 2019/2/26 8:30
* @ClassName:UserApplication
*/
@SpringBootApplication
public class ExcleApplication {
public static void main(String[] args) {
SpringApplication.run(ExcleApplication.class);
}
}
| true
|
913646b10670c37d91b3efaed0bcbdb0b2b58f13
|
Java
|
Jorgelhc/Employee-management
|
/src/test/java/com/learning/employee_management/utils/JsonConvertionUtils.java
|
UTF-8
| 1,344
| 2.28125
| 2
|
[] |
no_license
|
package com.learning.employee_management.utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.ser.std.DateSerializer;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import org.springframework.format.annotation.DateTimeFormat;
import java.text.DateFormat;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class JsonConvertionUtils {
public static String objectToJsonString (Object object){
try{
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,true);
return objectMapper.writeValueAsString(object);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| true
|
98cff5f3d96b3a96d85de531ddc447b6ea45f128
|
Java
|
iyanushkevich/MJC-School-GiftCertificate
|
/service/api/src/main/java/com/epam/esm/service/api/BaseService.java
|
UTF-8
| 463
| 2.15625
| 2
|
[] |
no_license
|
package com.epam.esm.service.api;
/**
* The interface Base service.
*
* @param <T> the type parameter
*/
public interface BaseService<T> {
/**
* Find by id t.
*
* @param id the id
* @return the t
*/
T findById(long id);
/**
* Add t.
*
* @param entity the entity
* @return the t
*/
T add(T entity);
/**
* Remove.
*
* @param id the id
*/
void remove(long id);
}
| true
|
ef9030df6a38798ec442d7e031aac17ebfe104c8
|
Java
|
maoyujiao/bible1
|
/base/src/main/java/com/iyuba/base/BaseFragment.java
|
UTF-8
| 1,098
| 2.078125
| 2
|
[] |
no_license
|
package com.iyuba.base;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.StringRes;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import com.iyuba.base.util.T;
import com.iyuba.base.widget.MyViewPager;
/**
* BaseFragment
*/
public class BaseFragment extends Fragment {
protected Activity mActivity;
protected Context mContext;
protected MyViewPager containerVp;
public void setContainerVp(MyViewPager containerVp) {
this.containerVp = containerVp;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mActivity = activity;
mContext = activity;
}
public void showShort(Object info) {
T.showShort(mContext, info.toString());
}
public void showShort(@StringRes int id) {
T.showShort(mContext, id);
}
public void showLong(Object info) {
T.showShort(mContext, info.toString());
}
public void showLong(@StringRes int id) {
T.showShort(mContext, id);
}
}
| true
|
bb8590de5a1ec9a57af1138cbed88f6157a4ad2a
|
Java
|
jtzwm/study
|
/springmvc2/src/main/java/com/zhuwm/mybatis/base/RedisDAO.java
|
UTF-8
| 1,533
| 2.796875
| 3
|
[] |
no_license
|
package com.zhuwm.mybatis.base;
import com.zhuwm.jedis.RedisUtil;
import redis.clients.jedis.Jedis;
/**
* 封装对Redis的操作
* 功能说明: <br>
* 系统版本: v1.0<br>
* 开发人员: @author zhuweiming<br>
* 开发时间: 2016年2月25日<br>
*/
public class RedisDAO {
protected Jedis jedis;
public RedisDAO() {
jedis = RedisUtil.getJedis();
}
/**
* 释放jedis连接,需要子类自行调用此方法释放
* @author zhuweiming
*/
public void returnResource() {
RedisUtil.returnResource(jedis);
}
/**
* 从Redis获取
* @author zhuweiming
* @return
*/
public Object getObjectFromRedis(String key) {
if (key == null)
return null;
return jedis.get(key);
}
/**
* 创建key
* @author zhuweiming
* @param key
*/
public String createKey(String key,String value){
if (key == null)
return null;
return jedis.set(key, value);
}
/**
* 设置key的过期时间
* @author zhuweiming
* @param key
* @param expiredTime
* @return
*/
public String createKeyAndExpiredTime(String key,int expiredTime,String value){
return jedis.setex(key, expiredTime, value);
}
/**
* 用来管理数据库主键,如果数据库中没有,则初始化为0,并自增1。如果有,则返回ID并自增1.
* @author zhuweiming
* @param key
* @return
*/
public String getIDAndIncr(String key){
String result=jedis.get(key);
if(result != null)
jedis.incr(key);
else{
jedis.set(key,"1");
result ="1";
}
return result;
}
}
| true
|
2680dab242e056e864bc2eff047807f71e0882ca
|
Java
|
AshiyaZabeen/Crux-Aug-Live21
|
/Lec10/Bubble_Sort.java
|
UTF-8
| 571
| 3.671875
| 4
|
[] |
no_license
|
package Lec10;
public class Bubble_Sort {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = { 3, 4, 5, 7, 2, 1, 2 };
Sort(arr);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
public static void Sort(int[] arr) {
for (int pass = 1; pass < arr.length; pass++) {// pass<=arr.lenght-1
for (int j = 0; j < arr.length - pass; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
| true
|
1a54dc8402ab363c16fc0847dc15113dad15cf76
|
Java
|
WangZhouA/liupeng_naidean_mensuo_2018_12_29
|
/app/src/main/java/com/saiyi/naideanlock/ui/wifibinding/BindingPresenter.java
|
UTF-8
| 456
| 2.046875
| 2
|
[] |
no_license
|
package com.saiyi.naideanlock.ui.wifibinding;
/**
* 描述:
* 创建作者:Fanjianchang
* 创建时间:2017/9/30 11:43
* 注册业务逻辑处理
*/
public class BindingPresenter implements BindingContract.BindingPresenter {
private BindingContract.BindingView mBindingView;
public BindingPresenter(BindingContract.BindingView mBindingView) {
this.mBindingView = mBindingView;
mBindingView.setPresenter(this);
}
}
| true
|
4833812de846c2f0cfd43fc32296f3a68add0e35
|
Java
|
crazile-dot/myProject
|
/src/main/java/Query1/util/Query1CsvWriter.java
|
UTF-8
| 1,603
| 2.6875
| 3
|
[] |
no_license
|
package Query1.util;
import org.apache.spark.api.java.JavaPairRDD;
import org.joda.time.DateTime;
import scala.Tuple2;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
public class Query1CsvWriter {
public static final char CSV_SEPARATOR = ',';
public static void makeCsv(JavaPairRDD<DateTime, Double> rdd1, JavaPairRDD<DateTime, Double> rdd2, String output) throws IOException{
//aggiungere un controllo (se esiste già il file, ciao)
JavaPairRDD<DateTime, Tuple2<Double, Double>> joinedRdd = rdd1.join(rdd2).sortByKey();
List<Tuple2<DateTime, Tuple2<Double, Double>>> list = joinedRdd.collect();
writeCsv(list, output);
}
public static void writeCsv(List<Tuple2<DateTime, Tuple2<Double, Double>>> l, String output) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter(output));
writer.append("data").append(CSV_SEPARATOR).append("dimessi_guariti").append(CSV_SEPARATOR)
.append("tamponi").append(System.lineSeparator());
l.forEach(t -> {
try {
writer.append(t._1().toString()).append(CSV_SEPARATOR)
.append(Double.toString(t._2()._1())).append(CSV_SEPARATOR)
.append(Double.toString(t._2()._2())).append(System.lineSeparator());
} catch (IOException io) {
io.printStackTrace();
System.out.println("Errore del file\n");
}
});
writer.flush();
writer.close();
}
}
| true
|
d3ad783f9458891f7be2c32028536d971012f2e4
|
Java
|
romina1601/Banking-Service
|
/Backend/src/main/java/utcn/labs/sd/bankingservice/domain/service/ServiceInterface.java
|
UTF-8
| 1,637
| 2.5
| 2
|
[] |
no_license
|
package utcn.labs.sd.bankingservice.domain.service;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
public interface ServiceInterface {
static String getUser(){
Authentication loggedInUser = SecurityContextHolder.getContext().getAuthentication();
String username = null;
if(loggedInUser != null)
username = loggedInUser.getName();
return username;
}
static boolean isInPeriod(String from, String to, String current) throws Exception
{
SimpleDateFormat dateFormatFrom = new SimpleDateFormat("yyyy-MM-dd");
Date parsedDateFrom = dateFormatFrom.parse(from);
Timestamp timestampFrom = new java.sql.Timestamp(parsedDateFrom.getTime());
to = to + " 23:59:59.999";
SimpleDateFormat dateFormatTo = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
Date parsedDateTo = dateFormatTo.parse(to);
Timestamp timestampTo= new java.sql.Timestamp(parsedDateTo.getTime());
SimpleDateFormat dateFormatCurrent = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
Date parsedDateCurrent = dateFormatTo.parse(current);
Timestamp timestampCurrent= new java.sql.Timestamp(parsedDateCurrent.getTime());
if(timestampCurrent.after(timestampFrom) && timestampCurrent.before(timestampTo))
{
return true;
}
else
{
return false;
}
}
}
| true
|
105bedfd360e25368834df44e0e0ce0ba46fb467
|
Java
|
OliversZhang/AndZilla
|
/app/src/main/java/com/zilla/andzilla/AndZillaApplication.java
|
UTF-8
| 832
| 1.898438
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.zilla.andzilla;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;
import ggx.com.libzilla.design.lifecycle.ActivityLifeCycle;
/**
* Created by jerry.guan on 3/28/2017.
*/
public class AndZillaApplication extends Application{
public static RefWatcher getRefWatcher(Context context) {
AndZillaApplication application = (AndZillaApplication) context.getApplicationContext();
return application.refWatcher;
}
private RefWatcher refWatcher;
@Override
public void onCreate() {
super.onCreate();
refWatcher= LeakCanary.install(this);
registerActivityLifecycleCallbacks(new ActivityLifeCycle());
}
}
| true
|
82e14ac07553f90ea06d90f2473b3549fb8f99a4
|
Java
|
KilRol/queuestack
|
/src/com/kilrol/queuestack/model/MyList.java
|
UTF-8
| 2,191
| 3.234375
| 3
|
[] |
no_license
|
package com.kilrol.queuestack.model;
public class MyList<T> {
Push<T> sq;
public void setSq(Push<T> sq) {
this.sq = sq;
sq.setList(this);
}
public void push(T item) {
sq.push(item);
}
public int getSize() {
return size;
}
public T elementAt() {
T info = currentNode.value;
if (currentNode.next != null) currentNode = currentNode.next;
return info;
}
public T getIndex(int index) {
Node<T> cur = head;
for (int i = 0; cur != null && i < index; i++, cur = cur.next) ;
return cur.value;
}
protected class Node<T> {
protected T value;
protected Node<T> next;
public Node(T value, Node<T> next) {
this.value = value;
this.next = next;
}
public Node(T value) {
this.value = value;
this.next = null;
}
@Override
public String toString() {
return value + "";
}
}
protected Node<T> head;
protected int size;
protected Node<T> currentNode;
public MyList() {
head = null;
size = 0;
currentNode = head;
}
public void add(T value) {
Node<T> nodeToAdd = new Node<T>(value);
if (head == null) {
head = nodeToAdd;
currentNode = head;
} else {
Node<T> cur = head;
while (cur.next != null) cur = cur.next;
cur.next = nodeToAdd;
currentNode = nodeToAdd;
}
size++;
}
public void add_front(T value) {
Node<T> nodeToAdd = new Node<T>(value);
if (head == null) {
head = nodeToAdd;
currentNode = head;
} else {
nodeToAdd.next = head;
head = nodeToAdd;
}
size++;
}
public T pop() {
T value = head.value;
head = head.next;
size--;
return value;
}
@Override
public String toString() {
String out = "List";
for (Node<T> i = this.head; i != null; i = i.next)
out += i + " ";
return out;
}
}
| true
|
eec9e406bb06e7bbfaecf99f07403fbeeb20d74c
|
Java
|
radarseesradar/rich_client
|
/originalObjGraph/Keyboard/_TVSessionBeanHome_TVSessionBean_Tie.java
|
UTF-8
| 1,617
| 1.960938
| 2
|
[] |
no_license
|
/* generated by emit_jrmi(Oct 25 2000) on 11/22/00 at 05:00:03 PM from Keyboard.odl
*/
package Keyboard;
public class _TVSessionBeanHome_TVSessionBean_Tie extends org.omg.stub.javax.ejb._EJBHomeImpl_Tie {
private Keyboard.TVSessionBeanHome _target = null;
public java.lang.String[] _ids() {
return _type_ids;
}
public void setTarget(java.rmi.Remote target) {
_target = (Keyboard.TVSessionBeanHome) target;
super.setTarget(target);
}
private static final java.lang.String[] _type_ids = {
"RMI:Keyboard.TVSessionBeanHome:0000000000000000",
"RMI:javax.ejb.EJBHome:0000000000000000"
};
public org.omg.CORBA.portable.OutputStream _invoke(java.lang.String _method, org.omg.CORBA.portable.InputStream _in, org.omg.CORBA.portable.ResponseHandler _reply) throws org.omg.CORBA.SystemException {
try {
if (_method.equals("createTVSessionBean")) {
Keyboard.TVSessionBeanObject _zz;
try {
_zz = _target.create();
} catch(javax.ejb.CreateException ex) {
org.omg.CORBA.portable.OutputStream _out = _reply.createExceptionReply();
_out.write_string("IDL:javax/ejb/CreateEx:1.0");
((org.omg.CORBA_2_3.portable.OutputStream)_out).write_value(ex, javax.ejb.CreateException.class);
return _out;
}
org.omg.CORBA.portable.OutputStream _out = _reply.createReply();
javax.rmi.CORBA.Util.writeRemoteObject(_out, _zz);
return _out;
}
} catch (org.omg.CORBA.SystemException ex) {
throw ex;
} catch (java.lang.Throwable ex) {
throw new org.omg.CORBA.portable.UnknownException(ex);
}
return super._invoke(_method, _in, _reply);
}
}
| true
|
f7f669fb3ff29da49597286dc8b22ba59764ff75
|
Java
|
armfahim/Job-Harvester
|
/src/test/java/io/naztech/jobharvestar/scraper/TestOnex.java
|
UTF-8
| 2,791
| 2.25
| 2
|
[] |
no_license
|
package io.naztech.jobharvestar.scraper;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
import com.itextpdf.text.pdf.parser.SimpleTextExtractionStrategy;
import com.itextpdf.text.pdf.parser.TextExtractionStrategy;
public class TestOnex {
private static final String PDF_PATH = "https://www.onexcompany.com/wp-content/uploads/2018/04/%CE%91%CE%93%CE%93%CE%95%CE%9B%CE%99%CE%91-BUSINESS-INTELLIGENCE-CONSULTANTS.pdf";
private static final String SITE_URL = "https://www.onexcompany.com/careers/";
private static final String ROW_EL_PATH = "//*[@id=\"content\"]/div[2]/div[2]/div/div/div/div/h5/a";
private static WebClient client;
private static PdfReader reader;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
URL url = new URL(PDF_PATH);
reader = new PdfReader(url);
client = new WebClient(BrowserVersion.FIREFOX_52);
client.getOptions().setTimeout(50*1000);
client.getOptions().setUseInsecureSSL(true);
client.setAjaxController(new NicelyResynchronizingAjaxController());
client.getCookieManager().setCookiesEnabled(true);
client.getOptions().setThrowExceptionOnFailingStatusCode(false);
client.getOptions().setThrowExceptionOnScriptError(false);
client.waitForBackgroundJavaScriptStartingBefore(10*1000);
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
reader.close();
client.close();
}
@Test
public void pdfParse() throws FailingHttpStatusCodeException, MalformedURLException, IOException {
StringBuffer sb = new StringBuffer();
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
TextExtractionStrategy strategy;
for(int i=1;i<=reader.getNumberOfPages();i++) {
strategy = parser.processContent(i, new SimpleTextExtractionStrategy());
sb.append(strategy.getResultantText());
}
System.out.println(sb);
}
@Test
public void testPageLoad() throws FailingHttpStatusCodeException, MalformedURLException, IOException {
HtmlPage page = client.getPage(SITE_URL);
client.waitForBackgroundJavaScript(5*1000);
List<HtmlElement> rowList = page.getBody().getByXPath(ROW_EL_PATH);
assertEquals(2, rowList.size());
}
}
| true
|
f5ab57530990e44def740a11f8cc7ee2827702fc
|
Java
|
perses-games/jogl-texture-fader
|
/src/com/persesgames/jogl/TestFader.java
|
UTF-8
| 833
| 2.609375
| 3
|
[] |
no_license
|
package com.persesgames.jogl;
/**
* User: rnentjes
* Date: 1/26/14
* Time: 4:28 PM
*/
public class TestFader extends Fader {
private Matrix source = new Matrix();
private Matrix dest = new Matrix();
@Override
public Matrix getSourceModelViewMatrix() {
source.setToIdentity();
source.scale(aspect, 1, 1);
source.translate(0,0,-1);
return source;
}
public float getSourceAlpha() {
return 1f;
}
@Override
public Matrix getDestinationModelViewMatrix() {
dest.setToIdentity();
dest.scale(aspect, 1, 1);
dest.translate(0,0,-1);
return dest;
}
public float getDestinationAlpha() {
return (float) Math.sin(time);
}
@Override
public boolean done() {
return time > Math.PI / 2;
}
}
| true
|
21aa16c30aecdecff30dee25003224c9dbf21927
|
Java
|
vitalifed/game-portal
|
/common/src/main/java/org/steelrat/game/portal/exception/RoomsThresholdExceedException.java
|
UTF-8
| 852
| 2.390625
| 2
|
[] |
no_license
|
package org.steelrat.game.portal.exception;
/**
* Thrown when an amount of rooms in repository exceeds defined value.
*
* @author <a href="mailto:vitali.fedosenko@gmail.com">Vitali Fedasenka</a>
*
*/
public class RoomsThresholdExceedException extends GamePortalException {
private static final long serialVersionUID = 1L;
public RoomsThresholdExceedException() {
super();
}
public RoomsThresholdExceedException(String message, Throwable cause, boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public RoomsThresholdExceedException(String message, Throwable cause) {
super(message, cause);
}
public RoomsThresholdExceedException(String message) {
super(message);
}
public RoomsThresholdExceedException(Throwable cause) {
super(cause);
}
}
| true
|
0c50bc3dd022b78b490fbb2c0f4d0b009b8acc11
|
Java
|
Qingmutang/controller
|
/serverbywanglong/model/src/main/java/com/modianli/power/model/RecommendEnterprisePubDetails.java
|
UTF-8
| 357
| 1.523438
| 2
|
[] |
no_license
|
package com.modianli.power.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Created by dell on 2017/5/17.
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class RecommendEnterprisePubDetails {
private String uuid;
private String name;
private String url;
}
| true
|
dcaa086cbd000242d31cc2c5b4eee48f04714bd4
|
Java
|
fuy219/CSE2
|
/hw02/Arithmetic.java
|
UTF-8
| 3,562
| 3.296875
| 3
|
[] |
no_license
|
//Fung Yeung
//hw02
//9/8/2015
//set up class
public class Arithmetic{
public static void main (String[]args){
//number of socks
int nSocks=3;
//cost of the socks, each pair
double sockCost$=2.58;
//number of drinking glasses
int nGlasses=6;
//cost of glasses, each
double glassCost$=2.29;
//number of envelopes
int nEnvelopes=1;
//cost of the envelopes, per box
double envelopeCost$=3.25;
double taxPercent= 0.06;
//total cost of socks variable plus sales tax
double totalSockCost$;
//total cost of Glasses variable plus sales tax
double totalGlassesCost$;
//total cost of Envelopes plus sales tax
double totalEnvelopeCost$;
//socks section
//total cost of socks no sales tax
double tcsnst;
tcsnst= (double)(nSocks*sockCost$);
//total sales tax for socks
double tsts;
tsts= (int)(tcsnst*taxPercent*100)/100.0;
//total cost of socks with sales tax
double tcsst;
tcsst= (float) (tsts+tcsnst)*1000/1000.0;
//println results
System.out.println("number of socks "+ nSocks);
System.out.println("cost per sock "+sockCost$);
System.out.println("sales tax on socks "+tsts);
System.out.println("cost of socks no sales tax " + tcsnst);
System.out.println("cost of socks with sales tax "+tcsst);
//glasses section
//total cost of glasses no sales tax
double tcgnst;
tcgnst= (double)(nGlasses*glassCost$);
//total sales tax for glasses
double tstg;
tstg=(int)(tcgnst*taxPercent*100)/100.0;
//total cost of glasses with sales tax
double tcgst;
tcgst= (float) (tstg+tcgnst)*1000/1000.0;
//println results
System.out.println("number of glasses "+ nGlasses);
System.out.println("cost per glass "+glassCost$);
System.out.println("sales tax on glasses "+ tstg);
System.out.println("cost of glasses no sales tax "+tcgnst);
System.out.println("cost of socks with sales tax "+tcgst);
//envelope section
//total cost of envelopes no sales tax
double tcenst;
tcenst= (double)(nEnvelopes*envelopeCost$);
//total sales tax for envelope
double tste;
tste=(int)(tcenst*taxPercent*100)/100.0;
//total cost of envelope with sales tax
double tcest;
tcest= (float) (tste+tcenst)*1000/1000.0;
//println results
System.out.println("number of envelopes "+nEnvelopes);
System.out.println("cost per envelope "+envelopeCost$);
System.out.println("sales tax on envelope "+tste);
System.out.println("cost of envelope no sales tax " +tcenst);
System.out.println("cost of socks with sales tax "+tcest);
//Final price section
//total cost of purchases
double tcp;
tcp= (float)(tcenst+tcgnst+tcsnst)*1000/1000.0;
//total sales tax
double tst;
tst=(float)(tste+tstg+tsts)*1000/1000.0;
//total cost of purchase with sales tax
double tcpst;
tcpst=(float)(tst+tcp)*1000/1000.0;
//println results
System.out.println("total cost of purchases no sales tax "+tcp);
System.out.println("total sales tax "+tst);
System.out.println("total cost of purchases with sales tax "+tcpst);
}
}
| true
|
20f3ef73626314a45ca47fef4ba78e8c2311147a
|
Java
|
Sekei/aymk
|
/app/src/main/java/com/live/tv/mvp/activity/live/bean/MemberAvoidBean.java
|
UTF-8
| 384
| 1.828125
| 2
|
[] |
no_license
|
package com.live.tv.mvp.activity.live.bean;
/**
* Created by taoh on 2018/6/4.
*/
public class MemberAvoidBean {
private String member_avoid_password;
public String getMember_avoid_password() {
return member_avoid_password;
}
public void setMember_avoid_password(String member_avoid_password) {
this.member_avoid_password = member_avoid_password;
}
}
| true
|
5fd004ccee2861cca122ceb0cf7eaa6f3e97a13d
|
Java
|
liyingben/tailoring
|
/src/main/java/com/tailoring/yewu/controller/api/LoginApi.java
|
UTF-8
| 2,764
| 2.4375
| 2
|
[] |
no_license
|
package com.tailoring.yewu.controller.api;
import com.tailoring.yewu.common.ActionResult;
import com.tailoring.yewu.entity.dto.LoginDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import javax.naming.*;
import javax.naming.directory.*;
import java.util.Hashtable;
@RestController
@RequestMapping("/api/login")
@Api(value = "登陆", tags = {"登陆接口"})
public class LoginApi {
@RequestMapping(value = "/post", method = RequestMethod.POST)
@ResponseBody
@ApiOperation(value = "登陆", tags = {"登陆接口"}, notes = "登陆")
public ActionResult<String> getAllPersonNamesWithTraditionalWay(@RequestBody LoginDto dto) {
String msg = getAllPersonNamesWithTraditionalWay(dto.getUsername(), dto.getPassword());
return new ActionResult<>(msg);
}
@RequestMapping(value = "/getMsg", method = RequestMethod.POST)
@ResponseBody
@ApiOperation(value = "登陆", tags = {"登陆接口"}, notes = "登陆")
public String getAllPersonNamesWithTraditionalWay(@RequestParam String username, @RequestParam String password) {
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://10.75.10.250:389/dc=ansell,dc=com");
env.put(Context.SECURITY_PRINCIPAL, username);
env.put(Context.SECURITY_CREDENTIALS, password);
DirContext ctx;
String name = "";
NamingEnumeration results = null;
try {
ctx = new InitialDirContext(env);
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
results = ctx.search("", "(&(objectclass=person)(userprincipalname=" + username + "))", controls);
SearchResult searchResult = (SearchResult) results.next();
Attributes attributes = searchResult.getAttributes();
name = attributes.get("userprincipalname").get().toString().split("@")[0];
} catch (AuthenticationException e) {
String erroMsg = e.toString();
e.printStackTrace();
return erroMsg;
} catch (NameNotFoundException e) {
String erroMsg = e.toString();
e.printStackTrace();
return erroMsg;
} catch (NamingException e) {
e.printStackTrace();
return e.toString();
} finally {
if (results != null) {
try {
results.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return name;
}
}
| true
|
4ab15742246e5b97a50421308a384a85aafb5676
|
Java
|
rebeccaax/AP-Computer-Science
|
/lab03/MakeChange.java
|
UTF-8
| 863
| 3.609375
| 4
|
[] |
no_license
|
package lab03;
/**
* Created by rebeccaxu on 11/16/17.
*/
public class MakeChange {
public static String makeChange(double money) {
final double AMOUNT_OF_MONEY[] = {100, 50, 20, 10, 5, 1, 0.25, 0.10, 0.05, 0.01};
String change = "";
for (int i = 0; i < 10; i++){
change += (int)(money/AMOUNT_OF_MONEY[i]);
change += " ";
money %= AMOUNT_OF_MONEY[i];
money = (int)(Math.round(money*100))/ 100.0;
}
return change;
}
}
/*
Using modular arithmetic, please create a method to determine the
proper way to break an amount of money into change.
SpreadLines will take a series of arguments
Should return a String with the optimal number of the following,
separated by spaces:
Hundreds, fifties, twenties, tens, fives, singles, quarters, dimes, nickels, and pennies.
*/
| true
|
35843a6218e23ff2f835cda4aa53465118061e06
|
Java
|
RaiVolt/Java
|
/webmmc/src/main/java/br/com/senac/Domain/Usuario.java
|
UTF-8
| 2,226
| 2.1875
| 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 br.com.senac.Domain;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
*
* @author Rafael
*/
@Entity
public class Usuario extends GenericDomain {
@Column(length = 40, nullable = false)
private String nome;
@Column(length = 40, nullable = false)
private String email;
@Column(length = 32, nullable = false)
private String senha;
@Column(nullable = false)
private Character sexo;
@Column(nullable = false)
@Temporal(TemporalType.DATE)
private Date dataNac;
@Column(nullable = false)
@Temporal(TemporalType.DATE)
private Date dataCad;
@OneToOne
@JoinColumn(nullable = false)
private Cidade cidade;
@OneToOne
@JoinColumn(nullable = false)
private Tipo tipo;
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getSenha() {
return senha;
}
public void setSenha(String senha) {
this.senha = senha;
}
public Character getSexo() {
return sexo;
}
public void setSexo(Character sexo) {
this.sexo = sexo;
}
public Date getDataNac() {
return dataNac;
}
public void setDataNac(Date dataNac) {
this.dataNac = dataNac;
}
public Date getDataCad() {
return dataCad;
}
public void setDataCad(Date dataCad) {
this.dataCad = dataCad;
}
public Cidade getCidade() {
return cidade;
}
public void setCidade(Cidade cidade) {
this.cidade = cidade;
}
public Tipo getTipo() {
return tipo;
}
public void setTipo(Tipo tipo) {
this.tipo = tipo;
}
}
| true
|
518bea9318510c2c3da43ede3078b56bb5bf9584
|
Java
|
shivani2813/Localeats
|
/app/src/main/java/com/example/localeats/ResturantDetailActivity.java
|
UTF-8
| 5,914
| 1.921875
| 2
|
[] |
no_license
|
package com.example.localeats;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.ButtonBarLayout;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.gson.Gson;
import java.util.ArrayList;
public class ResturantDetailActivity extends AppCompatActivity implements MenuAdapter.callBack, Adapter.callBack {
Bundle extra;
RecyclerView recyclerView;
TextView name;
TextView T1, T2;
EditText E1;
Button btn, btn2, btn3,btn4,btn5;
RatingBar R1;
Toolbar toolbar;
ArrayList<additem> ad = new ArrayList<>();
DatabaseReference db;
MenuAdapter adapter;
String number="+91-8437839297";
RelativeLayout layoutCall;
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
}
return false;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_resturant_detail);
db = FirebaseDatabase.getInstance().getReference();
name = findViewById(R.id.txtLblname);
layoutCall=findViewById(R.id.layoutCall);
T1 = findViewById(R.id.textvi);
T2 = findViewById(R.id.textvie);
btn = findViewById(R.id.button1);
btn2 = findViewById(R.id.button2);
btn4 =findViewById(R.id.button);
btn5=findViewById(R.id.butt);
btn5.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String url = "https://api.whatsapp.com/send?phone="+number;
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
btn4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:123456789"));
startActivity(intent);
}
});
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(ResturantDetailActivity.this, activity_gallery.class);
startActivity(intent);
}
});
toolbar = findViewById(R.id.tool);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
btn3 = findViewById(R.id.add);
R1 = findViewById(R.id.rating);
recyclerView = findViewById(R.id.recyclerview);
extra = getIntent().getExtras();
modal modalObj = new Gson().fromJson(extra.getString("data"), modal.class);
Log.e("menu get", modalObj.getRestruent());
modalObj.getMenu();
Log.e("menu---", "" + modalObj.getMenu());
adapter = new MenuAdapter(this);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
db.child("Resturant").child("resturant16").child("Menu").get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
Log.e("inside", "success" + task.getResult());
for (DataSnapshot dataSnapshot : task.getResult().getChildren()) {
String discription = dataSnapshot.child("discription").getValue(String.class);
String tag = dataSnapshot.child("tag").getValue(String.class);
String title = dataSnapshot.child("title").getValue(String.class);
String prize = dataSnapshot.child("prize").getValue(String.class);
Integer rating = dataSnapshot.child("rating").getValue(Integer.class);
String image= dataSnapshot.child("image").getValue(String.class);
Log.e("tt", discription);
additem abc = new additem();
abc.setVegType("tag");
abc.setDescription(discription);
abc.setName(title);
abc.setRating((float) 4.87);
abc.setImageURL(image);
abc.setPrice(prize);
ad.add(abc);
}
adapter.setArrayList(ad);
recyclerView.setAdapter(adapter);
} else {
Log.e("db exectiption:", task.getException().getMessage());
}
}
});
name.setText(modalObj.getRestruent());
T1.setText(modalObj.getRestruantSlogan());
R1.setRating(modalObj.getRating());
}
@Override
public void cardItemClick(additem menu) {
}
@Override
public void addBtnClick(String tag) {
layoutCall.setVisibility(View.VISIBLE);
}
@Override
public void cardItemClick(modal menu) {
}
}
| true
|
4985d55d355f9dbb95288fa0f909cf4501e2a28f
|
Java
|
DimasSugara/lab-pbo-2020
|
/Pertemuan 1/CobaContinue.java
|
UTF-8
| 723
| 3.546875
| 4
|
[] |
no_license
|
public class CobaContinue{
public static void main(String arg[]){
for (int i=0; i<10; i++){
for (int j=0; j<i+1; j++){
if(j==5)
continue;
System.out.print('*');
}
System.out.println();
}
}
}
/**
* line 3 = looping pertama
* line 4 = looping didalam looping
* line 5 = menggunakan operator if apabila nilai j sama dengan 5 dan dimulai dari j = 5 dan akan continue sampai looping pertama mencapai batas dan menampilkan * sebanyak j
* output yang dihasilkan meningkat sesuai j
* contoh bila j=7 maka :
* *
* **
* ***
* ****
* ***** akan dilanjutkan ke looping pertama menjadi
* ***** dan baru dilanjutkan output tambahan
* ******
*/
| true
|
619de0aea8c8cc477e79d44a0678de81ab7e16fb
|
Java
|
GregHib/fury
|
/src/main/java/com/fury/game/container/impl/bank/BankSearch.java
|
UTF-8
| 2,838
| 2.453125
| 2
|
[] |
no_license
|
package com.fury.game.container.impl.bank;
import com.fury.game.GameSettings;
import com.fury.game.content.dialogue.input.impl.EnterSyntaxToBankSearchFor;
import com.fury.core.model.node.entity.actor.figure.player.Player;
import com.fury.core.model.item.Item;
import java.util.ArrayList;
import java.util.List;
public class BankSearch {
public void setPlayer(Player player) {
this.player = player;
}
Bank bank;
Player player;
String searchQuery;
public BankSearch(Bank bank) {
this.bank = bank;
}
public void stop() {
player.getPacketSender().sendConfig(117, 0).sendString(5383, "Bank of " + GameSettings.NAME);
player.getPacketSender().sendClientRightClickRemoval();
searchQuery = null;
bank.setSearching(false);
player.setInputHandling(null);
bank.refresh();
}
public void search(String string) {
player.getPacketSender().sendInterfaceComponentScrollPosition(5385, 0);
player.getPacketSender().sendClientRightClickRemoval();
player.getPacketSender().sendString(5383, "Bank of " + GameSettings.NAME + "(search: '" + string + "')");
bank.setCurrentTab(0);
searchQuery = string;
refresh();
bank.refresh();
}
public boolean handleButton(int id) {
if(id == 22004) {
if (!bank.isSearching()) {
bank.setSearching(true);
player.getPacketSender().sendConfig(117, 1);
if (player.getInputHandling() == null) {
player.setInputHandling(new EnterSyntaxToBankSearchFor());
player.getPacketSender().sendEnterInputPrompt("Enter the name of the item you wish to search for:");
}
} else
stop();
return true;
}
return false;
}
public void refresh() {
if (hasQuery()) {
Item[] items = getResults();
player.getPacketSender().sendItemContainer(items, 5382);
player.getPacketSender().sendInterfaceComponentScrollMax(5385, (int) Math.round(items.length * 4.5));
}
}
public Item[] getResults() {
List<Item> items = new ArrayList<>();
if(hasQuery()) {
for (int i = 0; i < bank.getTabCount(); i++)
for (Item item : bank.tab(i).getItems())
if (item != null && item.getDefinition().name != null)
if (item.getDefinition().name.toLowerCase().contains(searchQuery))
items.add(item);
}
return items.toArray(new Item[items.size()]);
}
public boolean hasQuery() {
return searchQuery != null && searchQuery.length() > 0;
}
public String getQuery() {
return searchQuery;
}
}
| true
|
e973de0e9d95648801b5e56adc1ad47f8d7fb172
|
Java
|
khaledboussaba/JardeenProject
|
/AppJardeenDao/src/main/java/fr/afcepf/ai105/p3/g1/appjardeen/dao/CompetenceDao.java
|
UTF-8
| 231
| 1.75
| 2
|
[] |
no_license
|
package fr.afcepf.ai105.p3.g1.appjardeen.dao;
import java.util.List;
import fr.afcepf.ai105.p3.g1.appjardeen.entities.Competence;
public interface CompetenceDao extends GenericDao<Competence>{
List<Competence> getAll();
}
| true
|
5b8c47499cd434af64b7232cffa42775a2e67274
|
Java
|
Kardesler-Kodculuk/G10_CENG112_HW3
|
/src/internals/ITransactionQueue.java
|
UTF-8
| 1,259
| 3.078125
| 3
|
[] |
no_license
|
package internals;
import simulation.Transaction;
public interface ITransactionQueue {
/**
* Insert a new transaction into the queue, analogous to enqueue.
* @param T the new transaction
*/
public void insert(Transaction T);
/**
* Remove the next transaction from the queue, anologous to dequeue.
* @return Transaction which was removed or Null.
*/
public Transaction remove();
/**
* Return if the queue is empty.
* @return
*/
public boolean isEmpty();
/**
* Delete the queue alltogether.
* @return
*/
public boolean clear();
/**
*
* @return a string representation of the queue.
*/
public String toString();
/**
* Get the next transaction queue.
* @return
*/
public ITransactionQueue getNextTransactionQueue();
/**
* Set the transaction queue.
*/
public void setNextTransactionQueue(ITransactionQueue next);
/**
* Get the total waiting time up onto this point.
* @return
*/
public int getTotalWaitingTime();
/**
* Get the number of transaction in the queue.
* @return
*/
public int getSize();
/**
*
* @return the Date of queue length.
*/
public String getDate();
/**
*
* @param Date - Date the transaction queue is created from.
*/
public void setDate(String Date);
}
| true
|
aee492e7c84ec30332e1d847434001dd786944c2
|
Java
|
GuillaumeRod/MyOwnStream
|
/app/src/main/java/polyteam/myownstetho/MyApp.java
|
UTF-8
| 2,955
| 2.171875
| 2
|
[] |
no_license
|
package polyteam.myownstetho;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.Application;
import android.app.DialogFragment;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import com.jcraft.jsch.Session;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.net.Socket;
import polyteam.myownstetho.Activities.ActivityDialogs.ProblemDialog;
import polyteam.myownstetho.Activities.ActivityDialogs.SavePathoDialog;
import polyteam.myownstetho.HandlerTCP.AsyncResponseString;
import polyteam.myownstetho.HandlerTCP.CommandTCP.GetResponse;
import polyteam.myownstetho.HandlerTCP.CommandTCP.SendString;
/**
* Created by Tristan on 14/02/2016.
*/
public class MyApp extends Application {
private Socket socket = null;
private boolean isConnected = false;
private Activity mCurrentActivity = null;
private Boolean choixHomme = true;
public Activity getCurrentActivity(){
return this.mCurrentActivity;
}
public void setCurrentActivity(Activity mCurrentActivity){
this.mCurrentActivity = mCurrentActivity;
}
public void setConnected(boolean co){
this.isConnected=co;
}
public boolean isConnected(){
return this.isConnected;
}
public Socket getSocket(){
return this.socket;
}
public void setSocket(Socket socket){
this.socket=socket;
}
public Boolean getChoixHomme() {
return choixHomme;
}
public void setChoixHomme(Boolean choixHomme) {
this.choixHomme = choixHomme;
}
public void sendMessage(String message, Activity mActivity){
Log.v("MyApp", "sendMessage de " + message + " par " + mActivity);
SendString asyncTask =new SendString(mActivity,message);
asyncTask.delegateResponse = (AsyncResponseString) mActivity;
asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
public void getResponse(Activity mActivity){
Log.v("MyApp", "getResponse de " + mActivity);
GetResponse asyncTask =new GetResponse(mActivity);
asyncTask.delegateResponse = (AsyncResponseString) mActivity;
asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
public void resetApp(Context context){
this.socket=null;
this.isConnected=false;
this.mCurrentActivity=null;
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
public void showProblemDialog(Context context){
DialogFragment newFragment = ProblemDialog.newInstance();
newFragment.setCancelable(false);
newFragment.show(getCurrentActivity().getFragmentManager(), "Problem Dialog");
}
}
| true
|
1b0e932a4180dd8e56868ff2f0c99144fc55f7de
|
Java
|
B00tlegger/SKILLBOX
|
/11_FilesAndNetwork/homework_11.5/src/main/java/Main.java
|
UTF-8
| 1,165
| 2.71875
| 3
|
[] |
no_license
|
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.util.Map;
public class Main {
private static Map<Integer, Line> linesMap;
public static void main(String[] args) {
MyJSONParser myJASONParser = new MyJSONParser(new MetroMap("https://www.moscowmap.ru/metro.html#lines"));
myJASONParser.writeFile("data/Mos_Metro.json");
// ============================================================================
JSONParser parser = new JSONParser();
JSONObject metroMap = new JSONObject();
try {
metroMap = (JSONObject) parser.parse(myJASONParser.getJsonFile("data/Mos_Metro.json"));
linesMap = myJASONParser.addLines(metroMap);
} catch (ParseException e) {
e.printStackTrace();
}
for (int i = 0; i < linesMap.size(); i++) {
linesMap.get(i + 1).addStations(metroMap);
System.out.println("На ветке метро " + "\"" + linesMap.get(i + 1).getName() + "\"" + " " + linesMap.get(i + 1).getStations().size() + " станций");
}
}
}
| true
|
124710623896ef09876e6941d8c5d0b050ae74b8
|
Java
|
RisingGeek/data_structures
|
/pep-tree-java/linearize.java
|
UTF-8
| 997
| 3.34375
| 3
|
[] |
no_license
|
public class linearize {
public static Node linear(Node root) {
if (root == null)
return null;
if (root.left == null && root.right == null)
return root;
Node left_tail = linear(root.left);
Node right_tail = linear(root.right);
if (left_tail == null) {
root.left = root.right;
root.right = null;
} else if (right_tail == null) {
root.right = null;
return left_tail;
} else {
left_tail.left = root.right;
root.right = null;
}
return right_tail;
}
public static void main(String[] args) {
int[] arr = { 10, 20, 30, -1, -1, 40, -1, -1, 50, 60, 80, -1, -1, -1, 70, 90, -1, 100, -1, -1, -1 };
tree_util ct = new tree_util();
Node root = ct.construct_tree(arr);
Node right_tail = linear(root);
System.out.println("right tail" + right_tail.data);
ct.display(root);
}
}
| true
|
d902df0e0d890f8e5fcf2d70c3e4b0bbc93a7224
|
Java
|
alexkarnei/epamTraining
|
/1_Basics of software code development/src/com/alexkarnei/Task35.java
|
UTF-8
| 619
| 3.296875
| 3
|
[] |
no_license
|
package com.alexkarnei;
import java.util.Scanner;
public class Task35 {
public static void main() {
int n = 1;
double a;
double sum = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Insert e");
if (sc.hasNextDouble()) {
double e = sc.nextDouble();
do {
a = 1 / Math.pow(2, n) + 1 / Math.pow(3, n);
sum = sum + a;
n++;
}
while (Math.abs(a) <= e);
System.out.println(" Sum = "+sum);
} else System.out.println("Insert wrong data");
}
}
| true
|
ceff138bcb80067c9dc7af48b1dd957104f7a9b9
|
Java
|
orekyuu/JavaBeamStudio
|
/Core/src/main/java/net/orekyuu/javatter/core/controller/AccountSettingsController.java
|
UTF-8
| 3,042
| 2.359375
| 2
|
[] |
no_license
|
package net.orekyuu.javatter.core.controller;
import com.gs.collections.api.list.ImmutableList;
import javafx.collections.ObservableList;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.MultipleSelectionModel;
import javafx.stage.Stage;
import javafx.util.Callback;
import net.orekyuu.javatter.api.account.AccountStorageService;
import net.orekyuu.javatter.api.account.TwitterAccount;
import net.orekyuu.javatter.api.controller.JavatterFXMLLoader;
import javax.inject.Inject;
import java.io.IOException;
import java.net.URL;
import java.util.Optional;
import java.util.ResourceBundle;
public class AccountSettingsController implements Initializable {
public ListView<TwitterAccount> accounts;
public Button remove;
public Button add;
@Inject
private AccountStorageService accountStorage;
@Override
public void initialize(URL location, ResourceBundle resources) {
accounts.setCellFactory(new Callback<ListView<TwitterAccount>, ListCell<TwitterAccount>>() {
@Override
public ListCell<TwitterAccount> call(ListView<TwitterAccount> param) {
return new ListCell<TwitterAccount>() {
@Override
protected void updateItem(TwitterAccount item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setGraphic(null);
setText(null);
return;
}
setText("@" + item.getId());
}
};
}
});
updateAccountsList();
}
public void removeAccount() {
MultipleSelectionModel<TwitterAccount> selectionModel = accounts.getSelectionModel();
ObservableList<TwitterAccount> selectedItems = selectionModel.getSelectedItems();
accountStorage.delete(selectedItems);
updateAccountsList();
}
public void addAccount() {
JavatterFXMLLoader loader = new JavatterFXMLLoader(getClass().getResource("/layout/signup.fxml"));
Stage stage = new Stage();
loader.setOwnerStage(stage);
try {
Scene scene = new Scene(loader.load());
stage.setScene(scene);
stage.requestFocus();
stage.showAndWait();
SignupController controller = loader.getController();
controller.onClose();
Optional<TwitterAccount> account = controller.getAccount();
account.ifPresent(a -> updateAccountsList());
} catch (IOException e) {
e.printStackTrace();
}
}
private void updateAccountsList() {
ImmutableList<TwitterAccount> accountList = accountStorage.findByType(TwitterAccount.class);
accounts.getItems().setAll(accountList.toList());
}
}
| true
|
0520010b95692ae7df2f6e06c8fbc4dec9731d26
|
Java
|
Emok1Ng/90015-Distributed-Systems-Assignment2
|
/comp90015a2/base/src/main/java/com/assignment2/base/Enum/MessageType.java
|
UTF-8
| 416
| 2.421875
| 2
|
[] |
no_license
|
package com.assignment2.base.Enum;
public enum MessageType {
ROOMCHANGE("roomchange"),
ROOMCONTENTS("roomcontents"),
ROOMLIST("roomlist"),
MESSAGE("message"),
HOSTCHANGE("hostchange"),
NEIGHBORS("neighbors"),
SHOUTMSG("shoutmsg");
private String type;
MessageType(String type) {
this.type = type;
}
public String getType(){
return this.type;
}
}
| true
|
8aeb84fe500a4304f61eba999c04c3bebdb45b44
|
Java
|
jtconnors/Scoreboard-v1.1
|
/src/scoreboard/common/networking/MulticastConnection.java
|
UTF-8
| 8,634
| 2.265625
| 2
|
[] |
no_license
|
/*
* Copyright (c) 2013, Jim Connors
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of this project nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package scoreboard.common.networking;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import scoreboard.common.networking.SocketListener;
import static scoreboard.common.Constants.MAX_DATAGRAM_MSG_SIZE;
import static scoreboard.common.Constants.DEBUG_NONE;
import static scoreboard.common.Constants.DEBUG_SEND;
import static scoreboard.common.Constants.DEBUG_RECV;
import static scoreboard.common.Constants.DEBUG_EXCEPTIONS;
import static scoreboard.common.Constants.DEBUG_STATUS;
import static scoreboard.common.Constants.DEFAULT_PORT;
import static scoreboard.common.Constants.DEFAULT_SESSION_ADDR;
import scoreboard.common.networking.SocketBase;
/**
* This class provides the framework for a multicast socket reader.
* When an update message is to be posted, it is broadcast over the
* multicast socket such that all connected clients will receive the message.
*
* This class is abstract and requires implementation of the onMessage()
* and onClosedStatus() methods.
*/
public abstract class MulticastConnection extends SocketBase implements
SocketListener, Runnable {
private MulticastSocket multicastSocket = null;
private int portNum;
private String addr;
private InetAddress inetAddress;
private int debugFlags = DEBUG_NONE;
/**
* Close down the MulticastSocket. As per the Java Socket
* API, once a Socket has been closed, it is not available for
* further networking use (i.e. can't be reconnected or rebound).
* A new Socket needs to be created.
*/
private void close() {
try {
if (multicastSocket != null && !multicastSocket.isClosed()) {
multicastSocket.close();
}
if (debugFlagIsSet(DEBUG_STATUS)) {
System.out.println("Multicast Connection closed");
}
/*
* The onClosedStatus() method has to be implemented by
* a sublclass. If used in conjunction with JavaFX 2.0,
* use Platform.runLater() to force this method to run
* on the main thread.
*/
onClosedStatus(true);
} catch (Exception e) {
if (debugFlagIsSet(DEBUG_EXCEPTIONS)) {
e.printStackTrace();
}
}
}
/*
* Set up a connection. This method returns no status,
* however the onClosedStatus(boolean) method will be called when the
* status of the socket changes, either opened or closed (for whatever
* reason).
*/
private void connect() {
try {
/*
* Create the MulticastSocket instance
*/
multicastSocket = new MulticastSocket(portNum);
inetAddress = InetAddress.getByName(addr);
multicastSocket.joinGroup(inetAddress);
/*
* Background thread to continuously read from the input stream.
*/
new ReaderThread().start();
} catch (Exception e) {
if (debugFlagIsSet(DEBUG_EXCEPTIONS)) {
e.printStackTrace();
}
}
}
/*
* Read from the multicast socket in a separate thread to make this
* asynchronous. The main program will be informed of a new received
* packet when the onMessage() method (to be implemented by a subclass)
* is called.
*/
class ReaderThread extends Thread {
@Override
public void run() {
try {
if (multicastSocket.isBound()) {
/*
* onClosedStatus() method to be implemented by a
* sublclass.
*/
onClosedStatus(false) ;
} else {
throw new Exception("ReaderThread socket not bound");
}
byte[] readBuf = new byte[MAX_DATAGRAM_MSG_SIZE];
DatagramPacket readPacket = new DatagramPacket(readBuf,
readBuf.length);
/*
* Read one DatagramPacket at a time from MulticastSocket
* instance, The receive() method below will block until
* a datagram is recieved.
*/
while (true) {
multicastSocket.receive(readPacket);
String msg = new String(readPacket.getData(),
0, readPacket.getLength());
if (debugFlagIsSet(DEBUG_RECV)) {
System.out.println("recv> " + msg);
}
/*
* onMessage() method to be implemented by a sublclass.
*/
onMessage(msg);
}
} catch (Exception e) {
if (debugFlagIsSet(DEBUG_EXCEPTIONS)) {
e.printStackTrace();
}
} finally {
close();
}
}
}
/**
* Send a message in String format to the MulticastSocket instance.
*
* @param msg The String message to send
*/
public void sendMessage(String msg) {
byte[] sendMsgBuf = msg.getBytes();
DatagramPacket packet = new DatagramPacket(sendMsgBuf,
sendMsgBuf.length, inetAddress, portNum);
if (debugFlagIsSet(DEBUG_SEND)) {
System.out.println("send> " + msg);
}
try {
multicastSocket.send(packet);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Determines if the socket is connected.
* @return true if the socket is connected, false if not.
*/
public boolean isConnected() {
if (multicastSocket != null) {
return multicastSocket.isConnected();
} else {
return false;
}
}
/**
* Returns true if the specified debug flag is set.
* @param flag Debug flag in question
* @return true if the debug flag 'flag' is set.
*/
public boolean debugFlagIsSet(int flag) {
return ((flag & debugFlags) != 0) ? true : false;
}
/**
* Turn on debugging option.
* @param flags The debugging flags to enable
*/
public void setDebugFlags(int flags) {
debugFlags = flags;
}
/**
* Turn off debugging option.
*/
public void clearDebugFlags() {
debugFlags = DEBUG_NONE;
}
@Override
public void run() {
connect();
}
public MulticastConnection() {
this(DEFAULT_SESSION_ADDR, DEFAULT_PORT, DEBUG_NONE);
}
public MulticastConnection(int portNum) {
this(DEFAULT_SESSION_ADDR, portNum, DEBUG_NONE);
}
public MulticastConnection(String addr, int portNum, int debugFlags) {
this.addr = addr;
this.portNum = portNum;
this.debugFlags = debugFlags;
}
}
| true
|
e00fda8476d6fc792abc1bceefc0de1605e7b114
|
Java
|
budnyjj/money_keeper
|
/app/android/app/src/main/java/budny/moneykeeper/db/util/IDataChangeListener.java
|
UTF-8
| 267
| 1.859375
| 2
|
[
"MIT"
] |
permissive
|
package budny.moneykeeper.db.util;
/**
* An interface to notify UI layer about data changes.
*
* The purpose of this method is to avoid exposing storage-related
* details (Realm) to the UI level.
*/
public interface IDataChangeListener {
void onChange();
}
| true
|
9951c157d9cebd7d650e1e731236f785f02b20dd
|
Java
|
YesungLee/AcademyJava
|
/Machine/src/kiosk/JPanel05.java
|
UTF-8
| 433
| 2.4375
| 2
|
[] |
no_license
|
package kiosk;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class JPanel05 extends JPanel{
JPanelChange win;
JTextArea textbox = new JTextArea();
public JPanel05(JPanelChange win)
{
setLayout(null);
this.win = win;
textbox.setBounds(7, 10, 710, 300);
textbox.setEditable(false); // 텍스트 수정 X
add(textbox);
}
public void setTextBox(String text)
{
textbox.append(text);
}
}
| true
|
af588d130db59b94e59033dd39df3394c01f7edd
|
Java
|
JorgeGarcia855/Fund-de-Prog
|
/FP_PicasFijasFinal/src/co/edu/unbosque/view/VentanaPrincipal.java
|
ISO-8859-1
| 1,979
| 3.0625
| 3
|
[] |
no_license
|
package co.edu.unbosque.view;
/**
* Clase VentanaPrincipal
*
* Clase de la vista que cuenta con 2 metodos, el constructor y otro de tipo void.
*
* @author David Real
* @author David Milln
* @author Jorge Garca
* @version 1.0
*
*/
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
@SuppressWarnings("serial")
public class VentanaPrincipal extends JFrame{
/**
* Objeto de PanelPricipal que permite llamar sus mtodos y atributos
*/
private PanelPrincipal principal;
/**
* Objeto de PanelImagen que permite llamar sus mtodos y atributos
*/
private PanelImagen pImagen;
/**
* Objeto de JLayeredPane
*/
private JLayeredPane lPane;
/**
* Mtodo Contructor de la clase VentanaPrincipal
*/
public VentanaPrincipal() {
setTitle("Men Principal");
setSize(500, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(null);
getContentPane().setBackground(Color.darkGray);
inicializarComponentes();
setResizable(false);
setLocationRelativeTo(null);
setVisible(true);
}
/**
* Mtodo que inicializa los componentes de los objetos.
*
*/
public void inicializarComponentes() {
principal = new PanelPrincipal();
principal.setBounds(5, 5, 475,350);
principal.setOpaque(false);
getContentPane().add(principal);
lPane = new JLayeredPane();
lPane.setBounds(0, 0, 500, 400);
getContentPane().add(lPane);
pImagen = new PanelImagen();
pImagen.setBounds(75, 20, 320, 320);
pImagen.setOpaque(true);
lPane.add(pImagen, new Integer(0), 0);
}
public PanelPrincipal getPrincipal() {
return principal;
}
public void setPrincipal(PanelPrincipal principal) {
this.principal = principal;
}
public PanelImagen getpImagen() {
return pImagen;
}
public void setpImagen(PanelImagen pImagen) {
this.pImagen = pImagen;
}
public JLayeredPane getlPane() {
return lPane;
}
public void setlPane(JLayeredPane lPane) {
this.lPane = lPane;
}
}
| true
|
c48f4b5e143c0c1e667063f8987bd21605b03ce3
|
Java
|
lbbzcy/news-release-system
|
/news-frontend/src/main/java/com/news/frontend/controller/SolrController.java
|
UTF-8
| 1,391
| 2.03125
| 2
|
[] |
no_license
|
package com.news.frontend.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.news.common.core.dto.PageData;
import com.news.common.core.utils.SolrUtils;
import com.news.common.project.dto.NewsDetailDto;
import com.news.frontend.common.BaseController;
@Controller
@RequestMapping("/solr")
public class SolrController extends BaseController {
/**
* 全文检索
* @param queryParam
* @param request
* @param model
* @param pageData
* @return
* @throws Exception
*/
@RequestMapping("/search")
public String search(@RequestParam(value="queryParam") String queryParam
,HttpServletRequest request
,Model model
,PageData<NewsDetailDto> pageData) throws Exception {
getAllNewsType(model);
System.out.println("queryparam:"+queryParam);
queryParam = new String(queryParam.getBytes("ISO-8859-1"), "UTF-8");
if(null != queryParam && !"".equals(queryParam)){
pageData.setPageSize(8);
List<NewsDetailDto> queryList = SolrUtils.querySolr(queryParam);
pageData.setRows(queryList);
model.addAttribute("pageData", pageData);
setPagination(model, pageData, request);
}
return "/solr/result";
}
}
| true
|
2740420171836cffe9d97a16643ddd2c3cfaeb75
|
Java
|
lavantien/iot
|
/src/main/java/com/t3/iot/api/DataRealtimeController.java
|
UTF-8
| 1,327
| 2.1875
| 2
|
[] |
no_license
|
package com.t3.iot.api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@RestController
@RequestMapping("/api/data-realtime")
public class DataRealtimeController {
DataRealltimeRepository dataRealltimeRepository;
@Autowired
public DataRealtimeController(DataRealltimeRepository dataRealltimeRepository) {
this.dataRealltimeRepository = dataRealltimeRepository;
}
@GetMapping
public ResponseEntity<List<DataRealtime>> getAll() {
return ResponseEntity.ok(this.dataRealltimeRepository.findAll());
}
@PostMapping
public ResponseEntity save(@RequestBody DataRealtime dataRealtime) {
this.dataRealltimeRepository.save(dataRealtime);
return ResponseEntity.ok().build();
}
@GetMapping("/save")
public ResponseEntity saveFromDevice(@RequestParam Double humidity, @RequestParam Double temperature, @RequestParam Double heatIndex) {
DataRealtime dataRealtime = new DataRealtime(humidity, temperature, heatIndex, new SimpleDateFormat("yyyy-MM-dd").format(new Date()), new SimpleDateFormat("HH:mm:ss").format(new Date()));
this.dataRealltimeRepository.save(dataRealtime);
return ResponseEntity.ok().build();
}
}
| true
|
4b61fe1a77946e2c9c0e9a2fb25ec99316a2095c
|
Java
|
sanjeevhalyal/VCSshark
|
/src/getfiles/getfiles.java
|
UTF-8
| 1,928
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
package getfiles;
import java.io.File;
import java.io.FilenameFilter;
public class getfiles {
public static String getsharkfile(String path, String projectname) throws Exception {
File file = new File(path);
System.out.println(path);
String[] subfiles = file.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
if(name.lastIndexOf('.')>0) {
// get last index for '.' char
int lastIndex = name.lastIndexOf('.');
// get extension
String str = name.substring(lastIndex);
if(str.equals(".shark")) {
return true;
}
}
return false;
}});
if(subfiles.length==0)
{
throw new Exception("No Shark File");
}
return subfiles[0];
// return customverifyandreturn(".ser", ".shark", subfiles, projectname);
}
public static String getserfile(String path, String projectname) throws Exception {
File file = new File(path);
String[] subfiles = file.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
if(name.lastIndexOf('.')>0) {
// get last index for '.' char
int lastIndex = name.lastIndexOf('.');
// get extension
String str = name.substring(lastIndex);
// match path name extension
if(str.equals(".ser")) {
return true;
}
}
return false;
}});
if(subfiles.length==0)
{
throw new Exception("No object File");
}
return subfiles[0];
}
}
| true
|
f258b5001c8ada90440ac99a143f5a7ec5f42e3d
|
Java
|
sanjeet123456789/spring_project
|
/major_project/src/main/java/com/pal/controller/TeacherRestController.java
|
UTF-8
| 2,203
| 2.234375
| 2
|
[
"MIT"
] |
permissive
|
package com.pal.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.pal.dao.TeachersDao;
import com.pal.entity.Class_t;
import com.pal.entity.Teachers_t;
import com.pal.service.CustomerService;
@Controller
@RequestMapping("/admin/teachers_t")
public class TeacherRestController {
@Autowired
private CustomerService customerService;
// @Autowired
// private TeachersDao pal;
@GetMapping("/listTeachers")
public String listTeachers_ts(Model theModel) {
List<Teachers_t> theClass_ts=customerService.getTeachers_ts();
theModel.addAttribute("teachers_ts", theClass_ts);
return "list-teachers_ts";
}
@RequestMapping("/showFormForAddTeachers")
public String showFormTeachers_t(Model theModel) {
Teachers_t theCustomer =new Teachers_t();
theModel.addAttribute("teachers_t",theCustomer);
return "teachers_t-form";
}
@PostMapping("/saveTeachers_t")
public String saveTeachers_t(@ModelAttribute("teachers_t") Teachers_t theTeachers_t) {
//save the customer using our service
customerService.saveTeachers_t(theTeachers_t);
return "redirect:/admin/teachers_t/listTeachers";
}
@GetMapping("/showFormForUpdateTeachers")
public String showFormForUpdateTeachers(@RequestParam("teachers_tId") int theId,
Model theModel) {
//get customer from the service
Teachers_t theCustomer=customerService.getTeachers_t(theId);
//set customer as a model attribute to pre-populate the form
theModel.addAttribute("teachers_t", theCustomer);
//send over to our form
return "teachers_t-form";
}
@GetMapping("/delete")
public String deleteTeachers_t(@RequestParam("teachersId") int theId) {
customerService.deleteTeachers_t(theId);
return "redirect:/admin/teachers_t/listTeachers";
}
}
| true
|
3e7ade7a8f9fafa8b26ecc08030bf23d11eb6203
|
Java
|
SpookyHammer/Berlin
|
/test/ClockTest.java
|
UTF-8
| 2,326
| 3
| 3
|
[] |
no_license
|
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.time.DateTimeException;
import java.time.LocalDateTime;
import org.junit.*;
public class ClockTest {
@Test
public void testLocalClock() {
Clock clock = new Clock("local");
LocalDateTime now = LocalDateTime.now();
assertEquals(clock.time.getHour(), now.getHour());
assertEquals(clock.time.getMinute(), now.getMinute());
assertEquals(clock.time.getSecond(), now.getSecond());
}
@Test
public void testMinValidClock() {
Clock clock = new Clock("00:00:00");
assertEquals(clock.time.getHour(), 0);
assertEquals(clock.time.getMinute(), 0);
assertEquals(clock.time.getSecond(), 0);
}
@Test
public void testMaxValidClock() {
Clock clock = new Clock("23:59:59");
assertEquals(clock.time.getHour(), 23);
assertEquals(clock.time.getMinute(), 59);
assertEquals(clock.time.getSecond(), 59);
}
@Test
public void testMinHourWriten() {
Clock clock = new Clock("00:00:00");
assertEquals(clock.getSeconds(), "O");
assertEquals(clock.getHoursTop(), "----");
assertEquals(clock.getHoursLower(), "----");
assertEquals(clock.getMinutesTop(), "-----------");
assertEquals(clock.getMinutesLower(), "----");
}
@Test
public void testMaxHourWriten() {
Clock clock = new Clock("23:59:59");
assertEquals(clock.getSeconds(), "-");
assertEquals(clock.getHoursTop(), "HHHH");
assertEquals(clock.getHoursLower(), "hhh-");
assertEquals(clock.getMinutesTop(), "MMRMMRMMRMM");
assertEquals(clock.getMinutesLower(), "mmmm");
}
@Test(expected = DateTimeException.class)
public void testOverMaxClock() {
Clock clock = new Clock("25:25:25");
}
@Test(expected = DateTimeException.class)
public void testUnderMinClock() {
Clock clock = new Clock("-5:00:00");
}
@Test
public void testFullBerlinClock() {
Clock clock = new Clock("19:25:35");
String expected = "";
expected += "-" + "\n";
expected += "HHH-" + "\n";
expected += "hhhh" + "\n";
expected += "MMRMM------" + "\n";
expected += "----";
assertEquals(clock.writeFullBerlin(), expected);
}
@Test(expected = IllegalArgumentException.class)
public void illigalArgumentThrownTest() {
Clock clock = new Clock("wrong text");
}
}
| true
|
62515d2b4567254631bd7527af2ae3ecc6dd41ed
|
Java
|
nightwolf93/Wakxy-Core-Decompiled
|
/1_39_120042/com/ankamagames/baseImpl/graphics/alea/display/lights/IsoLightSourceModifier.java
|
UTF-8
| 6,924
| 2.4375
| 2
|
[] |
no_license
|
package com.ankamagames.baseImpl.graphics.alea.display.lights;
import com.ankamagames.baseImpl.graphics.alea.display.lights.lightMap.*;
import com.ankamagames.baseImpl.graphics.isometric.debug.particlesAndLights.*;
import com.ankamagames.framework.graphics.engine.light.*;
import com.ankamagames.framework.kernel.core.maths.*;
import gnu.trove.*;
public class IsoLightSourceModifier extends LitSceneModifierMap
{
private static final IsoLightSourceModifier m_instance;
private final TIntObjectHashMap<IsoLightSource> m_lights;
private final Cache m_lightCache;
private final UpdatelightSourceProcedure m_updateProcedure;
public static IsoLightSourceModifier getInstance() {
return IsoLightSourceModifier.m_instance;
}
private IsoLightSourceModifier() {
super();
this.m_lights = new TIntObjectHashMap<IsoLightSource>();
this.m_lightCache = new Cache(1024);
this.m_updateProcedure = new UpdatelightSourceProcedure();
}
@Override
public void precompute() {
this.m_lightCache.reset();
if (!this.m_lights.isEmpty()) {
final float lightFactor = 1.0f;
this.m_lights.forEachValue(new TObjectProcedure<IsoLightSource>() {
@Override
public boolean execute(final IsoLightSource light) {
if (light.isEnabled() && light.getIntensity() != 0.0f) {
light.apply(IsoLightSourceModifier.this.m_lightCache, 1.0f);
}
return true;
}
});
}
}
@Override
public void update(final int deltaTime) {
}
@Override
public int getPriority() {
return 600;
}
@Override
public boolean useless() {
return this.m_lights.isEmpty();
}
@Override
public void apply(final int x, final int y, final int z, final int layerId, final float[] colors) {
this.m_lightCache.applyOnColor(x, y, z, colors);
}
void updateLightSource(final float lightIntensity, final int deltaTime) {
this.m_updateProcedure.reset(lightIntensity, deltaTime);
if (!this.m_lights.isEmpty()) {
this.m_lights.forEachValue(this.m_updateProcedure);
}
final int toRemoveCount = this.m_updateProcedure.m_lightsIdToRemove.size();
if (toRemoveCount != 0) {
for (int i = 0; i < toRemoveCount; ++i) {
this.removeLight(this.m_updateProcedure.m_lightsIdToRemove.getQuick(i));
}
}
}
public final void add(final IsoLightSource light) {
this.m_lights.put(light.getId(), light);
ParticlesAndLightDebug.INSTANCE.addLightSource(light);
}
public final void removeLight(final int id) {
final IsoLightSource light = this.m_lights.remove(id);
ParticlesAndLightDebug.INSTANCE.removeLightSource(light);
}
public final void clear() {
this.m_lights.clear();
}
public final IsoLightSource getLight(final int id) {
return this.m_lights.get(id);
}
@Override
public void setBounds(final int minX, final int minY, final int width, final int height) {
this.m_lightCache.setBounds(minX, minY, width, height);
}
static {
m_instance = new IsoLightSourceModifier();
}
private static class Cache implements LightMap
{
private final Rect m_bounds;
private final TLongObjectHashMap<float[]> m_colors;
Cache(final int capacity) {
super();
this.m_bounds = new Rect(0, 0, 0, 0);
this.m_colors = new TLongObjectHashMap<float[]>(capacity, 0.9f);
}
public final void reset() {
this.m_colors.clear();
}
public final void applyOnColor(final int x, final int y, final int z, final float[] colors) {
final float[] v = this.m_colors.get(hash(x, y, z));
if (v != null) {
final int n = 0;
colors[n] += v[0] + v[3];
final int n2 = 1;
colors[n2] += v[1] + v[4];
final int n3 = 2;
colors[n3] += v[2] + v[5];
}
}
static long hash(final int x, final int y, final int z) {
return MathHelper.getIntFromTwoInt(x, y);
}
@Override
public Rect getBounds() {
return this.m_bounds;
}
@Override
public void setBounds(final int minX, final int minY, final int width, final int height) {
this.m_bounds.set(minX, minX + width, minY, minY + height);
}
@Override
public void addColors(final int x, final int y, final int z, final float br, final float bg, final float bb, final float sr, final float sg, final float sb) {
final long hash = hash(x, y, z);
final float[] value = this.m_colors.get(hash);
if (value != null) {
final float[] array = value;
final int n = 0;
array[n] += br;
final float[] array2 = value;
final int n2 = 1;
array2[n2] += bg;
final float[] array3 = value;
final int n3 = 2;
array3[n3] += bb;
final float[] array4 = value;
final int n4 = 3;
array4[n4] += sr;
final float[] array5 = value;
final int n5 = 4;
array5[n5] += sg;
final float[] array6 = value;
final int n6 = 5;
array6[n6] += sb;
}
else {
this.m_colors.put(hash, new float[] { br, bg, bb, sr, sg, sb });
}
}
}
private static class UpdatelightSourceProcedure implements TObjectProcedure<IsoLightSource>
{
private float m_lightIntensity;
private int m_deltaTime;
final TIntArrayList m_lightsIdToRemove;
private UpdatelightSourceProcedure() {
super();
this.m_lightsIdToRemove = new TIntArrayList();
}
@Override
public boolean execute(final IsoLightSource light) {
if (light.isNightOnly()) {
light.setIntensity(this.m_lightIntensity);
}
light.update(this.m_deltaTime);
if (light.isShutdown()) {
this.m_lightsIdToRemove.add(light.getId());
}
return true;
}
void reset(final float lightIntensity, final int deltaTime) {
this.m_lightIntensity = lightIntensity;
this.m_deltaTime = deltaTime;
this.m_lightsIdToRemove.resetQuick();
}
}
}
| true
|
7d66dfa80aaa185b65fd753e385141f8554cad7d
|
Java
|
StefanLiebenberg/jspackage
|
/jspackage-jsunit/src/main/java/org/slieb/jspackage/jsunit/internal/CachedTestConfigurator.java
|
UTF-8
| 1,614
| 1.992188
| 2
|
[] |
no_license
|
package org.slieb.jspackage.jsunit.internal;
import org.slieb.jspackage.dependencies.GoogDependencyCalculator;
import org.slieb.jspackage.dependencies.GoogDependencyNode;
import org.slieb.jspackage.jsunit.api.TestConfigurator;
import org.slieb.kute.api.Resource;
import java.util.Collection;
public class CachedTestConfigurator implements TestConfigurator {
private final Resource.Provider sourceProvider, testProvider;
private final GoogDependencyCalculator calculator;
private final Integer timeout;
public CachedTestConfigurator(TestConfigurator testConfigurator) {
this.sourceProvider = testConfigurator.sources();
this.testProvider = testConfigurator.tests();
this.calculator = new CachedCalculator(this.sourceProvider);
this.timeout = testConfigurator.getTimeout();
}
public GoogDependencyCalculator calculator() {
return calculator;
}
@Override
public Resource.Provider tests() {
return testProvider;
}
@Override
public Resource.Provider sources() {
return sourceProvider;
}
@Override
public Integer getTimeout() {
return timeout;
}
}
class CachedCalculator extends GoogDependencyCalculator {
private Collection<GoogDependencyNode> cachedNodes;
public CachedCalculator(Iterable<Resource.Readable> resources) {
super(resources);
}
@Override
public Collection<GoogDependencyNode> getDependencyNodes() {
if (cachedNodes == null) {
cachedNodes = super.getDependencyNodes();
}
return cachedNodes;
}
}
| true
|
832eb9249ab8b2300bc3b8bc66a82555edf2c1ba
|
Java
|
learnercys/hazelcast-nodejs-client
|
/test/javaclasses/ComparatorFactory.java
|
UTF-8
| 492
| 2.171875
| 2
|
[
"Apache-2.0"
] |
permissive
|
import com.hazelcast.nio.serialization.DataSerializableFactory;
import com.hazelcast.nio.serialization.IdentifiedDataSerializable;
public class ComparatorFactory implements DataSerializableFactory {
private static ReverseValueComparator reverseComparator = new ReverseValueComparator();
@Override
public IdentifiedDataSerializable create(int typeId) {
if (typeId == 1) {
return reverseComparator;
} else {
return null;
}
}
}
| true
|
a09f4f14b7b317a7a7a7d9798fe7e65e43412dd9
|
Java
|
uemurakento/stock-management-bugfix-spring
|
/src/main/java/jp/co/rakus/stockmanagement/web/BookController.java
|
UTF-8
| 3,920
| 2.59375
| 3
|
[] |
no_license
|
package jp.co.rakus.stockmanagement.web;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import jp.co.rakus.stockmanagement.domain.Book;
import jp.co.rakus.stockmanagement.service.BookService;
/**
* 書籍関連処理を行うコントローラー.
* @author igamasayuki
*
*/
@Controller
@RequestMapping("/book")
@Transactional
public class BookController {
@Autowired
private BookService bookService;
/**
* フォームを初期化します.
* @return フォーム
*/
@ModelAttribute
public BookForm setUpForm() {
return new BookForm();
}
/**
* 書籍情報登録フォームの初期化.
*
* @return フォーム
*/
@ModelAttribute
public BookRegistrationForm setUpRegistrationForm() {
return new BookRegistrationForm();
}
/**
* 書籍リスト情報を取得し書籍リスト画面を表示します.
* @param model モデル
* @return 書籍リスト表示画面
*/
@RequestMapping(value = "list")
public String list(Model model) {
List<Book> bookList = bookService.findAll();
model.addAttribute("bookList", bookList);
return "book/list";
}
/**
* 書籍詳細情報を取得し書籍詳細画面を表示します.
* @param id 書籍ID
* @param model モデル
* @return 書籍詳細画面
*/
@RequestMapping(value = "show/{bookId}")
public String show(@PathVariable("bookId") Integer id, Model model) {
Book book = bookService.findOne(id);
model.addAttribute("book", book);
return "book/show";
}
/**
* 書籍更新を行います.
* @param form フォーム
* @param result リザルト情報
* @param model モデル
* @return 書籍リスト画面
*/
@RequestMapping(value = "update")
public String update(@Validated BookForm form, BindingResult result, Model model) {
if (result.hasErrors()) {
return show(form.getId(), model);
}
Book book = bookService.findOne(form.getId());
book.setStock(form.getStock());
bookService.update(book);
return list(model);
}
@RequestMapping(value = "registrationView")
public String registrationView() {
return "book/bookForm";
}
@RequestMapping(value = "registration")
public String registration(@Validated BookRegistrationForm form,BindingResult result,Model model) throws ParseException {
if(form.getImage().isEmpty()) {
result.rejectValue("image", null, "画像を選択してください");
}
if (form.getImage().getContentType().indexOf("image") == -1) {
System.out.println(form.getImage().getContentType().indexOf("image"));
result.rejectValue("image", null, "画像形式のファイルを選択してください");
}
if(result.hasErrors()) {
return registrationView();
}
//画像保存処理
//TODO:同じ名前の画像ファイルが入力されたときに上書きされてしまうので直す必要がある
bookService.uploadImage(form.getImage());
//書籍登録処理
Book book = new Book();
BeanUtils.copyProperties(form, book);
book.setPrice(Integer.valueOf(form.getPrice()));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date saleDate = sdf.parse(form.getSaledate());
book.setSaledate(saleDate);
book.setImage(form.getImage().getOriginalFilename());
book.setStock(0);
bookService.insert(book);
return list(model);
}
}
| true
|
f58666455cd2cf0b6621d87fddc2d80ef4ecec6c
|
Java
|
kannans89/sample-bank-app
|
/bank-application/src/main/java/com/techlabs/viewmodel/LoginViewModel.java
|
UTF-8
| 530
| 2.1875
| 2
|
[] |
no_license
|
package com.techlabs.viewmodel;
public class LoginViewModel
{
private boolean postBack=false;
private String userId;
private String password;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isPostBack() {
return postBack;
}
public void setPostBack(boolean postBack) {
this.postBack = postBack;
}
}
| true
|
53931d6308b5261b4ae8323af7230f8d12777812
|
Java
|
erickjhorman/reddit-clone-spring
|
/src/main/java/com/co/reddit/controller/AuthController.java
|
UTF-8
| 1,203
| 2.140625
| 2
|
[] |
no_license
|
package com.co.reddit.controller;
import com.co.reddit.dto.AuthenticationResponse;
import com.co.reddit.dto.LoginRequest;
import com.co.reddit.dto.RegisterRequest;
import com.co.reddit.service.AuthService;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/auth")
@AllArgsConstructor
public class AuthController {
private final AuthService authService;
@PostMapping("/signup")
public ResponseEntity<String> signup(@RequestBody RegisterRequest registerRequest){
authService.signup(registerRequest);
return new ResponseEntity<>("User Registration Successfully", HttpStatus.OK);
}
@GetMapping("accountVerificacion/{token}")
public ResponseEntity<String> verifyAccount(@PathVariable String token){
authService.verifyAccount(token);
return new ResponseEntity<>("Account Activated Successfully", HttpStatus.OK);
}
@PostMapping("/login")
public AuthenticationResponse login(@RequestBody LoginRequest loginRequest){
return authService.login(loginRequest);
}
}
| true
|
8104e59f50f5838edb87044825185ad393b24ad3
|
Java
|
wangkai265/wangkai
|
/IntelligentServer/app/src/main/java/com/newland/digled/Digled.java
|
UTF-8
| 1,605
| 2.796875
| 3
|
[] |
no_license
|
package com.newland.digled;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author lin
* @version 2018/7/2 0002
*/
public class Digled {
static {
System.loadLibrary("Digled");
}
private static native int JNI_PosDledVer(byte[] buf);
private static native int JNI_PosShowDigLed(byte[] buf);
private static native int JNI_PosDledBright(int bright);
private static native int JNI_PosDledClr();
/**
* 获取驱动版本
* @param buf
* @return
*/
public int digLedVer(byte[] buf){
if (buf == null){
return -2;
}
if (buf.length < 28){
return -2;
}
return JNI_PosDledVer(buf);
}
Pattern mPattern = Pattern.compile("([0-9]|\\.)*");
/**
* 显示应用层传递下来的字符数字
* @param num
* @return
*/
public int showDigLed(String num){
if (num == null || "".equals(num)){
return -2;
}
Matcher matcher = mPattern.matcher(num);
if (!matcher.matches()) {
return -2;
}
byte[] numBuffer = new byte[num.getBytes().length+1];
System.arraycopy(num.getBytes(), 0, numBuffer, 0, numBuffer.length-1);
return JNI_PosShowDigLed(numBuffer);
}
/**
* 设置亮度及开启扫描
* @param bright 0-7
* @return
*/
public int brightDigLed(int bright){
return JNI_PosDledBright(bright);
}
/**
* 数码管全灭
* @return
*/
public int clrDigLed(){return JNI_PosDledClr();}
}
| true
|
2841b124ffd163c05113481bcdc217c83e5c79a0
|
Java
|
adminho/BigOFamily
|
/src/com/bigo/fragment/EasyFortuneAdapter.java
|
UTF-8
| 2,940
| 2.5
| 2
|
[] |
no_license
|
package com.bigo.fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import com.bigo.activity.EasyFortuneActv;
import com.bigo.activity.R;
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class EasyFortuneAdapter extends FragmentPagerAdapter {
/**
* The fragment argument representing the section number for this fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
private final FragmentActivity activity;
private final Intent intent;
public EasyFortuneAdapter(FragmentActivity activity,Intent intent) {
super(activity.getSupportFragmentManager());
this.activity = activity;
this.intent = intent;
}
private Bundle extractData() {
Bundle bundle = new Bundle();
bundle.putString(EasyFortuneActv.PHONE_NUM, intent.getStringExtra (EasyFortuneActv.PHONE_NUM));
bundle.putString(EasyFortuneActv.PHONE_SUMNUM, intent.getStringExtra (EasyFortuneActv.PHONE_SUMNUM));
bundle.putString(EasyFortuneActv.AUSP_NUM, intent.getStringExtra (EasyFortuneActv.AUSP_NUM));
bundle.putString(EasyFortuneActv.GOOD_NUM, intent.getStringExtra (EasyFortuneActv.GOOD_NUM));
bundle.putString(EasyFortuneActv.BAD_NUM, intent.getStringExtra (EasyFortuneActv.BAD_NUM));
bundle.putString(EasyFortuneActv.FORECAST_1, intent.getStringExtra (EasyFortuneActv.FORECAST_1));
bundle.putString(EasyFortuneActv.FORECAST_2, intent.getStringExtra (EasyFortuneActv.FORECAST_2));
bundle.putString(EasyFortuneActv.FORECAST_3, intent.getStringExtra (EasyFortuneActv.FORECAST_3));
bundle.putString(EasyFortuneActv.FORECAST_NUM, intent.getStringExtra (EasyFortuneActv.FORECAST_NUM));
bundle.putString(EasyFortuneActv.BIRTHDAY_OF_WEEK, intent.getStringExtra(EasyFortuneActv.BIRTHDAY_OF_WEEK));
bundle.putString(EasyFortuneActv.BIRTHDAY, intent.getStringExtra(EasyFortuneActv.BIRTHDAY));
return bundle;
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = null;
switch (position){
case 0:
fragment = new PhoneFlgmt();
break;
case 1:
fragment = new BirthDayFlgmt();
break;
}
Bundle args = extractData();
args.putInt(EasyFortuneAdapter.ARG_SECTION_NUMBER, position);
fragment.setArguments(args);
return fragment;
}
@Override
public int getCount() {
return 2;// Show 2 total pages.
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return activity.getString(R.string.result_phone);
case 1:
return activity.getString(R.string.result_birthday);
}
return null;
}
}
| true
|
b0c8a6ba19fb21034ebfc7b8d5d530c613bf7534
|
Java
|
ryanlfoster/ep-commerce-engine-68
|
/core/ep-core/src/main/java/com/elasticpath/cmweb/dto/catalog/impl/PriceListEditorModelImpl.java
|
UTF-8
| 9,809
| 2.40625
| 2
|
[] |
no_license
|
package com.elasticpath.cmweb.dto.catalog.impl;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.EqualsBuilder;
import com.elasticpath.cmweb.dto.catalog.PriceListEditorModel;
import com.elasticpath.common.dto.ChangeSetObjects;
import com.elasticpath.common.dto.category.ChangeSetObjectsImpl;
import com.elasticpath.common.dto.pricing.BaseAmountDTO;
import com.elasticpath.common.dto.pricing.PriceListDescriptorDTO;
/**
* Default implementation of PriceListEditorModel. The model manages a snapshot of a Price List retrieved from the database, along
* with a change set capturing any modifications a client might want to make to the Price List. The model should have no
* dependencies on any service or view.
*/
public class PriceListEditorModelImpl implements PriceListEditorModel, Serializable {
private static final long serialVersionUID = 1L;
private PriceListDescriptorDTO priceListDescriptor;
/*
* The list of base amount DTOs should remain unchanged once created, as it is meant to be a snapshot.
*/
private final List<BaseAmountDTO> baseAmountDtos = new ArrayList<BaseAmountDTO>();
/*
* The change set contains required modifications to the snapshot list of base amounts. Management of items in this ChangeSet
* is required when adding new items. All items in resultant change set should only be in one of the states. i.e. either add
* or remove, not both.
*/
private ChangeSetObjects<BaseAmountDTO> changeSet = new ChangeSetObjectsImpl<BaseAmountDTO>();
/**
* Constructs the model.
*
* @param priceListDescriptor PriceListDescriptor of this Price List
* @param baseAmounts collection for this Price List
*/
public PriceListEditorModelImpl(final PriceListDescriptorDTO priceListDescriptor, final Collection<BaseAmountDTO> baseAmounts) {
this.priceListDescriptor = priceListDescriptor;
this.baseAmountDtos.addAll(baseAmounts);
}
/**
* Get the BaseAmounts in this model. This list is generated by a combination/subtraction of the changes with the snapshot
* list of BaseAmounts.
*
* @return full list of BaseAmounts managed by this Price List model.
*/
public List<BaseAmountDTO> getBaseAmounts() {
List<BaseAmountDTO> fullBaseAmount = new ArrayList<BaseAmountDTO>();
fullBaseAmount.addAll(baseAmountDtos);
for (BaseAmountDTO toRemove : changeSet.getRemovalList()) {
removeFromListIfExisting(fullBaseAmount, toRemove);
}
for (BaseAmountDTO toUpdate : changeSet.getUpdateList()) {
updateExistingBaseAmount(fullBaseAmount, toUpdate);
}
fullBaseAmount.addAll(this.changeSet.getAdditionList());
return fullBaseAmount;
}
/**
* Get the BaseAmounts in this model. Removed objects are still kept as existing until save action.
*
* @return full list of BaseAmounts managed by this Price List model.
*/
public Collection<BaseAmountDTO> getBaseAmountWithRemoved() {
Set<BaseAmountDTO> fullBaseAmount = new HashSet<BaseAmountDTO>();
fullBaseAmount.addAll(baseAmountDtos);
for (BaseAmountDTO toUpdate : changeSet.getUpdateList()) {
updateExistingBaseAmount(fullBaseAmount, toUpdate);
}
fullBaseAmount.addAll(this.changeSet.getRemovalList());
fullBaseAmount.addAll(this.changeSet.getAdditionList());
return fullBaseAmount;
}
/**
* Filters base amounts by given object type.
*
* @param businessObjectType business object type
* @return list of base amounts with given object type
*/
public List<BaseAmountDTO> filterBaseAmounts(final String businessObjectType) {
return filterBaseAmounts(businessObjectType, getBaseAmounts());
}
/**
* Filters given base amounts.
*
* @param businessObjectType business object type
* @param baseAmountList list of base amounts to filter
* @return filtered list of base amounts
*/
protected List<BaseAmountDTO> filterBaseAmounts(final String businessObjectType, final List<BaseAmountDTO> baseAmountList) {
CollectionUtils.filter(baseAmountList, new Predicate() {
public boolean evaluate(final Object baseAmount) {
return ((BaseAmountDTO) baseAmount).getObjectType().equals(businessObjectType);
}
});
return baseAmountList;
}
@Override
public boolean hasBaseAmounts() {
return getNumberOfBaseAmounts() != 0;
}
@Override
public int getNumberOfBaseAmounts() {
return baseAmountDtos.size() + changeSet.getAdditionList().size() - changeSet.getRemovalList().size();
}
/**
* Update a BaseAmount entry in a list if it exists. If the item is already in the list, replace it with the updated entry.
* Otherwise simply add.
*
* @param baseAmountList list of BaseAmountDTOs
* @param toUpdate the updated entry
*/
protected void updateExistingBaseAmount(final Collection<BaseAmountDTO> baseAmountList, final BaseAmountDTO toUpdate) {
for (Iterator<BaseAmountDTO> iterator = baseAmountList.iterator(); iterator.hasNext();) {
BaseAmountDTO item = iterator.next();
if (StringUtils.isNotEmpty(item.getGuid()) && item.getGuid().equals(toUpdate.getGuid())) {
iterator.remove();
continue;
}
}
baseAmountList.add(toUpdate);
}
/**
* Remove an entry from a list if it exists. We must use logical comparisons because items in the list might not have GUIDs.
*
* @param baseAmountList list of BaseAmountDTOs
* @param baseAmountItem item to remove
* @return boolean true if element was deleted, false in over case
*/
protected boolean removeFromListIfExisting(final List<BaseAmountDTO> baseAmountList, final BaseAmountDTO baseAmountItem) {
for (Iterator<BaseAmountDTO> iterator = baseAmountList.iterator(); iterator.hasNext();) {
if (logicalEquals(iterator.next(), baseAmountItem)) {
iterator.remove();
return true;
}
}
return false;
}
@Override
public void addBaseAmount(final BaseAmountDTO baseAmountDTO) {
baseAmountDTO.setPriceListDescriptorGuid(priceListDescriptor.getGuid());
this.changeSet.addToAdditionList(baseAmountDTO);
}
@Override
public void removeBaseAmount(final BaseAmountDTO baseAmountDTO) {
removeFromListIfExisting(changeSet.getAdditionList(), baseAmountDTO);
removeFromListIfExisting(changeSet.getUpdateList(), baseAmountDTO);
removeFromListIfExisting(changeSet.getRemovalList(), baseAmountDTO);
this.changeSet.addToRemovalList(baseAmountDTO);
}
@Override
public void removeAllBaseAmounts() {
for (BaseAmountDTO baseAmountDTO : getBaseAmounts()) {
removeBaseAmount(baseAmountDTO);
}
}
@Override
public void updateBaseAmount(final BaseAmountDTO oldBaseAmountDTO, final BaseAmountDTO newBaseAmountDTO) {
List<BaseAmountDTO> baseAmountList = this.getChangeSet().getAdditionList();
// check for add list. We should to check for any new created PL, new created PL can be edit also.
boolean wasFoundAndRemoved = removeFromListIfExisting(baseAmountList, oldBaseAmountDTO);
if (!wasFoundAndRemoved) { // if not found in add list, then try look in edit list
baseAmountList = this.getChangeSet().getUpdateList();
wasFoundAndRemoved = removeFromListIfExisting(baseAmountList, oldBaseAmountDTO);
}
baseAmountList.add(newBaseAmountDTO);
}
/**
* Gets base amount by qty.
* <p>
* NOTICE: it's not recommended to reimplement this method by calling getBaseAmounts().
* </p>
* @param qty the qty
* @return base amount with given qty
*/
public BaseAmountDTO getBaseAmountDTO(final int qty) {
BaseAmountDTO addBaseAmountDTO = getBaseAmountDTO(changeSet.getAdditionList(), qty);
if (addBaseAmountDTO != null) {
return addBaseAmountDTO;
}
if (getBaseAmountDTO(changeSet.getRemovalList(), qty) != null) {
return null; // return null if based amount removed but not persisted.
}
BaseAmountDTO persistedBaseAmount = getBaseAmountDTO(baseAmountDtos, qty);
if (persistedBaseAmount != null) {
return persistedBaseAmount;
}
return null;
}
/**
* Returns base amount by quantity.
*
* @param baseAmounts list of base amounts
* @param qty qty
* @return base amount with given qty or null if such base amount does not exist
*/
protected BaseAmountDTO getBaseAmountDTO(final List<BaseAmountDTO> baseAmounts, final int qty) {
for (BaseAmountDTO baseAmountDTO : baseAmounts) {
if (baseAmountDTO.getQuantity().intValue() == qty) {
return baseAmountDTO;
}
}
return null;
}
@Override
public boolean logicalEquals(final BaseAmountDTO dto1, final BaseAmountDTO dto2) {
return new EqualsBuilder().append(dto1.getObjectGuid(), dto2.getObjectGuid())
.append(dto1.getObjectType(), dto2.getObjectType())
.append(dto1.getQuantity(), dto2.getQuantity()).isEquals();
}
@Override
public PriceListDescriptorDTO getPriceListDescriptor() {
return this.priceListDescriptor;
}
@Override
public void setPriceListDescriptor(final PriceListDescriptorDTO dto) {
this.priceListDescriptor = dto;
}
@Override
public ChangeSetObjects<BaseAmountDTO> getChangeSet() {
return this.changeSet;
}
@Override
public boolean isNewlyAdded(final BaseAmountDTO baseAmountDto) {
return changeSet.getAdditionList().contains(baseAmountDto);
}
@Override
public boolean isDeleted(final BaseAmountDTO baseAmountDto) {
return changeSet.getRemovalList().contains(baseAmountDto);
}
@Override
public boolean isEdited(final BaseAmountDTO baseAmountDto) {
return changeSet.getUpdateList().contains(baseAmountDto);
}
@Override
public void setChangeSet(final ChangeSetObjects<BaseAmountDTO> changeSet) {
this.changeSet = changeSet;
}
@Override
public List<BaseAmountDTO> getRawBaseAmounts() {
return baseAmountDtos;
}
}
| true
|
cde8b2d6ca69f93aa37474025b36688a632b50b8
|
Java
|
wujialing1988/jx_kny
|
/JX_KNY/src/com/yunda/jx/pjwz/wellpartsmanage/wellpartsregister/entity/WellPartsRegister.java
|
UTF-8
| 12,035
| 1.882813
| 2
|
[] |
no_license
|
package com.yunda.jx.pjwz.wellpartsmanage.wellpartsregister.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.codehaus.jackson.annotate.JsonAutoDetect;
import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
import org.hibernate.annotations.GenericGenerator;
/**
* <li>标题: 机车检修管理信息系统
* <li>说明:wellPartsRegister实体类, 数据表:良好配件登记
* <li>创建人:程梅
* <li>创建日期:2015-10-13
* <li>修改人:
* <li>修改日期:
* <li>修改内容:
* <li>版权: Copyright (c) 2008 运达科技公司
* @author 测控部检修系统项目组
* @version 1.0
*/
@Entity
@Table(name="PJWZ_WELL_PARTS_REGISTER")
@JsonAutoDetect(fieldVisibility=Visibility.ANY,getterVisibility=Visibility.NONE)
public class WellPartsRegister implements java.io.Serializable{
/* 使用默认序列版本ID */
private static final long serialVersionUID = 1L;
public static final int ACCEPT_DEPT_TYPE_ORG = 1 ;//责任部门类型:机构
public static final int ACCEPT_DEPT_TYPE_WH = 2 ;//责任部门类型:库房
/** 单据类型 - 新购 */
public static final String SOURCE_NEW = "新购";
/** 单据类型 - 调入 */
public static final String SOURCE_INTO= "调入";
/* idx主键 */
@GenericGenerator(strategy="uuid", name = "uuid_id_generator")
@Id @GeneratedValue(generator="uuid_id_generator")
private String idx;
/* 责任部门ID */
@Column(name="ACCEPT_DEPT_ID")
private String acceptDeptId;
/* 责任部门序列(存储组织机构的orgseq字段) */
@Column(name="ACCEPT_DEPT_ORGSEQ")
private String acceptDeptOrgSeq;
/* 责任部门 */
@Column(name="ACCEPT_DEPT")
private String acceptDept;
/* 责任部门类型:1:机构;2:库房 */
@Column(name="ACCEPT_DEPT_Type")
private Integer acceptDeptType;
/* 接收日期 */
@Temporal(TemporalType.TIMESTAMP)
@Column(name="ACCEPT_TIME")
private java.util.Date acceptTime;
/* 接收人主键 */
@Column(name="TAKE_OVER_EMP_ID")
private Long takeOverEmpId;
/* 接收人 */
@Column(name="TAKE_OVER_EMP")
private String takeOverEmp;
/* 配件信息主键 */
@Column(name="PARTS_ACCOUNT_IDX")
private String partsAccountIdx;
/* 配件规格型号主键 */
@Column(name="PARTS_TYPE_IDX")
private String partsTypeIdx;
/* 配件名称 */
@Column(name="PARTS_NAME")
private String partsName;
/* 规格型号 */
@Column(name="SPECIFICATION_MODEL")
private String specificationModel;
/* 配件编号 */
@Column(name="PARTS_NO")
private String partsNo;
/* 配件铭牌号 */
@Column(name="nameplate_No")
private String nameplateNo;
/* 配件识别码 */
@Column(name="IDENTIFICATION_CODE")
private String identificationCode;
/* 生产厂主键 */
@Column(name="MADE_FACTORY_IDX")
private String madeFactoryIdx;
/* 生产厂名 */
@Column(name="MADE_FACTORY_NAME")
private String madeFactoryName;
/* 出厂日期 */
@Temporal(TemporalType.TIMESTAMP)
@Column(name="FACTORY_DATE")
private java.util.Date factoryDate;
/* 存放位置 */
@Column(name="LOCATION_NAME")
private String locationName;
/*详细配置 */
@Column(name="CONFIG_DETAIL")
private String configDetail;
/* 单据类型:(新、调入) */
private String source;
/* 单据状态 */
private String status;
/* 创建人名称 */
@Column(name="CREATOR_NAME")
private String creatorName;
/* 表示此条记录的状态:0为表示未删除;1表示删除 */
@Column(name="RECORD_STATUS")
private Integer recordStatus;
/* 站点标识,为了同步数据而使用 */
@Column(updatable=false)
private String siteID;
/* 创建人 */
@Column(updatable=false)
private Long creator;
/* 创建时间 */
@Temporal(TemporalType.TIMESTAMP)
@Column(name="CREATE_TIME",updatable=false)
private java.util.Date createTime;
/* 修改人 */
private Long updator;
/* 修改时间 */
@Temporal(TemporalType.TIMESTAMP)
@Column(name="UPDATE_TIME")
private java.util.Date updateTime;
/* 配件状态编码 */
@Column(name="Parts_Status")
private String partsStatus;
/* 配件状态名称 */
@Column(name="Parts_Status_Name")
private String partsStatusName;
public String getPartsStatus() {
return partsStatus;
}
public void setPartsStatus(String partsStatus) {
this.partsStatus = partsStatus;
}
public String getPartsStatusName() {
return partsStatusName;
}
public void setPartsStatusName(String partsStatusName) {
this.partsStatusName = partsStatusName;
}
/**
* @return String 获取接收部门主键
*/
public String getAcceptDeptId(){
return acceptDeptId;
}
/**
* @param acceptDeptId 设置接收部门主键
*/
public void setAcceptDeptId(String acceptDeptId) {
this.acceptDeptId = acceptDeptId;
}
/**
* @return String 获取接收部门序列
*/
public String getAcceptDeptOrgSeq(){
return acceptDeptOrgSeq;
}
/**
* @param acceptDeptOrgSeq 设置接收部门序列
*/
public void setAcceptDeptOrgSeq(String acceptDeptOrgSeq) {
this.acceptDeptOrgSeq = acceptDeptOrgSeq;
}
/**
* @return String 获取接收部门
*/
public String getAcceptDept(){
return acceptDept;
}
/**
* @param acceptDept 设置接收部门
*/
public void setAcceptDept(String acceptDept) {
this.acceptDept = acceptDept;
}
/**
* @return Integer 获取接收部门类型
*/
public Integer getAcceptDeptType(){
return acceptDeptType;
}
/**
* @param acceptDeptType 设置接收部门类型
*/
public void setAcceptDeptType(Integer acceptDeptType) {
this.acceptDeptType = acceptDeptType;
}
/**
* @return java.util.Date 获取接收日期
*/
public java.util.Date getAcceptTime(){
return acceptTime;
}
/**
* @param acceptTime 设置接收日期
*/
public void setAcceptTime(java.util.Date acceptTime) {
this.acceptTime = acceptTime;
}
/**
* @return Long 获取接收人主键
*/
public Long getTakeOverEmpId(){
return takeOverEmpId;
}
/**
* @param takeOverEmpId 设置接收人主键
*/
public void setTakeOverEmpId(Long takeOverEmpId) {
this.takeOverEmpId = takeOverEmpId;
}
/**
* @return String 获取接收人
*/
public String getTakeOverEmp(){
return takeOverEmp;
}
/**
* @param takeOverEmp 设置接收人
*/
public void setTakeOverEmp(String takeOverEmp) {
this.takeOverEmp = takeOverEmp;
}
/**
* @return String 获取配件信息主键
*/
public String getPartsAccountIdx(){
return partsAccountIdx;
}
/**
* @param partsAccountIdx 设置配件信息主键
*/
public void setPartsAccountIdx(String partsAccountIdx) {
this.partsAccountIdx = partsAccountIdx;
}
/**
* @return String 获取配件规格型号主键
*/
public String getPartsTypeIdx(){
return partsTypeIdx;
}
/**
* @param partsTypeIdx 设置配件规格型号主键
*/
public void setPartsTypeIdx(String partsTypeIdx) {
this.partsTypeIdx = partsTypeIdx;
}
/**
* @return String 获取配件名称
*/
public String getPartsName(){
return partsName;
}
/**
* @param partsName 设置配件名称
*/
public void setPartsName(String partsName) {
this.partsName = partsName;
}
/**
* @return String 获取规格型号
*/
public String getSpecificationModel(){
return specificationModel;
}
/**
* @param specificationModel 设置规格型号
*/
public void setSpecificationModel(String specificationModel) {
this.specificationModel = specificationModel;
}
/**
* @return String 获取配件编号
*/
public String getPartsNo(){
return partsNo;
}
/**
* @param partsNo 设置配件编号
*/
public void setPartsNo(String partsNo) {
this.partsNo = partsNo;
}
/**
* @return String 获取配件识别码
*/
public String getIdentificationCode(){
return identificationCode;
}
/**
* @param identificationCode 设置配件识别码
*/
public void setIdentificationCode(String identificationCode) {
this.identificationCode = identificationCode;
}
/**
* @return String 获取配件来源
*/
public String getSource(){
return source;
}
/**
* @param source 设置配件来源
*/
public void setSource(String source) {
this.source = source;
}
/**
* @return String 获取单据状态
*/
public String getStatus(){
return status;
}
/**
* @param status 设置单据状态
*/
public void setStatus(String status) {
this.status = status;
}
public String getConfigDetail() {
return configDetail;
}
public void setConfigDetail(String configDetail) {
this.configDetail = configDetail;
}
public String getCreatorName() {
return creatorName;
}
public void setCreatorName(String creatorName) {
this.creatorName = creatorName;
}
public java.util.Date getFactoryDate() {
return factoryDate;
}
public void setFactoryDate(java.util.Date factoryDate) {
this.factoryDate = factoryDate;
}
public String getLocationName() {
return locationName;
}
public void setLocationName(String locationName) {
this.locationName = locationName;
}
public String getMadeFactoryIdx() {
return madeFactoryIdx;
}
public void setMadeFactoryIdx(String madeFactoryIdx) {
this.madeFactoryIdx = madeFactoryIdx;
}
public String getMadeFactoryName() {
return madeFactoryName;
}
public void setMadeFactoryName(String madeFactoryName) {
this.madeFactoryName = madeFactoryName;
}
/**
* @return Integer 获取记录的状态
*/
public Integer getRecordStatus(){
return recordStatus;
}
/**
* @param recordStatus 设置记录的状态
*/
public void setRecordStatus(Integer recordStatus) {
this.recordStatus = recordStatus;
}
/**
* @return String 获取站点标识
*/
public String getSiteID(){
return siteID;
}
/**
* @param siteID 设置站点标识
*/
public void setSiteID(String siteID) {
this.siteID = siteID;
}
/**
* @return Long 获取创建人
*/
public Long getCreator(){
return creator;
}
/**
* @param creator 设置创建人
*/
public void setCreator(Long creator) {
this.creator = creator;
}
/**
* @return java.util.Date 获取创建时间
*/
public java.util.Date getCreateTime(){
return createTime;
}
/**
* @param createTime 设置创建时间
*/
public void setCreateTime(java.util.Date createTime) {
this.createTime = createTime;
}
/**
* @return Long 获取修改人
*/
public Long getUpdator(){
return updator;
}
/**
* @param updator 设置修改人
*/
public void setUpdator(Long updator) {
this.updator = updator;
}
/**
* @return java.util.Date 获取修改时间
*/
public java.util.Date getUpdateTime(){
return updateTime;
}
/**
* @param updateTime 设置修改时间
*/
public void setUpdateTime(java.util.Date updateTime) {
this.updateTime = updateTime;
}
/**
* @return String idx主键
*/
public String getIdx() {
return idx;
}
/**
* @param idx 设置idx主键
*/
public void setIdx(String idx) {
this.idx = idx;
}
public String getNameplateNo() {
return nameplateNo;
}
public void setNameplateNo(String nameplateNo) {
this.nameplateNo = nameplateNo;
}
}
| true
|
4b2595aaa3b03246fa069f55849cd78822374c8c
|
Java
|
lapavila/Java-Arduino-IoT
|
/Java/TemperatureClient/src/org/gujavasc/iot/cliente/mqtt/MqttPublisher.java
|
UTF-8
| 1,827
| 2.609375
| 3
|
[] |
no_license
|
package org.gujavasc.iot.cliente.mqtt;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.gujavasc.iot.cliente.util.PropertyUtils;
/**
*
* @author avila
*/
public class MqttPublisher implements Runnable {
private String messageContent;
String topic;
int qos = 2;
String broker;
String clientId = "JavaTemperature";
public MqttPublisher() {
this.broker = PropertyUtils.getPropertyString("mqtt.broker");
this.topic = PropertyUtils.getPropertyString("mqtt.topic.publish");
}
public void sendMessage(String messageContent) {
this.messageContent = messageContent;
(new Thread(this)).start();
}
@Override
public void run() {
MemoryPersistence persistence = new MemoryPersistence();
try {
MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setCleanSession(true);
sampleClient.connect(connOpts);
MqttMessage message = new MqttMessage(messageContent.getBytes());
message.setQos(qos);
sampleClient.publish(topic, message);
sampleClient.disconnect();
System.out.println("Temperature sento to " + broker);
} catch (MqttException me) {
System.out.println("reason " + me.getReasonCode());
System.out.println("msg " + me.getMessage());
System.out.println("loc " + me.getLocalizedMessage());
System.out.println("excep " + me);
}
}
}
| true
|
d7ee58b4ba54a25dca59e4775c572dd430e3a7a1
|
Java
|
herolj/fct
|
/FinanceService/FinanceService.Data/src/main/java/com/fct/finance/data/Entity/MemberAccountHistory.java
|
UTF-8
| 1,374
| 2.0625
| 2
|
[] |
no_license
|
package com.fct.finance.data.entity;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
import javax.persistence.*;
import java.math.BigDecimal;
import java.util.Date;
/**
* Created by jon on 2017/4/7.
*/
@Entity
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class MemberAccountHistory {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
/// <summary>
/// 用户Id
/// </summary>
private Integer memberId;
/// <summary>
/// 变动金额
/// </summary>
private BigDecimal amount;
/// <summary>
/// 余额
/// </summary>
private BigDecimal balanceAmount;
/// <summary>
/// 变动积分
/// </summary>
private Integer points;
/// <summary>
/// 当前结余积分
/// </summary>
private Integer balancePoints;
/// <summary>
/// 行为类型(充值、消费、结算返佣、退款、提现)
/// </summary>
private String tradeType;
/// <summary>
/// 相关数据主键
/// </summary>
private String tradeId;
/// <summary>
/// 备注
/// </summary>
private String remark;
/// <summary>
/// 行为{0:支出,1:收入}
/// </summary>
private Integer behaviorType;
/// <summary>
/// 创建时间
/// </summary>
private Date createTime;
}
| true
|
75adb84da74e3f8bd9bd3642af6cb49aa4aa0e37
|
Java
|
analicefs/LearningJava
|
/AulaJava/src/System/out/OOConcepts.java
|
ISO-8859-1
| 688
| 3.125
| 3
|
[] |
no_license
|
package System.out;
import System.out.PersonComGeteSet;
public class OOConcepts {
public static void main(String[] args) {
// TODO Auto-generated method stub
String a = "motorola";
String b = new String ("motorola");
String c = "igual";
if(a==b) {
System.out.println("Igual");
}else {
System.out.println("diferente");// Est olhando o ponteiro da memria
}
if(a.equals(c)) {
System.out.println("so iguais");
}
PersonComGeteSet p = new PersonComGeteSet();
p.setNome("Ana");
p.setCpf("0102028");
p.setIdade(23);
System.out.println(p.getNome());
System.out.println(p.getCpf());
System.out.println(p.getIdade());
}
}
| true
|
6870cc1c9cb11629c91617b44a6a46638d2b6b94
|
Java
|
marcushojww/SingHealthAuditApp
|
/backend/src/main/java/com/c2g4/SingHealthWebApp/Admin/Controllers/ManagementController.java
|
UTF-8
| 285
| 1.546875
| 2
|
[] |
no_license
|
package com.c2g4.SingHealthWebApp.Admin.Controllers;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RestController;
@CrossOrigin(origins = { "http://localhost:3000" })
@RestController
public class ManagementController {
}
| true
|
c94819e3f0d5143358f7037e2ab1260060462b2d
|
Java
|
DangHuynhPT/App_phone_store_manager_Nhom_3
|
/app/src/main/java/com/example/app_phone_store_manager_nhom_3/utilities/Utilities.java
|
UTF-8
| 603
| 2.625
| 3
|
[] |
no_license
|
package com.example.app_phone_store_manager_nhom_3.utilities;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Utilities {
private static final String DATE_PATTREN = "yyyy-MM-dd";
private static DateFormat dateFormat = new SimpleDateFormat(DATE_PATTREN);
public static Date stringToDate(String strDate) {
try {
return dateFormat.parse(strDate);
} catch (Exception e) {
return null;
}
}
public static String dateToString(Date date) {
return dateFormat.format(date);
}
}
| true
|
f87f858c242ebffaa10655107bdc1dc9c0fd1cec
|
Java
|
Panghu98/project-management-system
|
/src/main/java/group/uchain/project/util/SaltUtil.java
|
UTF-8
| 432
| 2.328125
| 2
|
[] |
no_license
|
package group.uchain.project.util;
import java.util.UUID;
/**
* @author project
* @Title: SaltUtil
* @ProjectName oil-supply-chain
* @date 19-3-29 上午8:18
*/
public class SaltUtil {
/**
* 生成长UUID
*/
private static String randomUUID() {
return UUID.randomUUID().toString().replace("-", "");
}
public static String getSalt(){
return randomUUID().substring(12,20);
}
}
| true
|
2887ba5ff4f625aca873571cc2e49c66c220e016
|
Java
|
asaake/comety
|
/comety-chat-example/src/main/java/app/ChatApp.java
|
UTF-8
| 221
| 1.53125
| 2
|
[] |
no_license
|
package app;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
/**
* チャットシステムアプリケーション
*/
@ApplicationPath("/jaxrs")
public class ChatApp extends Application {
}
| true
|
b42ade2962052468c2fdf8c123010d55db856323
|
Java
|
bamaboyAsh/30JavaPrograms
|
/src/onlyArrays/RemoveSpecificElementFromAnArray.java
|
UTF-8
| 761
| 3.75
| 4
|
[] |
no_license
|
package onlyArrays;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class RemoveSpecificElementFromAnArray
{
public static void main(String[] args)
{
int [] array= {1,2,3,4,5,6,7,8,9};
Scanner sc= new Scanner(System.in);
System.out.println("Enter an element you want to delete");
int num= sc.nextInt();
ArrayList<Integer> arrayList = new ArrayList<Integer>();
for(int i=0; i<array.length;i++)
{
int convert = array[i];
arrayList.add(convert);
}
System.out.println("");
System.out.println(arrayList);
for(int i=0; i<array.length; i++)
{
if(num==array[i])
{
arrayList.remove(i);
}
}
System.out.println("");
System.out.println(arrayList);
}
}
| true
|
6584287d3044f0b07646e4881c0d9db58a48e6d7
|
Java
|
sanuri92/Java-_-Project-
|
/src/foodcityresidencecomplex/Views/RoomRegister.java
|
UTF-8
| 14,873
| 2.1875
| 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 foodcityresidencecomplex.Views;
import javax.swing.JOptionPane;
/**
*
* @author Sanuri Isara
*/
public class RoomRegister extends javax.swing.JFrame {
/**
* Creates new form RoomRegister
*/
public RoomRegister() {
initComponents();
}
public String itemRtn(){
String s1=txtFloor.getText();
int count=cmbFloor.getItemCount();
String s = null;
for (int i = 0; i < count; i++) {
s=cmbFloor.getItemAt(i).toString();
}
return s;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
txtrid = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
txtFloor = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
txtAppartmt = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
txtRoomNo = new javax.swing.JTextField();
btnadd = new javax.swing.JButton();
btnupdate = new javax.swing.JButton();
btndelete = new javax.swing.JButton();
btnsearch = new javax.swing.JButton();
btnhome = new javax.swing.JButton();
btnexit = new javax.swing.JButton();
jLabel7 = new javax.swing.JLabel();
txtBeds = new javax.swing.JTextField();
cmbFloor = new javax.swing.JComboBox();
cmbApartment = new javax.swing.JComboBox();
cmdRoomNo = new javax.swing.JComboBox();
cmbNoBeds = new javax.swing.JComboBox();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
AddBed = new javax.swing.JButton();
AddFloor = new javax.swing.JButton();
addAppart = new javax.swing.JButton();
AddRoom = new javax.swing.JButton();
jLabel12 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel1.setFont(new java.awt.Font("Tekton Pro", 3, 36)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 51, 51));
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("Room Registration");
jLabel1.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 40, 460, 50));
jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/foodcityresidencecomplex/Views/src/System-Home-icon2.png"))); // NOI18N
getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, -1, 125));
jLabel3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel3.setText("Room ID");
getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(68, 153, 163, 27));
txtrid.setEditable(false);
txtrid.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
getContentPane().add(txtrid, new org.netbeans.lib.awtextra.AbsoluteConstraints(260, 150, 240, 27));
jLabel4.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel4.setText("Add New No of Beds");
getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(510, 340, 130, 27));
getContentPane().add(txtFloor, new org.netbeans.lib.awtextra.AbsoluteConstraints(650, 190, 130, 27));
jLabel5.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel5.setText("Apartment");
getContentPane().add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(68, 243, 163, 27));
getContentPane().add(txtAppartmt, new org.netbeans.lib.awtextra.AbsoluteConstraints(650, 240, 130, 27));
jLabel6.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel6.setText("Room No");
getContentPane().add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 290, 163, 20));
getContentPane().add(txtRoomNo, new org.netbeans.lib.awtextra.AbsoluteConstraints(650, 290, 130, 27));
btnadd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/foodcityresidencecomplex/Views/src/download-database-icon.png"))); // NOI18N
getContentPane().add(btnadd, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 430, 80, 80));
btnupdate.setIcon(new javax.swing.ImageIcon(getClass().getResource("/foodcityresidencecomplex/Views/src/Icons_respaldo.png"))); // NOI18N
getContentPane().add(btnupdate, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 430, 80, 80));
btndelete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/foodcityresidencecomplex/Views/src/remove-from-database-icon.png"))); // NOI18N
getContentPane().add(btndelete, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 430, 80, 80));
btnsearch.setIcon(new javax.swing.ImageIcon(getClass().getResource("/foodcityresidencecomplex/Views/src/user-database-icon-search.png"))); // NOI18N
getContentPane().add(btnsearch, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 430, 80, 80));
btnhome.setIcon(new javax.swing.ImageIcon("C:\\Users\\Sanuri Isara\\Documents\\NetBeansProjects\\FoodCityResidenceComplex\\Resourses\\ICON\\System-Home-icon - Copy - Copy.png")); // NOI18N
getContentPane().add(btnhome, new org.netbeans.lib.awtextra.AbsoluteConstraints(610, 430, 80, 80));
btnexit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/foodcityresidencecomplex/Views/src/exit-icon-2.png"))); // NOI18N
getContentPane().add(btnexit, new org.netbeans.lib.awtextra.AbsoluteConstraints(740, 430, 80, 80));
jLabel7.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel7.setText("No of Total Beads");
getContentPane().add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 340, 163, 27));
getContentPane().add(txtBeds, new org.netbeans.lib.awtextra.AbsoluteConstraints(650, 340, 130, 27));
cmbFloor.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
cmbFloor.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "2", "3", "4", "5", "6" }));
getContentPane().add(cmbFloor, new org.netbeans.lib.awtextra.AbsoluteConstraints(260, 190, 240, 29));
cmbApartment.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
cmbApartment.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "A", "B", "C", "D" }));
getContentPane().add(cmbApartment, new org.netbeans.lib.awtextra.AbsoluteConstraints(260, 240, 240, 29));
cmdRoomNo.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
cmdRoomNo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16" }));
cmdRoomNo.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusLost(java.awt.event.FocusEvent evt) {
cmdRoomNoFocusLost(evt);
}
});
getContentPane().add(cmdRoomNo, new org.netbeans.lib.awtextra.AbsoluteConstraints(260, 290, 240, 29));
cmbNoBeds.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
cmbNoBeds.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4" }));
getContentPane().add(cmbNoBeds, new org.netbeans.lib.awtextra.AbsoluteConstraints(260, 340, 240, 29));
jLabel8.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel8.setText("Floor");
getContentPane().add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(68, 198, 163, 27));
jLabel9.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel9.setText("Add New Floor");
getContentPane().add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(510, 190, 130, 27));
jLabel10.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel10.setText("Add New Apartment");
getContentPane().add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(510, 240, 130, 27));
jLabel11.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel11.setText("Add New RoomNo");
getContentPane().add(jLabel11, new org.netbeans.lib.awtextra.AbsoluteConstraints(510, 290, 130, 27));
AddBed.setIcon(new javax.swing.ImageIcon(getClass().getResource("/foodcityresidencecomplex/Views/src/698913-icon-81-document-add-1282.png"))); // NOI18N
getContentPane().add(AddBed, new org.netbeans.lib.awtextra.AbsoluteConstraints(800, 340, 30, 30));
AddFloor.setIcon(new javax.swing.ImageIcon(getClass().getResource("/foodcityresidencecomplex/Views/src/698913-icon-81-document-add-1282.png"))); // NOI18N
AddFloor.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AddFloorActionPerformed(evt);
}
});
getContentPane().add(AddFloor, new org.netbeans.lib.awtextra.AbsoluteConstraints(800, 190, 30, 30));
addAppart.setIcon(new javax.swing.ImageIcon(getClass().getResource("/foodcityresidencecomplex/Views/src/698913-icon-81-document-add-1282.png"))); // NOI18N
getContentPane().add(addAppart, new org.netbeans.lib.awtextra.AbsoluteConstraints(800, 240, 30, 30));
AddRoom.setIcon(new javax.swing.ImageIcon(getClass().getResource("/foodcityresidencecomplex/Views/src/698913-icon-81-document-add-1282.png"))); // NOI18N
getContentPane().add(AddRoom, new org.netbeans.lib.awtextra.AbsoluteConstraints(800, 290, 30, 30));
jLabel12.setIcon(new javax.swing.ImageIcon("C:\\Users\\Sanuri Isara\\Documents\\NetBeansProjects\\FoodCityResidenceComplex\\Resourses\\ICON\\Light-Pink-Background.jpg")); // NOI18N
getContentPane().add(jLabel12, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 860, 540));
pack();
}// </editor-fold>//GEN-END:initComponents
private void cmdRoomNoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_cmdRoomNoFocusLost
try {
String floor=cmbFloor.getSelectedItem().toString();
String appartment=cmbApartment.getSelectedItem().toString();
String roomno=cmdRoomNo.getSelectedItem().toString();
txtrid.setText(floor+""+appartment+"-"+roomno);
} catch (Exception e) {
e.printStackTrace();
}
}//GEN-LAST:event_cmdRoomNoFocusLost
private void AddFloorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddFloorActionPerformed
if (s.equals(s1)) {
JOptionPane.showMessageDialog(RoomRegister.this,"That Floor no is already exsist");
}else{
cmbFloor.addItem(s1);
}
}//GEN-LAST:event_AddFloorActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(RoomRegister.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(RoomRegister.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(RoomRegister.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(RoomRegister.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new RoomRegister().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton AddBed;
private javax.swing.JButton AddFloor;
private javax.swing.JButton AddRoom;
private javax.swing.JButton addAppart;
private javax.swing.JButton btnadd;
private javax.swing.JButton btndelete;
private javax.swing.JButton btnexit;
private javax.swing.JButton btnhome;
private javax.swing.JButton btnsearch;
private javax.swing.JButton btnupdate;
private javax.swing.JComboBox cmbApartment;
private javax.swing.JComboBox cmbFloor;
private javax.swing.JComboBox cmbNoBeds;
private javax.swing.JComboBox cmdRoomNo;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JTextField txtAppartmt;
private javax.swing.JTextField txtBeds;
private javax.swing.JTextField txtFloor;
private javax.swing.JTextField txtRoomNo;
private javax.swing.JTextField txtrid;
// End of variables declaration//GEN-END:variables
}
| true
|
da9f19a8f81811c39e4b5428e0bb1f7b3cda9b5a
|
Java
|
ejoftheweb/boox
|
/Boox/src/uk/co/platosys/boox/cash/Cash.java
|
UTF-8
| 14,733
| 2.453125
| 2
|
[] |
no_license
|
package uk.co.platosys.boox.cash;
import java.util.ArrayList;
import java.util.List;
import uk.co.platosys.boox.core.Account;
import uk.co.platosys.boox.core.Clerk;
import uk.co.platosys.boox.core.Enterprise;
import uk.co.platosys.boox.core.Ledger;
import uk.co.platosys.boox.core.exceptions.BooxException;
import uk.co.platosys.boox.core.exceptions.PermissionsException;
import uk.co.platosys.boox.money.Money;
import uk.co.platosys.db.ColumnNotFoundException;
import uk.co.platosys.db.PlatosysDBException;
import uk.co.platosys.db.Row;
import uk.co.platosys.db.RowNotFoundException;
import uk.co.platosys.db.Table;
import uk.co.platosys.db.jdbc.JDBCRow;
import uk.co.platosys.db.jdbc.JDBCTable;
import uk.co.platosys.util.Logger;
import uk.co.platosys.util.ShortHash;
/**
* The Cash class models devices and places used to store and handle cash.
* In particular it is for cash-registers, but a petty-cash tin is also
* modeled by an instance of this class.
*
* Note that on the sales side, each instance can handle only one tax-band. For
* multi-taxbands, we handle this recursively by means of child instances of Cash
*
* @author edward
*
* <h2>Handling cash under SDE</h2>
* <dl>
* <dt>Sale:</dt>
* <dd>Debit register, credit Sales</dd>
* <dt>Departments</dt>
* <dd>Debit register, credit department</dd>
* <dd>Debit department, credit deptSales untaxed amount</dd>
* <dd>Debit department, credit outputVat tax amount</dd>
*
* <dt>Paid-Out</dt>
* <dd>Debit purchases, credit register.</dd>
*
* <dt>Shorts</dt>
* <dd>Debit difference, credit register</dd>
* (charged to staff? -> check legality?)
* <dd>Debit cashier, credit difference</dd>
*
* <dt>Overs</dt>
* <dd> Debit register, credit Difference</dd>
*
*
*
* <dt>Banking </dt>
* (cash goes from register, to bank)
* <dd>Debit Bank, credit register.</dd>
*
* <dt>Taxed Sales:</dt>
* <dd> Debit register, credit Sales untax amount</dd>
* <dd>Debit register, credit outputVAT tax amount</dd>
*
* <dt>Paid-Out transferred to petty cash:</dt>
* <dd> Debit petty-cash, credit Register</dd>
* <dd>Debit purchases, credit petty-cash</dd>
*
* <dt>Correcting/reversing over-ring</dt>
* <dd> if not done using machine "void" function
* Debit Sales, credit Register</dd>
*
* <dt>Credit/Debit card sales</dt>
* <dd>Debit merchant, credit register</dd>
* <dd>Debit finance-charge, credit merchant transaction fee.</dd>
* </dl>
*
* <h2>A Petty Cash Tin</h2>
* <dt>Top-up with cash from bank</dt>
* <dd> Debit petty-cash, credit bank</dd>
*
* <dt>For each purchase</dt>
* <dd>Debit purchases, credit petty-cash</dd>
*
* <h2>Multi-department registers</h2>
* Most modern cash-registers have multiple departments. This is useful, say, for distinguishing taxed and untaxed sales.
* Even the smallest typically has eight. The sales for each department are credited to different sales accounts.
*
* We manage this recursively. For the root machine, the actual machine, we record the number of departments.
* A separate instance of Cash is created for each department, each with its own sales account and tax-band. It records its parent column.
* A null in the parent column indicates that the machine has no parent, therefore is a parent machine.
*
*
*/
public class Cash {
//the registers table
public static final String TABLE_NAME="bx_cash";
public static final String NAME_COLNAME="name";
public static final String SYSNAME_COLNAME="sysname";
public static final String LEDGER_COLNAME="ledger";
public static final String ACCOUNT_COLNAME="account";
public static final String DIFF_ACCOUNT_COLNAME="diff_account";
public static final String PO_ACCOUNT_COLNAME="po_account";
public static final String SALES_ACCOUNT_COLNAME="sales_account";
public static final String PARENT_COLNAME="parent";
public static final String DEPTS_COLNAME="depts";
public static final String TAXBAND_COLNAME="taxband";
public static final String MODEL_COLNAME="model";
public static final String REPORTNO_COLNAME="report";
public static final String GT_COLNAME="runningtotal";
public static final String FLOAT_COLNAME="float";
public static final String SYSNAME_PREFIX="h";//configurable
public static final String CASH_LEDGER_NAME="Root:XBX:Current:Assets:Cash:Registers"; //make configurable from props file?
public static final String DIFF_ACCOUNT_NAME="bx_Difference"; //make configurable from props file?
public static final String PO_ACCOUNT_NAME="bx_PaidOuts"; //make configurable from props file?
private static Logger logger = Logger.getLogger("boox");
Table table;
String name;
String model;
String sysname;
Ledger ledger;
Account account;
Account diffAccount;
Account poAccount;
Account salesAccount;
int reportNo;
int depts;
String parentSysname;
int taxband;
Money gt;
Money floatbal;
Cash[] children;
private Cash(Enterprise enterprise, Clerk clerk, String sysname) throws PlatosysDBException {
table=JDBCTable.getTable(enterprise.getDatabaseName(), TABLE_NAME, SYSNAME_COLNAME);
Row row;
try {
row = getRow(enterprise,sysname);
this.name=row.getString(NAME_COLNAME);
this.sysname=row.getString(SYSNAME_COLNAME);
this.ledger=Ledger.getLedger(enterprise, row.getString(LEDGER_COLNAME));
this.account=Account.getAccount(enterprise, row.getString(ACCOUNT_COLNAME), clerk);
this.diffAccount=Account.getAccount(enterprise, row.getString(DIFF_ACCOUNT_COLNAME), clerk);
this.poAccount=Account.getAccount(enterprise, row.getString(PO_ACCOUNT_COLNAME), clerk);
this.salesAccount=Account.getAccount(enterprise, row.getString(SALES_ACCOUNT_COLNAME), clerk);
this.reportNo=row.getInt(REPORTNO_COLNAME);
this.depts=row.getInt(DEPTS_COLNAME);
this.taxband=row.getInt(TAXBAND_COLNAME);
this.gt=new Money(enterprise.getDefaultCurrency(), row.getBigDecimal(GT_COLNAME));
this.floatbal=new Money(enterprise.getDefaultCurrency(),row.getBigDecimal(FLOAT_COLNAME));
} catch (Exception e) {
// TODO Auto-generated catch block
logger.log("error:",e);
}
}
private Cash(Enterprise enterprise, Clerk clerk, Row row) throws ClassCastException, PermissionsException, ColumnNotFoundException, PlatosysDBException{
table=JDBCTable.getTable(enterprise.getDatabaseName(), TABLE_NAME, SYSNAME_COLNAME);
this.name=row.getString(NAME_COLNAME);
this.sysname=row.getString(SYSNAME_COLNAME);
this.ledger=Ledger.getLedger(enterprise, row.getString(LEDGER_COLNAME));
this.account=Account.getAccount(enterprise, row.getString(ACCOUNT_COLNAME), clerk);
this.diffAccount=Account.getAccount(enterprise, row.getString(DIFF_ACCOUNT_COLNAME), clerk);
this.reportNo=row.getInt(REPORTNO_COLNAME);
this.gt=new Money(enterprise.getDefaultCurrency(), row.getBigDecimal(GT_COLNAME));
this.floatbal=new Money(enterprise.getDefaultCurrency(),row.getBigDecimal(FLOAT_COLNAME));
}
/**
* Use this method to set up a machine on the system for the first time
* @param enterprise
* @param clerk
* @param cashmcsLedger
* @param name
* @return
* @throws PlatosysDBException
* @throws PermissionsException
* @throws BooxException
*/
public static Cash addCashmc(Enterprise enterprise, Clerk clerk, Ledger cashmcsLedger, String name) throws PlatosysDBException, PermissionsException, BooxException{
JDBCTable cashmcsTable=null;
if(!JDBCTable.tableExists(enterprise.getDatabaseName(), TABLE_NAME)){
logger.log("Cash: creating cashmcsTable");
try {
cashmcsTable = JDBCTable.createTable(enterprise.getDatabaseName(), TABLE_NAME, SYSNAME_COLNAME, Table.TEXT_COLUMN);
cashmcsTable.addColumn(NAME_COLNAME, Table.TEXT_COLUMN);
cashmcsTable.addColumn(MODEL_COLNAME, Table.TEXT_COLUMN);
cashmcsTable.addColumn(LEDGER_COLNAME, Table.TEXT_COLUMN);
cashmcsTable.addColumn(ACCOUNT_COLNAME, Table.TEXT_COLUMN);
cashmcsTable.addColumn(DIFF_ACCOUNT_COLNAME, Table.TEXT_COLUMN);
cashmcsTable.addColumn(PO_ACCOUNT_COLNAME, Table.TEXT_COLUMN);
cashmcsTable.addColumn(SALES_ACCOUNT_COLNAME, Table.TEXT_COLUMN);
cashmcsTable.addColumn(DEPTS_COLNAME, Table.INTEGER_COLUMN);//not sure we actually need this?
cashmcsTable.addColumn(PARENT_COLNAME, Table.TEXT_COLUMN);
cashmcsTable.addColumn(REPORTNO_COLNAME, Table.INTEGER_COLUMN);
cashmcsTable.addColumn(GT_COLNAME, Table.DECIMAL_COLUMN);
cashmcsTable.addColumn(FLOAT_COLNAME, Table.DECIMAL_COLUMN);
} catch (PlatosysDBException e) {
logger.log("Cash.addCashMc: exception thrown creating cashmc table", e);
throw new PlatosysDBException ("problem creating cashmc", e);
}
}else{
logger.log("cash: mccs table exists, opening it");
cashmcsTable=JDBCTable.getTable(enterprise.getDatabaseName(), TABLE_NAME, SYSNAME_COLNAME);
}
//name: should be unique.
if(cashmcsTable.rowExists(NAME_COLNAME, name)){
logger.log("Cash: machine called "+name+" already exists");
//then a customer of this name already exists so we return it
JDBCRow row;
try {
row = cashmcsTable.getRow(NAME_COLNAME, name);
} catch (RowNotFoundException e) {
logger.log("Customer.CC: RNF exception thrown", e);
//eh? the row exists but exception thrown??
throw new PlatosysDBException("Faulty CashMc Database: machine row not found", e);
}
try {
return new Cash(enterprise, clerk, row.getString(SYSNAME_COLNAME));
} catch (Exception e) {
logger.log("exception thrown", e);
//col not found exception? Table is buggad.
throw new PlatosysDBException("CashMc Database Fault: sysname col not found", e);
}
}else{
//
String sysname=SYSNAME_PREFIX+ShortHash.hash(name+enterprise.getName());
cashmcsTable.addRow(SYSNAME_COLNAME, sysname);
cashmcsTable.amend(sysname, NAME_COLNAME, name);
//machine needs a Ledger:
Ledger ledger = Ledger.createLedger(enterprise, sysname, cashmcsLedger, enterprise.getDefaultCurrency(), clerk, true);
cashmcsTable.amend(sysname, LEDGER_COLNAME, ledger.getFullName());
//And an Account:
Account account = Account.createAccount(enterprise, sysname, clerk, ledger, enterprise.getDefaultCurrency(), name, true);
cashmcsTable.amend(sysname, ACCOUNT_COLNAME, account.getSysname());
//And a Difference Account:
Account diffAccount = Account.createAccount(enterprise, sysname, clerk, ledger, enterprise.getDefaultCurrency(), DIFF_ACCOUNT_NAME, false);
cashmcsTable.amend(sysname,DIFF_ACCOUNT_COLNAME, diffAccount.getSysname());
//And a paid-outs Account:
Account poAccount = Account.createAccount(enterprise, sysname, clerk, ledger, enterprise.getDefaultCurrency(), PO_ACCOUNT_NAME, false);
cashmcsTable.amend(sysname,PO_ACCOUNT_COLNAME, poAccount.getSysname());
Cash cash = new Cash(enterprise, clerk, sysname);
logger.log("Ccash: created cashmc"+cash.getName());
return cash;
}
}
/**
* Use this method to retrieve an instance of Cash
* @param enterprise
* @param clerk
* @param sysname
* @return
* @throws PlatosysDBException
*/
public static Cash getCash(Enterprise enterprise, Clerk clerk, String sysname) throws PlatosysDBException{
return new Cash(enterprise, clerk, sysname);
}
/**
* for multi-department machines, i.e. most
* @return
* @throws PlatosysDBException
* @throws ColumnNotFoundException
* @throws PermissionsException
* @throws ClassCastException
*/
public ArrayList<Cash> getChildren(Enterprise enterprise, Clerk clerk) throws ClassCastException, PermissionsException, ColumnNotFoundException, PlatosysDBException{
ArrayList<Cash> children=new ArrayList<Cash>();
if (depts==0){
children.add(this);
}else{
List<Row> rows = table.getRows(PARENT_COLNAME, sysname);
for(Row row:rows){
children.add(new Cash(enterprise, clerk, row));
}
}
return children;
}
/**
* Add a sub-department to this Cash
* @param name
* @param taxBand
* @return
*/
public Cash addDept(String name, int taxBand){
return null;
}
public String getName(){
return name;
}
static Row getRow(Enterprise enterprise, String sysname)throws PlatosysDBException, RowNotFoundException{
JDBCTable cashmcsTable=null;
cashmcsTable=JDBCTable.getTable(enterprise.getDatabaseName(), TABLE_NAME, SYSNAME_COLNAME);
return cashmcsTable.getRow(sysname);
}
static List <Row> getRows(Enterprise enterprise) throws PlatosysDBException{
JDBCTable cashmcsTable=null;
cashmcsTable=JDBCTable.getTable(enterprise.getDatabaseName(), TABLE_NAME, SYSNAME_COLNAME);
return cashmcsTable.getRows();
}
public static List<Cash> getCashes(Enterprise enterprise, Clerk clerk) throws PlatosysDBException, ClassCastException, PermissionsException, ColumnNotFoundException{
List<Row> rows = getRows(enterprise);
ArrayList<Cash> cashes=new ArrayList<Cash>();
for(Row row:rows){
if (row.getString(PARENT_COLNAME)==null){
cashes.add(new Cash(enterprise, clerk, row));
}
}
return cashes;
}
public String getSysname() {
return sysname;
}
public void setSysname(String sysname) {
this.sysname = sysname;
}
public Ledger getLedger() {
return ledger;
}
public void setLedger(Ledger ledger) {
try{
table.amend(sysname, LEDGER_COLNAME, ledger.getFullName());
this.ledger = ledger;
}catch(Exception x){
logger.log("CashSL problem", x);
}
}
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
try{
table.amend(sysname, ACCOUNT_COLNAME, account.getSysname());
this.account = account;
}catch(Exception x){
logger.log("CashSA problem", x);
}
}
public int getReportNo() {
return reportNo;
}
public void setReportNo(int reportNo) {
try{
table.amend(sysname, REPORTNO_COLNAME, reportNo);
this.reportNo = reportNo;
}catch(Exception x){
logger.log("CashSRN problem", x);
}
}
public Money getGt() {
return gt;
}
public void setGt(Money gt) {
try{
table.amend(sysname, GT_COLNAME, gt.getAmount());
this.gt = gt;
}catch(Exception x){
logger.log("CashSGT problem", x);
}
}
public Money getFloatbal() {
return floatbal;
}
public void setFloatbal(Money floatbal) {
try{
table.amend(sysname, FLOAT_COLNAME, floatbal.getAmount());
this.floatbal =floatbal;
}catch(Exception x){
logger.log("CashSFB problem", x);
}
}
public void setName(String name) {
this.name = name;
}
public String getModel() {
return model;
}
public void setModel(String model) {
try{
table.amend(sysname, MODEL_COLNAME, model);
this.model = model;
}catch(Exception x){
logger.log("CashSM problem", x);
}
}
}
| true
|
3903baf8a4c376f1c3580787b2917b3f3dc238a9
|
Java
|
saskelevich/it-academy
|
/src/main/java/by/itacademy/java/yaskelevich/classroom/lessons8/PassengerCar.java
|
UTF-8
| 189
| 2.25
| 2
|
[] |
no_license
|
package by.itacademy.java.yaskelevich.classroom.lessons8;
public class PassengerCar extends Car {
@Override
public void move() {
System.out.println("i move fast");
}
}
| true
|
b2ce3b41375097885ae40c6e4af8ee564c532cae
|
Java
|
Arnaud-Nauwynck/avro
|
/lang/java/avro/src/test/java/org/apache/avro/TestDataFileAppend.java
|
UTF-8
| 4,714
| 2.078125
| 2
|
[
"BSD-3-Clause",
"Zlib",
"GPL-1.0-or-later",
"FSFAP",
"MIT",
"LicenseRef-scancode-other-permissive",
"zlib-acknowledgement",
"GPL-2.0-only",
"BSL-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-generic-cla",
"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
*
* https://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.avro;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import org.apache.avro.file.CodecFactory;
import org.apache.avro.file.DataFileReader;
import org.apache.avro.file.DataFileStream.Header;
import org.apache.avro.file.DataFileWriter;
import org.apache.avro.generic.GenericDatumReader;
import org.apache.avro.generic.GenericDatumWriter;
import org.apache.avro.util.RandomData;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
public class TestDataFileAppend {
@Rule
public TemporaryFolder DIR = new TemporaryFolder();
private static final String SCHEMA_JSON = "{\"type\": \"record\", \"name\": \"Test\", \"fields\": ["
+ "{\"name\":\"stringField\", \"type\":\"string\"}," + "{\"name\":\"longField\", \"type\":\"long\"}]}";
private static final Schema SCHEMA = new Schema.Parser().parse(SCHEMA_JSON);
private static final long SEED = System.currentTimeMillis();
private static final int COUNT = Integer.parseInt(System.getProperty("test.count", "200"));
private static final boolean VALIDATE = !"false".equals(System.getProperty("test.validate", "true"));
/*
*
*/
@Test
public void testAppendTo() throws Exception {
File file = new File(DIR.getRoot().getPath(), "testAppend.avro");
Iterator<Object> datumGenerator = new RandomData(SCHEMA, COUNT, SEED).iterator();
// initialize file with COUNT rows
try (DataFileWriter<Object> writer = new DataFileWriter<>(new GenericDatumWriter<>()).setSyncInterval(100)) {
writer.setCodec(CodecFactory.nullCodec());
writer.create(SCHEMA, file);
for (int i = 0; i < COUNT; i++) {
Object datum = datumGenerator.next();
writer.append(datum);
if (i % (COUNT / 3) == 0)
writer.sync(); // force some syncs mid-file
}
}
checkGenericRead(file, COUNT);
// read Header from file
Header header;
{
DataFileReader<Object> reader = new DataFileReader<>(file, new GenericDatumReader<>());
header = reader.getHeader();
reader.close();
}
int repeatAppend = 2;
for (int repeat = 0; repeat < repeatAppend; repeat++) {
// append to in-memory buffer next COUNT rows
ByteArrayOutputStream bufferOut = new ByteArrayOutputStream();
try (DataFileWriter<Object> writer = new DataFileWriter<>(new GenericDatumWriter<>()).setSyncInterval(100)) {
writer.setCodec(CodecFactory.nullCodec());
writer.appendTo(header, bufferOut);
for (int i = 0; i < COUNT; i++) {
Object datum = datumGenerator.next();
writer.append(datum);
if (i % (COUNT / 3) == 0)
writer.sync(); // force some syncs mid-file
}
}
bufferOut.close();
byte[] serializedBytes = bufferOut.toByteArray();
// append buffer to file (emulate a remote file append)
try (OutputStream appendTo = new FileOutputStream(file, true)) {
appendTo.write(serializedBytes);
}
}
// check file with appended data
checkGenericRead(file, COUNT + repeatAppend * COUNT);
}
private void checkGenericRead(File file, int expectedCount) throws IOException {
Iterator<Object> datumGenerator = new RandomData(SCHEMA, COUNT, SEED).iterator();
try (DataFileReader<Object> reader = new DataFileReader<>(file, new GenericDatumReader<>())) {
Object datum = null;
for (int i = 0; i < expectedCount; i++) {
datum = reader.next(datum);
if (VALIDATE) {
Object expected = datumGenerator.next();
assertEquals(expected, datum);
}
}
if (reader.hasNext()) {
Assert.fail("should have no more rows");
}
}
}
}
| true
|
c370a7b9cfebdca21f80e338f7a9d35ab9dbc0c2
|
Java
|
CodeRockerzz/DockerApp
|
/src/main/java/com/example/demo/service/TestService.java
|
UTF-8
| 164
| 1.742188
| 2
|
[] |
no_license
|
package com.example.demo.service;
import java.util.List;
import com.example.demo.pojo.Student;
public interface TestService {
List<Student> getAllStudent();
}
| true
|
59d0401e2774c5ce899e4a76664e83e047e47340
|
Java
|
heitorpsena/teste-fcamara
|
/src/br/com/fcamara/questao3/Questao3.java
|
UTF-8
| 608
| 3.296875
| 3
|
[] |
no_license
|
package br.com.fcamara.questao3;
import java.util.Scanner;
public class Questao3 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Digite o numero de horas: ");
int horas = scanner.nextInt();
System.out.println("Digite o valor do salario minimo: ");
double valorDoSalario = scanner.nextDouble();
double valorHora = valorDoSalario * 0.1;
double salarioBruto = horas * valorHora;
double salarioLiquido = salarioBruto - (salarioBruto * 0.03);
System.out.printf("Seu salario e no valor de: %.2f", salarioLiquido);
}
}
| true
|
6011a15b0acb82b51ee4a6f6af42b14296d87d12
|
Java
|
wonthechan/PS
|
/src/study/date0411/Main_B1305_광고.java
|
UTF-8
| 1,025
| 3.03125
| 3
|
[] |
no_license
|
package study.date0411;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
public class Main_B1305_광고 {
static int L;
public static void main(String[] args) throws Exception {
System.setIn(new FileInputStream("input_b1305.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
L = Integer.parseInt(br.readLine());
String source = br.readLine();
int[] pi = getPi(source);
// System.out.println(Arrays.toString(pi));
// System.out.println(source.substring(0, L - pi[L - 1]));
System.out.println(L - pi[L - 1]);// 개수를 출력!!!
}
private static int[] getPi(String source) {
int[] pi = new int[source.length()];
int j = 0;
for (int i = 1; i < source.length(); i++) {
while (j > 0 && source.charAt(i) != source.charAt(j)) {
j = pi[j - 1]; //back!
}
if (source.charAt(i) == source.charAt(j)) {
pi[i] = ++j;
}
}
return pi;
}
}
| true
|
20a66da82601107880affd50bc0bb36fc4af84f6
|
Java
|
ndsev/zserio
|
/test/errors/expressions_error/java/expressions_error/isset_operators/IsSetOperatorsErrorTest.java
|
UTF-8
| 1,260
| 2.078125
| 2
|
[
"BSD-3-Clause"
] |
permissive
|
package expressions_error.isset_operators;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import test_utils.ZserioErrorOutput;
public class IsSetOperatorsErrorTest
{
@BeforeAll
public static void readZserioErrors() throws IOException
{
zserioErrors = new ZserioErrorOutput();
}
@Test
public void arrayType()
{
final String error = "array_type_error.zs:11:31: 'bitmaskArray' is not a bitmask!";
assertTrue(zserioErrors.isPresent(error));
}
@Test
public void enumType()
{
final String error = "enum_type_error.zs:10:35: 'enumField' is not a bitmask!";
assertTrue(zserioErrors.isPresent(error));
}
@Test
public void integerType()
{
final String error = "integer_type_error.zs:11:33: 'field' is not a bitmask!";
assertTrue(zserioErrors.isPresent(error));
}
@Test
public void wrongBitmaskType()
{
final String error = "wrong_bitmask_type_error.zs:16:47: 'WrongBitmask' does not match to 'Bitmask'!";
assertTrue(zserioErrors.isPresent(error));
}
private static ZserioErrorOutput zserioErrors;
}
| true
|
8691c5fc27359751c2b5f0ca5b73b034dfa5977a
|
Java
|
hujianrui/Synthesizer
|
/src/Sources/Widget.java
|
UTF-8
| 223
| 2.171875
| 2
|
[] |
no_license
|
package Sources;
import javafx.scene.layout.BorderPane;
import javafx.scene.shape.Circle;
public interface Widget {
public BorderPane getWidget();
public Circle getOutputCircle();
public Circle getInputCircle();
}
| true
|
76c4ba8ff40485109292f77a993f1a85dc6306e3
|
Java
|
gentics/mesh
|
/rest-model/src/main/java/com/gentics/mesh/core/rest/event/node/SchemaMigrationCause.java
|
UTF-8
| 676
| 2.046875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.gentics.mesh.core.rest.event.node;
import com.gentics.mesh.ElementType;
import com.gentics.mesh.core.rest.event.EventCauseAction;
import com.gentics.mesh.core.rest.event.EventCauseInfo;
import com.gentics.mesh.core.rest.event.migration.SchemaMigrationMeshEventModel;
/**
* Cause POJO for a schema migration cause that can be included in an event.
*/
public class SchemaMigrationCause extends SchemaMigrationMeshEventModel implements EventCauseInfo {
public SchemaMigrationCause() {
}
@Override
public ElementType getType() {
return ElementType.JOB;
}
@Override
public EventCauseAction getAction() {
return EventCauseAction.SCHEMA_MIGRATION;
}
}
| true
|
1a31592b35f41068b961d6c82a645f9ffee697dc
|
Java
|
Joshua-Inkyu-Heo/Java_example
|
/Day006/src/Exam_03.java
|
UTF-8
| 663
| 3.4375
| 3
|
[] |
no_license
|
import java.io.*;
public class Exam_03 {
public static void main(String[] args) throws IOException {
BufferedReader in =
new BufferedReader(new InputStreamReader(System.in));
int su1 = 0, su2 = 0;
System.out.print("su1 = ");
su1 = Integer.parseInt(in.readLine());
System.out.print("su2 = ");
su2 = Integer.parseInt(in.readLine());
if (su1 > su2)
System.out.println("su1 이 더 큰수 입니다.");
else if (su1 < su2)
System.out.println("su2 이 더 큰수 입니다.");
else
System.out.println("같은 수 입니다.");
}
}
| true
|
3d828bda5fb410243cd4146105599b37c86910b4
|
Java
|
KarenWest/happy_birthday_valentine
|
/MainActivity.java
|
UTF-8
| 6,861
| 2.5625
| 3
|
[] |
no_license
|
package com.example.happybirthdayvalentine;
//Karen West, Assignment #3 Android Apps Class, Feb. 9th, 2013
//This app demonstrates the use of concepts learned in Weeks 6 and 7
//and some concepts from earlier weeks as well.
//I used: ScrollView, LinearLayout, OnClickListener, TextView, ImageView
//Visibility, Simple Animation, Intents, EditText and a button for email
//(from the list the professor gave,
//where we must use at least 4 items on that list).
//I tested it on the emulator: Intel 10 480x800-mdpi and it worked fine.
//I tested it on the emulator: Nexus-7-18tvdpi, and it worked fine there too,
//except that when you went to the youtube video (clicking on bottom photo),
//the music played, but you could not see the monkey singing it, as you could
//on the other emulator, and I did not have time to find out why.
//NOTE: for the email part - the Intel 10 email client set up DID NOT work -
//I could NOT set up the email on the emulator. However it did work on the
//Nexus 7. Here is the set-up instructions I followed, since I do not yet own
//a mobile device and rely on the emulators for this class.
//http://www.androidaspect.com/2012/06/how-to-send-email-from-android-emulator.html
//These worked on the Nexus 7, so that is where that part will work, with email.
//On the Intel 10 emulated device, if you click send email, you will get the
//toast message to please configure your email device, and when I tried to do that
//there as I did on the Nexus 7, it said it was not allowed on this for some reason.
//However, sending email did work on the Nexus 7.
//The Nexus 7 did NOT work though as mentioned for VIEWING the monkey singing
//happy birthday you tube video - you could hear him but not see him.
//In order to SEE the monkey on you tube singing happy birthday, you have to use the
//Intel 10 device - did not have time to figure out why.
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final String TAG = "HappyBirthdayValentineActivity";
private EditText mEmail;
MediaPlayer beatlesHappyBirthdayMediaPlayer;
//beatles happy birthday yout tube video not available for mobiles
//String url_happybirthdayvalentine = "http://www.youtube.com/watch?v=LPO5UBbR8SE";
String url_happybirthdayvalentine = "http://www.youtube.com/watch?v=rur5wKoua1o&list=PLA9525CE7B38D5742&index=1";
//String url_photoAfterAnimate = "file:///android_asset/peter_on_newyearseve_2013into2014.jpg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEmail = (EditText) findViewById(R.id.email);
OnClickListener listener = new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent i = new Intent(Intent.ACTION_VIEW);
//video not allowed on mobiles
//change to a photo or happy birthday message
i.setData(Uri.parse(url_happybirthdayvalentine));
startActivity(i);
}
};
/* another possible way - did other way -from onClick in xml
final Button emailButton = (Button) findViewById(R.id.emailbutton);
emailButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
sendValentineBirthdayEmail(v);
}
});
*/
findViewById(R.id.peterwithsaxophone).setOnClickListener(listener);
}
public void sendValentineBirthdayEmail(View v) {
Log.e(TAG, "sendEmail");
String email = mEmail.getText().toString();
String message = null;
if (email.length() > 0) {
message = message + "\nAlternative Email:" + email;
}
//From Professor Lawrence Angrave:
// FYI There's lots of discussion about email intents on StackOverflow
// eg SEND vs SENDTO and setting the mimetype to message/rfc822
// Experimentally the following works on many devices
// - Tested on Android 1.6 and 4.x phones, and tablets and 2.x,4.x
// emulator.
// You will need to configure the emulator's email client with a
// real email address.
// To test unsupported schemes change "mailto" to "horseback"
Log.e(TAG, "creating email Intent");
Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
emailIntent.setData(Uri.fromParts("mailto",
"incognitodiscforums@gmail.com", null));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "happy birthday valentine!");
emailIntent.putExtra(Intent.EXTRA_TEXT, message);
//From Professor Lawrence Angrave:
// Better .... use resolveActivity
// We can check to see if there is a configured email client
// BEFORE trying to start an activity
// Using this test we could have prevented the user from ever opening
// the survey...
Log.e(TAG,"email intent to resolve activity");
if (emailIntent.resolveActivity(getPackageManager()) == null) {
Log.e(TAG, "toast to please configure email client");
Toast.makeText(getApplicationContext(),
"Please configure your email client!", Toast.LENGTH_LONG).show();
} else {
// Secondly, use a chooser will gracefully handle 0,1,2+ matching
// activities
Log.e(TAG, "start activity create chooser");
startActivity(Intent.createChooser(emailIntent,"Please choose your email app!"));
}
}
@Override
protected void onResume() {
Log.e(TAG, "onResume!");
beatlesHappyBirthdayMediaPlayer = MediaPlayer.create(this, R.raw.the_beatles_birthday_song);
beatlesHappyBirthdayMediaPlayer.setLooping(true);
beatlesHappyBirthdayMediaPlayer.start();
super.onResume();
}
@Override
protected void onPause() {
Log.e(TAG, "onPause!");
beatlesHappyBirthdayMediaPlayer.stop();
beatlesHappyBirthdayMediaPlayer.release();
super.onPause();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void animatePeterAndSophie(View v) {
Log.e(TAG, "animatePeterAndSophie");
View view = findViewById(R.id.peterandsophie_newyears);
//view.setVisibility(View.VISIBLE);
// Declare the variable (the pointer!) The next line does NOT create a
// new animation object - all we have is pointer so far.
Animation anim;
// Create a new animation object
anim = AnimationUtils.makeOutAnimation(this, true);
//view.setVisibility(View.INVISIBLE);
// Tell the view it's time to start animating
view.startAnimation(anim);
//Intent i = new Intent(Intent.ACTION_VIEW);
//i.setData(Uri.parse(url_photoAfterAnimate));
//startActivity(i);
}
}
| true
|
fddf488257ecee3de33f4b4e6b05af9521f791aa
|
Java
|
danlangford/xenon
|
/source/main/java/com/avereon/xenon/Mod.java
|
UTF-8
| 3,547
| 2.84375
| 3
|
[] |
no_license
|
package com.avereon.xenon;
import com.avereon.product.ProductCard;
import com.avereon.util.LogUtil;
import org.slf4j.Logger;
import java.io.IOException;
import java.lang.invoke.MethodHandles;
import java.nio.file.Path;
/**
* Mods are the way to provide functionality in the program. Otherwise the
* program is nothing more than a framework. The Mod class provided the basic
* interface and implementation of a Mod. Subclasses should use the register(),
* create(), destroy() and unregister() lifecycle methods to interact with the
* program.
*/
public abstract class Mod implements ProgramProduct, Comparable<Mod> {
private static final Logger log = LogUtil.get( MethodHandles.lookup().lookupClass() );
private Program program;
private ProductCard card;
public Mod() {
try {
card = new ProductCard().load( this );
} catch( IOException exception ) {
throw new RuntimeException( "Error loading product card: " + getClass().getName() );
}
}
@Override
public Program getProgram() {
return program;
}
@Override
public ProductCard getCard() {
return card;
}
/**
* Called by the product manager to initialize the mod. This method should not
* be called by other classes.
*
* @param program
* @param card
*/
public final void init( Program program, ProductCard card ) {
this.program = program;
this.card = card;
}
/**
* Called by the program to register a mod instance. This method is typically
* called before the program frame and workspaces are created and allows the
* mod to register icons, actions, resource types, tools, etc. This method is
* also called as part of the mod install process before the {@link #startup}
* method is called.
*/
public void register() {}
/**
* Called by the program to startup a mod instance. This method is typically
* called after the program frame and workspaces are created, but not
* necessarily visible, and allows the mod to perform any work needed once the
* UI is generated. This method is also called as part of the mod install
* process after the {@link #register} method is called. This method is also
* called when a mod is enabled from the product tool.
*/
public void startup() {}
/**
* Called by the program to shutdown a mod instance. This method is typically
* called before the program frame and workspaces are destroyed. This allows
* the mod to perform any work needed before the UI is destroyed. This method
* is also called as part of the mod uninstall process before the
* {@link #unregister} method is called. This method is also called when a mod
* is disabled from the product tool.
*/
public void shutdown() {}
/**
* Called by the program to unregister a mod instance. This method is
* typically called after the program frame and workspaces are destroyed and
* allows the mod to unregister icons, actions, resource types, tools, etc.
* This method is also called as part of the mod uninstall process after the
* {@link #shutdown} method is called.
*/
public void unregister() {}
/**
* {@inheritDoc}
*/
@Override
public Path getDataFolder() {
return program.getDataFolder().resolve( card.getProductKey() );
}
/**
* This implementation only compares the product card artifact values.
*/
@Override
public int compareTo( Mod that ) {
return this.card.getArtifact().compareTo( that.card.getArtifact() );
}
/**
* This implementation only returns the product card name.
*/
@Override
public String toString() {
return card.getName();
}
}
| true
|
b91a6b31e727acfeb710ca6d143577a9e66f829e
|
Java
|
DanceZZ/Missile-Command
|
/src/main/java/com/blackenedsystems/games/missilecommand/EnemyWeaponsFactory.java
|
UTF-8
| 1,522
| 3.1875
| 3
|
[] |
no_license
|
package com.blackenedsystems.games.missilecommand;
import java.util.Random;
import java.util.List;
/**
* Creates the various enemy weapons against which the player must defend his cities and
* missile bases.
*
* @author: Alan Tibbetts
* @since: Feb 22, 2010, 9:42:04 PM
*/
public class EnemyWeaponsFactory {
private final Random randomNumberGenerator = new Random();
private final List<DefensiveObject> targets;
private final GameArea gameArea;
public EnemyWeaponsFactory(GameArea gameArea, List<DefensiveObject> targets) {
this.gameArea = gameArea;
this.targets = targets;
}
/**
* Constructs an <code>InterContinentalBallisticMissile</code>. Its target will be randomly
* selected from a list of defensive installations (cities and missile bases). The missile
* will start its flight at a random point along the top edge of the game area.
*
* @param speed the speed at which the missile will travel toward its target.
* @return an enemy missile.
*/
public InterContinentalBallisticMissile createMissile(int speed) {
return new InterContinentalBallisticMissile(generateInitialXCoordinate(), selectTarget(), speed);
}
private DefensiveObject selectTarget() {
int targetId = randomNumberGenerator.nextInt(targets.size() - 1);
return targets.get(targetId);
}
public int generateInitialXCoordinate() {
return randomNumberGenerator.nextInt(gameArea.getParent().getWidth() - 1);
}
}
| true
|
89aff80cc5d15d4f4227e4d2781eb3e42485b7b5
|
Java
|
aslepikas/playgroundmanager
|
/src/main/java/com/some/playground/history/Snapshot.java
|
UTF-8
| 313
| 1.804688
| 2
|
[] |
no_license
|
package com.some.playground.history;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import java.time.LocalDateTime;
import java.util.Set;
@RequiredArgsConstructor
@Getter
public class Snapshot {
private final LocalDateTime dateTime;
private final Set<UtilisationRecord> utilisationSet;
}
| true
|
617271f0853bb8d8259a37e39795258c8a4094a0
|
Java
|
spacechase0/ComponentEquipment
|
/com/spacechase0/minecraft/componentequipment/item/DocumentationItem.java
|
UTF-8
| 1,024
| 2.078125
| 2
|
[
"MIT"
] |
permissive
|
package com.spacechase0.minecraft.componentequipment.item;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import com.spacechase0.minecraft.componentequipment.ComponentEquipment;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class DocumentationItem extends Item
{
public DocumentationItem()
{
setUnlocalizedName( "componentequipment:docBook" );
setCreativeTab( ComponentEquipment.partsTab );
}
public ItemStack onItemRightClick( ItemStack stack, World world, EntityPlayer player )
{
player.openGui( ComponentEquipment.instance, ComponentEquipment.DOCUMENTATION_GUI_ID, world, 0, 0, 0 );
return stack;
}
@Override
@SideOnly(Side.CLIENT)
public void registerIcons( IIconRegister register )
{
itemIcon = register.registerIcon( "minecraft:book_enchanted" );
}
}
| true
|
1cae259d14c6358d46eadc62e2598ca95cef7309
|
Java
|
Game-Designing/Custom-Football-Game
|
/sources/com/inmobi/ads/NativeTracker.java
|
UTF-8
| 16,969
| 1.765625
| 2
|
[
"MIT"
] |
permissive
|
package com.inmobi.ads;
import com.inmobi.commons.core.p218a.C10621a;
import com.inmobi.commons.core.p222e.C10658a;
import com.inmobi.commons.core.utilities.C10700d;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
public final class NativeTracker {
/* renamed from: e */
private static final String f31376e = NativeTracker.class.getSimpleName();
/* renamed from: a */
String f31377a;
/* renamed from: b */
TrackerEventType f31378b;
/* renamed from: c */
Map<String, String> f31379c;
/* renamed from: d */
Map<String, Object> f31380d;
/* renamed from: f */
private String f31381f;
/* renamed from: g */
private int f31382g;
/* renamed from: com.inmobi.ads.NativeTracker$1 */
static /* synthetic */ class C103291 {
/* renamed from: a */
static final /* synthetic */ int[] f31383a = new int[TrackerEventType.values().length];
static {
try {
f31383a[TrackerEventType.TRACKER_EVENT_TYPE_UNKNOWN.ordinal()] = 1;
} catch (NoSuchFieldError e) {
}
try {
f31383a[TrackerEventType.TRACKER_EVENT_TYPE_LOAD.ordinal()] = 2;
} catch (NoSuchFieldError e2) {
}
try {
f31383a[TrackerEventType.TRACKER_EVENT_TYPE_CLIENT_FILL.ordinal()] = 3;
} catch (NoSuchFieldError e3) {
}
try {
f31383a[TrackerEventType.TRACKER_EVENT_TYPE_RENDER.ordinal()] = 4;
} catch (NoSuchFieldError e4) {
}
try {
f31383a[TrackerEventType.TRACKER_EVENT_TYPE_VIDEO_RENDER.ordinal()] = 5;
} catch (NoSuchFieldError e5) {
}
try {
f31383a[TrackerEventType.TRACKER_EVENT_TYPE_PAGE_VIEW.ordinal()] = 6;
} catch (NoSuchFieldError e6) {
}
try {
f31383a[TrackerEventType.TRACKER_EVENT_TYPE_CLICK.ordinal()] = 7;
} catch (NoSuchFieldError e7) {
}
try {
f31383a[TrackerEventType.TRACKER_EVENT_TYPE_PLAY.ordinal()] = 8;
} catch (NoSuchFieldError e8) {
}
try {
f31383a[TrackerEventType.TRACKER_EVENT_TYPE_Q1.ordinal()] = 9;
} catch (NoSuchFieldError e9) {
}
try {
f31383a[TrackerEventType.TRACKER_EVENT_TYPE_Q2.ordinal()] = 10;
} catch (NoSuchFieldError e10) {
}
try {
f31383a[TrackerEventType.TRACKER_EVENT_TYPE_Q3.ordinal()] = 11;
} catch (NoSuchFieldError e11) {
}
try {
f31383a[TrackerEventType.TRACKER_EVENT_TYPE_Q4.ordinal()] = 12;
} catch (NoSuchFieldError e12) {
}
try {
f31383a[TrackerEventType.TRACKER_EVENT_TYPE_CREATIVE_VIEW.ordinal()] = 13;
} catch (NoSuchFieldError e13) {
}
try {
f31383a[TrackerEventType.TRACKER_EVENT_TYPE_FULLSCREEN.ordinal()] = 14;
} catch (NoSuchFieldError e14) {
}
try {
f31383a[TrackerEventType.TRACKER_EVENT_TYPE_EXIT_FULLSCREEN.ordinal()] = 15;
} catch (NoSuchFieldError e15) {
}
try {
f31383a[TrackerEventType.TRACKER_EVENT_TYPE_MUTE.ordinal()] = 16;
} catch (NoSuchFieldError e16) {
}
try {
f31383a[TrackerEventType.TRACKER_EVENT_TYPE_UNMUTE.ordinal()] = 17;
} catch (NoSuchFieldError e17) {
}
try {
f31383a[TrackerEventType.TRACKER_EVENT_TYPE_PAUSE.ordinal()] = 18;
} catch (NoSuchFieldError e18) {
}
try {
f31383a[TrackerEventType.TRACKER_EVENT_TYPE_RESUME.ordinal()] = 19;
} catch (NoSuchFieldError e19) {
}
try {
f31383a[TrackerEventType.TRACKER_EVENT_TYPE_ERROR.ordinal()] = 20;
} catch (NoSuchFieldError e20) {
}
try {
f31383a[TrackerEventType.TRACKER_EVENT_TYPE_IAS.ordinal()] = 21;
} catch (NoSuchFieldError e21) {
}
try {
f31383a[TrackerEventType.TRACKER_EVENT_TYPE_MOAT.ordinal()] = 22;
} catch (NoSuchFieldError e22) {
}
try {
f31383a[TrackerEventType.TRACKER_EVENT_TYPE_END_CARD_CLOSE.ordinal()] = 23;
} catch (NoSuchFieldError e23) {
}
}
}
enum TrackerEventType {
TRACKER_EVENT_TYPE_UNKNOWN,
TRACKER_EVENT_TYPE_LOAD,
TRACKER_EVENT_TYPE_CLIENT_FILL,
TRACKER_EVENT_TYPE_RENDER,
TRACKER_EVENT_TYPE_PAGE_VIEW,
TRACKER_EVENT_TYPE_CLICK,
TRACKER_EVENT_TYPE_VIDEO_RENDER,
TRACKER_EVENT_TYPE_FALLBACK_URL,
TRACKER_EVENT_TYPE_PLAY,
TRACKER_EVENT_TYPE_Q1,
TRACKER_EVENT_TYPE_Q2,
TRACKER_EVENT_TYPE_Q3,
TRACKER_EVENT_TYPE_Q4,
TRACKER_EVENT_TYPE_CREATIVE_VIEW,
TRACKER_EVENT_TYPE_FULLSCREEN,
TRACKER_EVENT_TYPE_EXIT_FULLSCREEN,
TRACKER_EVENT_TYPE_MUTE,
TRACKER_EVENT_TYPE_UNMUTE,
TRACKER_EVENT_TYPE_PAUSE,
TRACKER_EVENT_TYPE_RESUME,
TRACKER_EVENT_TYPE_ERROR,
TRACKER_EVENT_TYPE_END_CARD_CLOSE,
TRACKER_EVENT_TYPE_CUSTOM_EVENT_VIDEO,
TRACKER_EVENT_TYPE_IAS,
TRACKER_EVENT_TYPE_MOAT,
TRACKER_EVENT_TYPE_DOWNLOADER_INIT,
TRACKER_EVENT_TYPE_DOWNLOADER_DOWNLOADING,
TRACKER_EVENT_TYPE_DOWNLOADER_DOWNLOADED,
TRACKER_EVENT_TYPE_DOWNLOADER_ERROR
}
public NativeTracker(String str, int i, TrackerEventType trackerEventType, Map<String, String> map) {
this("url_ping", str, i, trackerEventType, map);
}
private NativeTracker(String str, String str2, int i, TrackerEventType trackerEventType, Map<String, String> map) {
this.f31381f = str;
this.f31377a = str2.trim();
this.f31382g = i;
this.f31378b = trackerEventType;
this.f31379c = map;
}
/* renamed from: a */
static NativeTracker m33703a(JSONObject jSONObject) {
try {
String string = jSONObject.getString("type");
if (string != null) {
if (string.length() != 0) {
String lowerCase = string.toLowerCase(Locale.US);
switch (lowerCase.hashCode()) {
case -1918378017:
boolean equals = lowerCase.equals("html_script");
break;
case -970292670:
boolean equals2 = lowerCase.equals("url_ping");
break;
case -284840886:
boolean equals3 = lowerCase.equals("unknown");
break;
case 2015859192:
lowerCase.equals("webview_ping");
break;
}
}
}
return new NativeTracker(jSONObject.getString("url"), jSONObject.optInt("eventId", -1), m33702a(jSONObject.getString("eventType")), new HashMap());
} catch (JSONException e) {
new StringBuilder("Error building tracker from JSONObject; ").append(e.getMessage());
C10621a.m34854a().mo34423a(new C10658a(e));
return null;
}
}
/* renamed from: a */
static TrackerEventType m33702a(String str) {
if (str == null || str.length() == 0) {
return TrackerEventType.TRACKER_EVENT_TYPE_UNKNOWN;
}
char c = 65535;
switch (str.hashCode()) {
case -1638835128:
if (str.equals("midpoint")) {
c = 10;
break;
}
break;
case -1337830390:
if (str.equals("thirdQuartile")) {
c = 11;
break;
}
break;
case -934426579:
if (str.equals("resume")) {
c = 19;
break;
}
break;
case -840405966:
if (str.equals("unmute")) {
c = 17;
break;
}
break;
case -667101923:
if (str.equals("zMoatVASTIDs")) {
c = 22;
break;
}
break;
case -599445191:
if (str.equals("complete")) {
c = 12;
break;
}
break;
case -284840886:
if (str.equals("unknown")) {
c = 1;
break;
}
break;
case -174104201:
if (str.equals("client_fill")) {
c = 3;
break;
}
break;
case -45894975:
if (str.equals("IAS_VIEWABILITY")) {
c = 21;
break;
}
break;
case 3327206:
if (str.equals("load")) {
c = 2;
break;
}
break;
case 3363353:
if (str.equals("mute")) {
c = 16;
break;
}
break;
case 94750088:
if (str.equals("click")) {
c = 7;
break;
}
break;
case 96784904:
if (str.equals("error")) {
c = 20;
break;
}
break;
case 106440182:
if (str.equals("pause")) {
c = 18;
break;
}
break;
case 109757538:
if (str.equals("start")) {
c = 8;
break;
}
break;
case 110066619:
if (str.equals("fullscreen")) {
c = 14;
break;
}
break;
case 113951609:
if (str.equals("exitFullscreen")) {
c = 15;
break;
}
break;
case 354294980:
if (str.equals("VideoImpression")) {
c = 5;
break;
}
break;
case 560220243:
if (str.equals("firstQuartile")) {
c = 9;
break;
}
break;
case 883937877:
if (str.equals("page_view")) {
c = 6;
break;
}
break;
case 1342121331:
if (str.equals("closeEndCard")) {
c = 23;
break;
}
break;
case 1778167540:
if (str.equals("creativeView")) {
c = 13;
break;
}
break;
case 2114088489:
if (str.equals("Impression")) {
c = 4;
break;
}
break;
}
switch (c) {
case 2:
return TrackerEventType.TRACKER_EVENT_TYPE_LOAD;
case 3:
return TrackerEventType.TRACKER_EVENT_TYPE_CLIENT_FILL;
case 4:
return TrackerEventType.TRACKER_EVENT_TYPE_RENDER;
case 5:
return TrackerEventType.TRACKER_EVENT_TYPE_VIDEO_RENDER;
case 6:
return TrackerEventType.TRACKER_EVENT_TYPE_PAGE_VIEW;
case 7:
return TrackerEventType.TRACKER_EVENT_TYPE_CLICK;
case 8:
return TrackerEventType.TRACKER_EVENT_TYPE_PLAY;
case 9:
return TrackerEventType.TRACKER_EVENT_TYPE_Q1;
case 10:
return TrackerEventType.TRACKER_EVENT_TYPE_Q2;
case 11:
return TrackerEventType.TRACKER_EVENT_TYPE_Q3;
case 12:
return TrackerEventType.TRACKER_EVENT_TYPE_Q4;
case 13:
return TrackerEventType.TRACKER_EVENT_TYPE_CREATIVE_VIEW;
case 14:
return TrackerEventType.TRACKER_EVENT_TYPE_FULLSCREEN;
case 15:
return TrackerEventType.TRACKER_EVENT_TYPE_EXIT_FULLSCREEN;
case 16:
return TrackerEventType.TRACKER_EVENT_TYPE_MUTE;
case 17:
return TrackerEventType.TRACKER_EVENT_TYPE_UNMUTE;
case 18:
return TrackerEventType.TRACKER_EVENT_TYPE_PAUSE;
case 19:
return TrackerEventType.TRACKER_EVENT_TYPE_RESUME;
case 20:
return TrackerEventType.TRACKER_EVENT_TYPE_ERROR;
case 21:
return TrackerEventType.TRACKER_EVENT_TYPE_IAS;
case 22:
return TrackerEventType.TRACKER_EVENT_TYPE_MOAT;
case 23:
return TrackerEventType.TRACKER_EVENT_TYPE_END_CARD_CLOSE;
default:
return TrackerEventType.TRACKER_EVENT_TYPE_UNKNOWN;
}
}
public final String toString() {
String str;
JSONObject jSONObject = new JSONObject();
try {
jSONObject.put("type", this.f31381f);
jSONObject.put("url", this.f31377a);
String str2 = "eventType";
switch (C103291.f31383a[this.f31378b.ordinal()]) {
case 2:
str = "load";
break;
case 3:
str = "client_fill";
break;
case 4:
str = "Impression";
break;
case 5:
str = "VideoImpression";
break;
case 6:
str = "page_view";
break;
case 7:
str = "click";
break;
case 8:
str = "start";
break;
case 9:
str = "firstQuartile";
break;
case 10:
str = "midpoint";
break;
case 11:
str = "thirdQuartile";
break;
case 12:
str = "complete";
break;
case 13:
str = "creativeView";
break;
case 14:
str = "fullscreen";
break;
case 15:
str = "exitFullscreen";
break;
case 16:
str = "mute";
break;
case 17:
str = "unmute";
break;
case 18:
str = "pause";
break;
case 19:
str = "resume";
break;
case 20:
str = "error";
break;
case 21:
str = "IAS_VIEWABILITY";
break;
case 22:
str = "zMoatVASTIDs";
break;
case 23:
str = "closeEndCard";
break;
default:
str = "unknown";
break;
}
jSONObject.put(str2, str);
jSONObject.put("eventId", this.f31382g);
jSONObject.put("extras", C10700d.m35143a(this.f31379c == null ? new HashMap<>() : this.f31379c, ","));
return jSONObject.toString();
} catch (JSONException e) {
StringBuilder sb = new StringBuilder("Error serializing an ");
sb.append(f31376e);
sb.append(" instance (");
sb.append(e.getMessage());
C10621a.m34854a().mo34423a(new C10658a(e));
return "";
}
}
}
| true
|