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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
16cfc6fe740ffe6a0075d35e0941af6af7264b10 | Java | gauravmassand/DSA | /src/strings/LongestSubStringWithDistinctChars.java | UTF-8 | 891 | 3.734375 | 4 | [] | no_license | package strings;
import java.util.HashSet;
import java.util.Set;
/*3. Longest Substring Without Repeating Characters
Input: "abcabcbb"
Output: 3
Input: "bbbbb"
Output: 1
Input: "pwwkew"
Output: 3
*/
public class LongestSubStringWithDistinctChars {
public static void main(String[] args) {
System.out.println(lengthOfLongestSubstring("abcabcbb"));
}
public static int lengthOfLongestSubstring(String s) {
int i=0;
int j=0;
int maxCount=0;
int n = s.length();
Set<Character> st = new HashSet<>();
while(i<n && j<n) {
if(!st.contains(s.charAt(j))) {
st.add(s.charAt(j));
j++;
}
else {
st.remove(s.charAt(i));
i++;
}
maxCount = Math.max(maxCount,j-i);
}
return maxCount;
}
}
| true |
1753a3d24430caeeb566cb50eba95ba7e28c699a | Java | gonzalods/ejb | /Libreria JDBC/src/main/java/com/viewnextfor/libreria/repositorio/DataAccesException.java | UTF-8 | 297 | 2.140625 | 2 | [] | no_license | package com.viewnextfor.libreria.repositorio;
@SuppressWarnings("serial")
public class DataAccesException extends RuntimeException {
public DataAccesException(){}
public DataAccesException(String msg){
super(msg);
}
public DataAccesException(Throwable t){
super(t);
}
}
| true |
0833507c2980a9ce706434de61e78dddb345e125 | Java | xilin0007/template | /src/main/java/com/fxl/log/LogTool.java | UTF-8 | 1,686 | 2.59375 | 3 | [] | no_license | package com.fxl.log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LogTool {
private Logger logger = LoggerFactory.getLogger(LogTool.class);
//protected Logger logger = Logger.getLogger(this.getClass());
public static LogTool getInstance(Object[] objects) {
LogTool log = new LogTool();
if ((objects != null) && (objects.length > 0)
&& (objects[0] instanceof Class)) {
log.logger = LoggerFactory.getLogger((Class) objects[0]);
//log.logger = Logger.getLogger((Class) objects[0]);
}
return log;
}
public void debug(Object message) {
this.logger.debug("☆☆☆【" + message + "】☆☆☆");
}
public void error(Object message, Object[] objects) {
if ((objects != null) && (objects.length > 0)
&& (objects[0] instanceof Throwable))
this.logger
.error("◆◆◆【" + message + "】◆◆◆", (Throwable) objects[0]);
else
this.logger.error("◆◆◆【" + message + "】◆◆◆");
}
public void error(Object message) {
if (message instanceof Throwable)
this.logger.error("接口调用报错 ◆◆◆[" + message + "]◆◆◆",
(Throwable) message);
else
this.logger.error("◆◆◆【" + message + "】◆◆◆");
}
public void error(Exception message) {
this.logger.error("◆◆◆【" + message.getMessage() + "】◆◆◆");
}
public void info(Object message) {
this.logger.info("★★★【" + message + "】★★★");
}
public void warn(Object message) {
this.logger.warn("※※※【" + message + "】※※※");
}
public boolean isDebugEnabled() {
return this.logger.isDebugEnabled();
}
} | true |
1fb48f7b9f1e8f44f119048514b86a711e6259f6 | Java | aggitdev/investitapp | /src/main/java/investit/domain/ActionType.java | UTF-8 | 104 | 1.921875 | 2 | [] | no_license | package investit.domain;
public enum ActionType {
BUY, SELL;
public String enumValue;
}
| true |
b7d8e39c6a5a4006d753431dcddff69420d9e9dd | Java | vasudevramachandran/Sprint_2 | /src/com/uncc/fairshare/impl/FetchBillImpl.java | UTF-8 | 3,315 | 2.3125 | 2 | [] | no_license | /**
*
*/
package com.uncc.fairshare.impl;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import com.uncc.fairshare.connection.DbConnect;
import com.uncc.fairshare.constants.CommonConstants;
import com.uncc.fairshare.helper.BillDataFetch;
import com.uncc.fairshare.helper.FetchBillDetails;
import com.uncc.fairshare.intf.FetchBillIntf;
/**
* @author vasudev
*
*/
public class FetchBillImpl implements FetchBillIntf{
@Override
public FetchBillDetails fetchBillForUser(FetchBillDetails billDataObj) {
Connection conn = null;
Statement stateObj= null;
FetchBillDetails fetchDetailsObj = new FetchBillDetails();
ResultSet rsObj = null;
conn = new DbConnect().getConnection();
StringBuffer sBufQuery = new StringBuffer(" ");
sBufQuery.append(" SELECT ");
sBufQuery.append(" BILL_ID, CREATED_BY_NAME ");
sBufQuery.append(" , OWED_BY_NAME, BILL_DESCRIPTION, BILL_VALUE, created_by_emailid, owed_by_emailid ");
sBufQuery.append(" FROM FRIENDS_BILL WHERE BILL_ACTIVE = 1 AND created_by_emailid = '"+billDataObj.getEmail()+"'");
if (null != conn){
try {
stateObj = conn.createStatement();
rsObj = stateObj.executeQuery(sBufQuery.toString());
if(rsObj !=null){
BillDataFetch billFetchObj;
HashMap<Integer, BillDataFetch> billMap = new HashMap<Integer, BillDataFetch>();
while(rsObj.next()){
billFetchObj = new BillDataFetch();
billFetchObj.setBillId(rsObj.getInt(CommonConstants.SQL_BILL_ID));
billFetchObj.setBillDescription(rsObj.getString(CommonConstants.SQL_BILL_DESC));
billFetchObj.setBillAmount(rsObj.getLong(CommonConstants.SQL_BILL_AMT));
billFetchObj.setFriendName(rsObj.getString(CommonConstants.SQL_OWED_BY_NAME));
billFetchObj.setFriendEmail(rsObj.getString(CommonConstants.SQL_OWED_BY_EMAILID));
billFetchObj.setUserName(rsObj.getString(CommonConstants.SQL_CREATED_BY_NAME));
billFetchObj.setUserEmail(rsObj.getString(CommonConstants.SQL_CREATED_BY_EMAIL));
billMap.put(billFetchObj.getBillId(), billFetchObj);
}
fetchDetailsObj.setBillDetails(billMap);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(null!=conn){
try {
conn.close();
} catch (SQLException e) {
System.out.println("#addBill#Connection could not be closed in final block");
e.printStackTrace();
}
}
}
}
return fetchDetailsObj;
}
@Override
public int deleteBill(int deleteId) {
Connection conn = new DbConnect().getConnection();
int result = 0;
StringBuffer sBufQuery = new StringBuffer(" ");
sBufQuery.append(" DELETE FROM FRIENDS_BILL WHERE BILL_ID = "+deleteId+"");
Statement stateObj = null;
try {
stateObj = conn.createStatement();
result = stateObj.executeUpdate(sBufQuery.toString());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(null!=conn){
try {
conn.close();
} catch (SQLException e) {
System.out.println("#addBill#Connection could not be closed in final block");
e.printStackTrace();
}
}
}
return result;
}
}
| true |
263b14d5a478e495dfc0e10e98fc3854e86b95fc | Java | ezsaidi/configuration | /target/generated-sources/entity-codegen/extensions/pc/policy/typekey/ValueFormatterTypeExtConstants.java | UTF-8 | 1,621 | 1.765625 | 2 | [] | no_license |
package extensions.pc.policy.typekey;
import gw.pc.policy.typekey.ValueFormatterType;
import gw.pc.policy.typekey.ValueFormatterType.ValueFormatterTypeCache;
public final class ValueFormatterTypeExtConstants {
public final static ValueFormatterTypeCache TC_AGE = new ValueFormatterTypeCache(ValueFormatterType.TYPE, "Age");
public final static ValueFormatterTypeCache TC_CURRENCY = new ValueFormatterTypeCache(ValueFormatterType.TYPE, "Currency");
public final static ValueFormatterTypeCache TC_INTEGER = new ValueFormatterTypeCache(ValueFormatterType.TYPE, "Integer");
public final static ValueFormatterTypeCache TC_MONETARYAMOUNT = new ValueFormatterTypeCache(ValueFormatterType.TYPE, "MonetaryAmount");
public final static ValueFormatterTypeCache TC_NUMBER = new ValueFormatterTypeCache(ValueFormatterType.TYPE, "Number");
public final static ValueFormatterTypeCache TC_STATESET = new ValueFormatterTypeCache(ValueFormatterType.TYPE, "StateSet");
public final static ValueFormatterTypeCache TC_TESTFORMATTER = new ValueFormatterTypeCache(ValueFormatterType.TYPE, "TestFormatter");
public final static ValueFormatterTypeCache TC_USD = new ValueFormatterTypeCache(ValueFormatterType.TYPE, "USD");
public final static ValueFormatterTypeCache TC_USDBRIEF = new ValueFormatterTypeCache(ValueFormatterType.TYPE, "USDBrief");
public final static ValueFormatterTypeCache TC_UNFORMATTED = new ValueFormatterTypeCache(ValueFormatterType.TYPE, "Unformatted");
public final static ValueFormatterTypeCache TC_UNITS = new ValueFormatterTypeCache(ValueFormatterType.TYPE, "Units");
}
| true |
a1e7204cadb5a7da79a7af1a933b578277ea22c4 | Java | Bjelijah/whoseface | /howellsdk/src/main/java/com/howellsdk/net/http/bean/FaceDetectDeviceGroupList.java | UTF-8 | 1,194 | 2.171875 | 2 | [] | no_license | package com.howellsdk.net.http.bean;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
public class FaceDetectDeviceGroupList {
@SerializedName("Page") Page page;
@SerializedName("FaceDetectDeviceGroup") ArrayList<FaceDetectDeviceGroup> faceDetectDeviceGroups;
@Override
public String toString() {
return "FaceDetectDeviceGroupList{" +
"page=" + page +
", faceDetectDeviceGroups=" + faceDetectDeviceGroups +
'}';
}
public Page getPage() {
return page;
}
public void setPage(Page page) {
this.page = page;
}
public ArrayList<FaceDetectDeviceGroup> getFaceDetectDeviceGroups() {
return faceDetectDeviceGroups;
}
public void setFaceDetectDeviceGroups(ArrayList<FaceDetectDeviceGroup> faceDetectDeviceGroups) {
this.faceDetectDeviceGroups = faceDetectDeviceGroups;
}
public FaceDetectDeviceGroupList() {
}
public FaceDetectDeviceGroupList(Page page, ArrayList<FaceDetectDeviceGroup> faceDetectDeviceGroups) {
this.page = page;
this.faceDetectDeviceGroups = faceDetectDeviceGroups;
}
}
| true |
49621b1760077dc967ed8351dd895b411ccc08f6 | Java | sk-raheem/SocioTweet1 | /SocioTweet/src/main/java/com/sociotweet/controller/AuthController.java | UTF-8 | 1,334 | 2.125 | 2 | [] | no_license | package com.sociotweet.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.sociotweet.model.Response;
import com.sociotweet.model.User;
import com.sociotweet.service.AuthService;
@RestController
@RequestMapping("/auth")
public class AuthController {
@Autowired
AuthService authService;
@PostMapping("/regs")
public Response userRegistration(@RequestBody User user) {
if(user==null || user.getEmailId()==null || user.getFirstName()==null || user.getLastName()==null || user.getPassword()==null || user.getWardNo()<100) {
Response response=new Response();
response.setResult("fail");
return response;
}
else {
user.setUserRole(1);
Response response=authService.serviceRegister(user);
return response;
}
}
@PostMapping("/login")
public User userLogin(@RequestBody User user) {
if(user==null || user.getEmailId()==null || user.getPassword()==null) {
return user;
}
else {
User loginUser=authService.serviceLogin(user);
return loginUser;
}
}
}
| true |
b5518bf58ef8b397096c7007151f7aa27784d08a | Java | davidcroft/Thesis-MagPad-JavaProcessing | /src/magPadJavaV1/LocationRecognition.java | UTF-8 | 1,946 | 2.921875 | 3 | [] | no_license | package magPadJavaV1;
public class LocationRecognition {
private int m_cirBufSize;
private int m_bufIndex;
private double m_meanPrev;
private double m_meanCurr;
private double m_prevRecog[];
private double m_location;
private boolean m_locationReady;
// status: 0 -- in a robust location and ready to receive location change
// status: 1 -- in a transition status and wait for get a robust location
private int m_recogStatus;
public LocationRecognition(int cirBufSize) {
m_cirBufSize = cirBufSize;
m_bufIndex = 0;
m_meanPrev = 0;
m_meanCurr = 0;
m_location = 0;
m_locationReady = false;
m_recogStatus = 0;
m_prevRecog = new double[m_cirBufSize];
System.out.println("create a LocationRecognition object");
}
// when return true, it means a robust new location ready to be read
public boolean addToRecog(double res) {
// add to m_prevRecog[]
if(m_bufIndex < m_cirBufSize) {
// update m_meanCurr
m_meanCurr = (m_meanCurr*m_bufIndex+res)/(m_bufIndex+1);
// push to array
m_prevRecog[m_bufIndex] = res;
}
// detect recogStatus
updateDetectLocation();
// update m_bufIndex
m_bufIndex = m_bufIndex++ % m_cirBufSize;
// return status
return m_locationReady;
}
public void updateDetectLocation() {
// compare m_meanCurr with m_meanPrev to check if get robust result
if (Math.abs(m_meanCurr-m_meanPrev) >= GlobalConstants.MINRECOGMEAN) {
// move to a new location
m_recogStatus = 1;
} else if (Math.abs(m_meanCurr-m_meanPrev) <= GlobalConstants.MAXRECOGMEAN) {
// update location
if (m_recogStatus == 1) {
m_location = m_meanCurr;
m_recogStatus = 0;
m_locationReady = true;
}
}
// update m_meanPrev and m_meanCurr
m_meanPrev = m_meanCurr;
}
public double getDetectLocation() {
// status == 0, get a robust position
if (m_locationReady) {
m_locationReady = false;
return m_location;
} else {
return -1;
}
}
}
| true |
c89c147dc5f4579c018921f0ddabd3600f5adb4c | Java | stosabon/ssobolevsky | /chapter_003/src/main/java/ru/job4j/task/UserNotFoundException.java | UTF-8 | 295 | 2.125 | 2 | [
"Apache-2.0"
] | permissive | package ru.job4j.task;
/**
* Created by pro on 02.06.2017.
*/
public class UserNotFoundException extends RuntimeException {
/**
* Exception when user not found
* @param message - message
*/
public UserNotFoundException(String message) {
super(message);
}
}
| true |
72bd93c9815024516a9dd22c5aa70ae412dcbe5e | Java | Comcast/dawg | /libraries/dawg-show/src/test/java/com/comcast/video/dawg/show/video/BufferedImageCerealizerTest.java | UTF-8 | 1,693 | 2.328125 | 2 | [
"Apache-2.0"
] | permissive | /**
* Copyright 2010 Comcast Cable Communications Management, LLC
*
* 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.comcast.video.dawg.show.video;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.comcast.cereal.CerealException;
import com.comcast.cereal.ObjectCache;
public class BufferedImageCerealizerTest {
@Test
public void testCerealize() throws IOException, CerealException {
BufferedImageCerealizer cerealizer = new BufferedImageCerealizer();
BufferedImage image = ImageIO.read(BufferedImageCerealizerTest.class.getResourceAsStream("comcast.jpg"));
String base64 = cerealizer.cerealize(image, new ObjectCache());
BufferedImage image2 = cerealizer.deCerealize(base64, new ObjectCache());
/** Verifying the height and width of the two images it probably good enough.
* Since all the bytes are not exact because one is chunked differently */
Assert.assertEquals(image.getWidth(), image2.getWidth());
Assert.assertEquals(image.getHeight(), image2.getHeight());
}
}
| true |
78c2b1607c2a01ef7024c9f9d4f3a55bcd0ae045 | Java | bellmit/novel-subscription | /novel-subscription-service/novel-subscription-user/src/main/java/top/alexmmd/redis/RedisConfig.java | UTF-8 | 1,761 | 2.640625 | 3 | [] | no_license | package top.alexmmd.redis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
/**
* <h1>Redis 配置</h1>
*/
@Configuration
public class RedisConfig {
private final RedisConnectionFactory redisConnectionFactory;
@Autowired
public RedisConfig(RedisConnectionFactory redisConnectionFactory) {
this.redisConnectionFactory = redisConnectionFactory;
}
/**
* <h2>配置消息监听器</h2>
* */
@Bean
public SubscribeListener listener() {
return new SubscribeListener();
}
/**
* <h2>配置 发布/订阅 的 Topic</h2>
* */
@Bean
public ChannelTopic channelTopic() {
return new ChannelTopic("novel");
}
/**
* <h2>配置 ChannelName 的模式匹配</h2>
* */
@Bean
public PatternTopic patternTopic() {
return new PatternTopic("/novel/*");
}
/**
* <h2>将消息监听器绑定到消息容器</h2>
* */
@Bean
public RedisMessageListenerContainer messageListenerContainer() {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(redisConnectionFactory);
// 可以修改成 patternTopic, 看一看 MessageListener 中监听的数据
container.addMessageListener(listener(), channelTopic());
return container;
}
}
| true |
ff3ecbc3eadaea146a561baa20f813c2704ff9f1 | Java | kendallv17/Backend | /src/main/java/cr/una/crudapp/backend/comun/Constants.java | UTF-8 | 352 | 1.5625 | 2 | [] | no_license | package cr.una.crudapp.backend.comun;
/**
* Constantes del programa
*
* Aqui se guardan las constantes que se llegaran a usar en el programa. La variable URL_PREFIX se usa en
* el Web Service para que el programa sepa a donde debe de llamar
*
*
*/
public class Constants {
public static final String URL_PREFIX = "/api/v1/";
} | true |
dda7bd03c79fa6fc95620edb9fcaa79f82b03572 | Java | bsty2015/DMPlayerL | /app/src/main/java/com/lvandroid/bsty/dmplayer/manager/NotificationManager.java | UTF-8 | 285 | 1.59375 | 2 | [] | no_license | package com.lvandroid.bsty.dmplayer.manager;
/**
* Created by bsty on 4/12/16.
*/
public class NotificationManager {
public interface NotificationCenterDelegate {
void didReceivedNotification(int id, Object... args);
void newSongLoaded(Object... args);
}
}
| true |
6b6d0cedf2c777e2d899c4f0fbbe2b6fbb20e0c8 | Java | yuriwprado/stock-quote-manager | /src/test/java/com/stockquotemanager/controller/StockQuoteControllerTest.java | UTF-8 | 4,349 | 2.0625 | 2 | [] | no_license | package com.stockquotemanager.controller;
import static com.stockquotemanager.utils.StockQuoteConstraints.STOCK_QUOTE_PATH;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Optional.empty;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import org.apache.commons.compress.utils.Lists;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
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.request.MockMvcRequestBuilders;
import com.google.gson.Gson;
import com.stockquotemanager.dto.CreateStockQuoteDTO;
import com.stockquotemanager.dto.StockQuoteDTO;
import com.stockquotemanager.service.StockQuoteService;
@RunWith(SpringRunner.class)
@WebMvcTest(StockQuoteController.class)
public class StockQuoteControllerTest {
private static final String QUOTE_VALUE = "35";
private static final LocalDate QUOTE_DATE = LocalDate.of(2020, 3, 15);
private static final String STOCK_ID = "STOCK_ID_1";
@MockBean
StockQuoteService stockQuoteService;
@Autowired
private MockMvc mvc;
@Test
public void create_SuccessTest() throws Exception {
CreateStockQuoteDTO createDTO = buildCreateStockQuoteDTO();
mvc.perform(
MockMvcRequestBuilders.post(STOCK_QUOTE_PATH)
.content(new Gson().toJson(createDTO))
.contentType(APPLICATION_JSON)
.characterEncoding(UTF_8.displayName())
.accept(APPLICATION_JSON)
)
.andDo(print())
.andExpect(status().isOk());
}
@Test
public void create_NoParameterTest() throws Exception {
CreateStockQuoteDTO createDTO = null;
mvc.perform(
MockMvcRequestBuilders.post(STOCK_QUOTE_PATH)
.content(new Gson().toJson(createDTO))
.contentType(APPLICATION_JSON)
.characterEncoding(UTF_8.displayName())
.accept(APPLICATION_JSON)
)
.andDo(print())
.andExpect(status().isBadRequest());
}
@Test
public void findById_SuccessTest() throws Exception {
Mockito.when(stockQuoteService.findById(Mockito.any())).thenReturn(Optional.of(buildStockQuoteDTO()));
mvc.perform(
MockMvcRequestBuilders.get(STOCK_QUOTE_PATH + "/find/1")
.accept(MediaType.APPLICATION_JSON)
)
.andDo(print())
.andExpect(status().isOk());
}
@Test
public void findById_NoParameterTest() throws Exception {
mvc.perform(
MockMvcRequestBuilders.get(STOCK_QUOTE_PATH + "/find/")
.accept(MediaType.APPLICATION_JSON)
)
.andDo(print())
.andExpect(status().isNotFound());
}
@Test
public void findById_QuoteNotFoundTest() throws Exception {
Mockito.when(stockQuoteService.findById(Mockito.any())).thenReturn(empty());
mvc.perform(
MockMvcRequestBuilders.get(STOCK_QUOTE_PATH + "/find/1")
.accept(MediaType.APPLICATION_JSON)
)
.andDo(print())
.andExpect(status().isNotFound());
}
@Test
public void findAll_SuccessTest() throws Exception {
List<StockQuoteDTO> serviceReturnedList = Lists.newArrayList();
serviceReturnedList.add(buildStockQuoteDTO());
Mockito.when(stockQuoteService.findAll()).thenReturn(serviceReturnedList);
mvc.perform(
MockMvcRequestBuilders.get(STOCK_QUOTE_PATH + "/findAll")
.accept(MediaType.APPLICATION_JSON)
)
.andDo(print())
.andExpect(status().isOk());
}
private CreateStockQuoteDTO buildCreateStockQuoteDTO() {
return CreateStockQuoteDTO.builder().id(STOCK_ID).quotes(buildQuotes()).build();
}
private StockQuoteDTO buildStockQuoteDTO() {
return StockQuoteDTO.builder().id(STOCK_ID).quotes(buildQuotes()).build();
}
private HashMap<LocalDate, String> buildQuotes(){
HashMap<LocalDate, String> quotes = new HashMap<LocalDate, String>();
quotes.put(QUOTE_DATE, QUOTE_VALUE);
return quotes;
}
}
| true |
d7cf77ad7ed45c979633056514ffa1016f82448c | Java | alexbobp/TinkeredConstructer | /src/main/java/slimeknights/tconstruct/smeltery/inventory/ContainerSmelterySideInventory.java | UTF-8 | 1,139 | 2.53125 | 3 | [
"MIT"
] | permissive | package slimeknights.tconstruct.smeltery.inventory;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.SlotItemHandler;
import slimeknights.tconstruct.smeltery.tileentity.TileSmeltery;
import slimeknights.tconstruct.tools.common.inventory.ContainerSideInventory;
public class ContainerSmelterySideInventory extends ContainerSideInventory<TileSmeltery> {
public ContainerSmelterySideInventory(TileSmeltery tile, int x, int y, int columns) {
super(tile, x, y, columns);
}
@Override
protected Slot createSlot(IItemHandler itemHandler, int index, int x, int y) {
return new SmelterySlot(itemHandler, index, x, y);
}
private static class SmelterySlot extends SlotItemHandler {
public SmelterySlot(IItemHandler itemHandler, int index, int xPosition, int yPosition) {
super(itemHandler, index, xPosition, yPosition);
}
@Override
public boolean isItemValid(ItemStack stack) {
return true;
}
@Override
public int getItemStackLimit(ItemStack stack) {
return 1;
}
}
}
| true |
aa4fa6e24b70477e1b3e37a23dbb9531d9b714e8 | Java | z3jjlzt/designPattern | /src/com/kkk/pattern/facade/Waiter.java | UTF-8 | 382 | 2.671875 | 3 | [] | no_license | package com.kkk.pattern.facade;
/**
* 充当外观类
* Created by z3jjlzt on 2018/1/10.
*/
public class Waiter {
private Kitchen kitchen = Kitchen.getInstance();
private Checkstand checkstand = Checkstand.getInstance();
public void order(String food) {
kitchen.cook(food);
}
public void pay(int money) {
checkstand.cashier(money);
}
}
| true |
953db2be39688ca5a67ffeccba4e7c13209b074b | Java | luics1851/SyFP16 | /SyFP16/src/EjerTablas/Tabla.java | UTF-8 | 1,007 | 2.84375 | 3 | [] | no_license | package EjerTablas;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.table.AbstractTableModel;
public class Tabla extends AbstractTableModel {
String m[][];
int i=0;
public Tabla(String s) throws FileNotFoundException, IOException{
m=new String [101][5];
String row[];
BufferedReader br;
br= new BufferedReader(new FileReader(s));
String linea =br.readLine();
while(linea!=null){
row=linea.split(",");
m[i]=row;
i=i+1;
linea=br.readLine();
}
}
@Override
public int getRowCount() {
return 101;
}
@Override
public int getColumnCount() {
return 5;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return m[rowIndex][columnIndex];
}
}
| true |
96c7ee0f80f74cde42a7bc46ddd9e2d0595064a6 | Java | liugang-snow/Equipment | /RuoYi/ruoyi-system/src/main/java/com/ruoyi/system/domain/EquClass.java | UTF-8 | 2,665 | 2.03125 | 2 | [
"MIT"
] | permissive | package com.ruoyi.system.domain;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.core.domain.TreeEntity;
/**
* 设备分类对象 equ_class
*
* @author ruoyi
* @date 2020-02-11
*/
public class EquClass extends TreeEntity
{
private static final long serialVersionUID = 1L;
/** ID 主键 */
private Long classId;
/** Guid */
@Excel(name = "Guid")
private String classGuid;
/** 设备分类名称 */
@Excel(name = "设备分类名称")
private String className;
/** 状态 (0正常 1停用) */
@Excel(name = "状态 ", readConverterExp = "0=正常,1=停用")
private String status;
/** 删除状态 (0代表存在 2代表删除) */
private String delFlag;
/** 父分类名称 */
private String parentName;
public void setClassId(Long classId)
{
this.classId = classId;
}
public Long getClassId()
{
return classId;
}
public void setClassGuid(String classGuid)
{
this.classGuid = classGuid;
}
public String getClassGuid()
{
return classGuid;
}
public void setClassName(String className)
{
this.className = className;
}
public String getClassName()
{
return className;
}
public void setStatus(String status)
{
this.status = status;
}
public String getStatus()
{
return status;
}
public void setDelFlag(String delFlag)
{
this.delFlag = delFlag;
}
public String getDelFlag()
{
return delFlag;
}
public String getParentName()
{
return parentName;
}
public void setParentName(String parentName)
{
this.parentName = parentName;
}
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
.append("classId", getClassId())
.append("classGuid", getClassGuid())
.append("parentId", getParentId())
.append("ancestors", getAncestors())
.append("className", getClassName())
.append("orderNum", getOrderNum())
.append("status", getStatus())
.append("remark", getRemark())
.append("createBy", getCreateBy())
.append("createTime", getCreateTime())
.append("updateBy", getUpdateBy())
.append("updateTime", getUpdateTime())
.append("delFlag", getDelFlag())
.toString();
}
}
| true |
ffe15e8c5a883f9d9aabb9bd2653c11358ad2a78 | Java | hq2cake/JavaOnline_02_Algorithmization | /algorithmization/decomposition/Decomposition16.java | UTF-8 | 2,109 | 4.3125 | 4 | [] | no_license | package by.mikhailov.algorithmization.decomposition;
/**
* Написать программу, определяющую сумму n - значных чисел, содержащих только нечетные цифры.
* Определить также, сколько четных цифр в найденной сумме. Для решения задачи использовать декомпозицию.
*/
public class Decomposition16 {
public static void main(String[] args) {
int n = 4; // - значное число
showSumOfOddNumber(n);
}
public static void showSumOfOddNumber(int n) {
int begin;
int end;
begin = getBeginOfD(n);
end = getEndOfD(n);
for (int i = begin; i < end; i++) {
if (checkNumber(i)) {
System.out.print(i + " (" + " сумма цифр: " + calculateCheckedDigit(i));
System.out.println(" ,количество четных цифр в сумме: " +
getCountOfEvenDigit(calculateCheckedDigit(i)) + ")");
}
}
}
public static int getCountOfEvenDigit(int sum) {
int count = 0;
while (sum != 0) {
if (sum % 2 == 0) {
count++;
}
sum /= 10;
}
return count;
}
public static int calculateCheckedDigit(int number) {
int sum = 0;
while (number != 0) {
sum += (number % 10);
number /= 10;
}
return sum;
}
public static boolean checkNumber(int number) {
int temp;
while (number != 0) {
temp = number % 10;
if (temp % 2 == 0) {
return false;
}
number /= 10;
}
return true;
}
public static int getEndOfD(int n) {
return (int) (Math.pow(10, n));
}
public static int getBeginOfD(int n) {
return (int) (Math.pow(10, n - 1));
}
}
| true |
c228c65032ace5f349b3c05beb5834482ab2687b | Java | yukyeong-dev/pay-program-api | /src/main/java/com/ykpay/api/facade/LoginFacade.java | UTF-8 | 579 | 2.140625 | 2 | [] | no_license | package com.ykpay.api.facade;
import java.util.ArrayList;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import com.ykpay.api.user.model.User;
public class LoginFacade {
public ArrayList<User> loginQuery(String id, String pw, JdbcTemplate template) {
RowMapper<User> dto = new BeanPropertyRowMapper<User>(User.class);
return (ArrayList<User>) template.query("select * from user_table where user_id = '"+id+"' and user_password ='"+pw+"'" , dto);
}
}
| true |
a1b81b9147ec1ecac5f4cbc320b244ed44411797 | Java | BShashidhar/Core_Java | /Core_Java/src/list/Lists.java | UTF-8 | 1,405 | 3.203125 | 3 | [] | no_license | package list;
import java.util.*;
import java.io.*;
public class Lists {
public static void main(String[] args) {
// List<String> L=new ArrayList<>();
// L.add("Suresh");
// L.add("naresh");
// L.add("mahesh");
// /*Iterator itr=L.iterator();
// while(itr.hasNext())
// {
// System.out.println(itr.next());
// }*/
// for(String s:L)
// {
// System.out.println(s);
// }
// int pos=1;
// L.remove(pos);
// System.out.println(L);
// Object toFind="mahesh";
// int pos1=L.indexOf(toFind);
// if(pos1>=0)
// {
// System.out.println("found at " +pos);
// }
// else
// {
// System.out.println("not found");
// }
List<Student> l = new ArrayList<>();
l.add(new Student(101, 23));
l.add(new Student(1981, 278));
l.add(new Student(1214, 29));
l.add(new Student(108, 21));
// Collections.sort(l);
// int pos=1;
// Student stud=l.get(pos);
// stud.setAge(18);
// System.out.println(l);
Student toFind = new Student(101, 23);
int pos1 = l.indexOf(toFind);
Student stud = l.get(pos1);
// stud.setAge(10);
// System.out.println(l);
int i = (int) (Math.random() * 10);
System.out.println(i);
if (i < 5) {
Collections.sort(l);
} else {
Comparator<Student> c = new SortUsingStudentId();
Collections.sort(l, c);
}
for (Student s : l) {
System.out.println(s);
}
}
}
| true |
e7392628edbb8d6719b1e70a91baf3dfcb3346ef | Java | zP1nG/chatroom | /src/Main.java | UTF-8 | 148 | 1.5625 | 2 | [] | no_license |
public class Main {
public static void main(String args[]) {
PassWordWin a = new PassWordWin();
a.show_surface();
a.getinfo();
}
}
| true |
54f37956f5028b657bfa045cbba355ec156afde4 | Java | dsdsam/Kaleidoscope | /DSDS-DSE/src/main/java/dsdsse/designspace/initializer/AdfBasicTable.java | UTF-8 | 1,134 | 2.59375 | 3 | [
"MIT"
] | permissive | package dsdsse.designspace.initializer;
import javax.swing.*;
import javax.swing.table.TableModel;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
/**
* Created by Admin on 4/20/2016.
*/
public class AdfBasicTable extends JTable {
protected TableKeyListener tableKeyListener = new TableKeyListener(this);
class TableKeyListener implements KeyListener {
JTable table = null;
public TableKeyListener(JTable table) {
this.table = table;
}
public void keyPressed(KeyEvent evt) {
System.out.println(evt.getKeyCode() +" "+ evt.getKeyChar());
int i = evt.getModifiers();
if (evt.getKeyCode() == KeyEvent.VK_V) {
}
if (evt.getKeyCode() == KeyEvent.VK_A && ((i & InputEvent.META_MASK) == InputEvent.META_MASK)) {
selectAll();
}
}
public void keyTyped(KeyEvent evt) {
}
public void keyReleased(KeyEvent evt) {
}
}
AdfBasicTable(TableModel tableModel){
super(tableModel);
}
}
| true |
a5d38cc7fa23b398bae7c82a0b17af7ed3e77f02 | Java | JoelFdz/PRG-20-21 | /prg20-21/src/main/java/tema9/Ejer4/Test.java | UTF-8 | 963 | 2.859375 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package tema9.Ejer4;
/**
*
* @author JFSam
*/
public class Test {
public static void main(String[] args) {
Alumno a1 = new Alumno(1, 123, 100);
Alumno a2 = new Alumno(1, 123, 100);
System.out.println("" + a1.equals(a2));
//
Curso c = new Curso();
if (c.consulta(32)==null) {
System.out.println("No esta");
}
Alumno modi = new Alumno(2, "Joel");
Instituto insti1 = new Instituto();
System.out.println(c.toString());
System.out.println(c.consulta(1).toString());
System.out.println(c.modificacion(23, modi));
System.out.println(insti1.listadoGeneral());
System.out.println(insti1.consultaAlumno(56));
}
}
| true |
ea9112fb429d43b3134df4cece40370d63934687 | Java | buster92/test-ionix | /app/src/main/java/com/andresgarrido/testionix/model/sandbox/UserList.java | UTF-8 | 206 | 1.65625 | 2 | [] | no_license | package com.andresgarrido.testionix.model.sandbox;
import java.util.List;
public class UserList {
public List<UserResponse> items;
public UserList(List<UserResponse> items) {
this.items = items;
}
} | true |
67899bb7cc98c399147d2e7fdfe97a814adf49ba | Java | OlhaShymko/Tanks | /Player.java | UTF-8 | 4,091 | 3.21875 | 3 | [] | no_license | package com.thebyteguru.game;
import com.thebyteguru.IO.Input;
import com.thebyteguru.graphics.Sprite;
import com.thebyteguru.graphics.SpriteSheet;
import com.thebyteguru.graphics.TextureAtlas;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Chessmaster on 22.05.16.
*/
public class Player extends Entity {
public static final int SPRITE_SCALE = 16;
public static final int SPRITE_PER_HEADING = 1;
private enum Heading{
//куда смотрит Player(танк)
NORTH(0*SPRITE_SCALE,0*SPRITE_SCALE,1*SPRITE_SCALE, 1*SPRITE_SCALE),
EAST(6*SPRITE_SCALE,0*SPRITE_SCALE,1*SPRITE_SCALE, 1*SPRITE_SCALE),
SOUTH(4*SPRITE_SCALE,0*SPRITE_SCALE,1*SPRITE_SCALE, 1*SPRITE_SCALE),
WEST(2*SPRITE_SCALE,0*SPRITE_SCALE,1*SPRITE_SCALE, 1*SPRITE_SCALE);
//хранят координаты спрайта
private int x,y,h,w;
//конструктор
Heading(int x, int y, int h, int w){
this.x = x;
this.y = y;
this.h = h;
this.w = w;
}
//метод - вырезаем изображения
protected BufferedImage texture(TextureAtlas atlas){
return atlas.cut(x,y,w,h);
}
}
private Heading heading;
private Map<Heading,Sprite> spriteMap;
private float scale;
private float speed;
public Player(float x, float y, float scale, float speed, TextureAtlas atlas){
super(EntityType.Player, x, y);
//создаем карту
heading = Heading.NORTH;
spriteMap = new HashMap<Heading,Sprite>();
this.scale = scale;
this.speed = speed;
//связываем какие-то вещи между каким-то направлением и каким-то изображением
for(Heading h:Heading.values()){
//создаем индивидуальные спрайты
SpriteSheet sheet = new SpriteSheet(h.texture(atlas),SPRITE_PER_HEADING,SPRITE_SCALE);
Sprite sprite = new Sprite(sheet,scale);
//связали каждое направление с каким-то спрайтом
spriteMap.put(h,sprite);
}
}
@Override
public void update(Input input) {
//перестраховатся не вылез ли танк за экран, н-р
float newX = x;
float newY = y;
//проверка на нажатие кнопки вверх
if(input.getKey(KeyEvent.VK_UP)){
newY-=speed;
//если нажата кнопка вверх нужно поменять направление
heading = Heading.NORTH;
//чтоб танк не двигался по диагонали
} else if (input.getKey(KeyEvent.VK_RIGHT)){
newX +=speed;
heading = Heading.EAST;
}
else if (input.getKey(KeyEvent.VK_DOWN)){
newY +=speed;
heading = Heading.SOUTH;
}else if (input.getKey(KeyEvent.VK_LEFT)){
newX -=speed;
heading = Heading.WEST;
}
//проверка на х
if (newX < 0){
newX = 0; //танк за экраном
}else if(newX>=Game.WIDTH - SPRITE_SCALE*scale){
newX = Game.WIDTH - SPRITE_SCALE*scale;
}
//проверка на y
if (newY < 0){
newY = 0; //танк за экраном
}else if(newY>=Game.HEIGHT - SPRITE_SCALE*scale){
newY = Game.HEIGHT - SPRITE_SCALE*scale;
}
x= newX;
y = newY;
}
@Override
public void render(Graphics2D g) {
//проверем, куда смотрит наш танк
//вытащить правильный спрайт в правильном месте
spriteMap.get(heading).render(g, x, y);
}
}
| true |
f288c11ace85467cefd3fa2e872a10d31ec9a115 | Java | z243204162/SmartHome | /app/src/main/java/com/example/zeyupeng/smarthome/Model/MyDevices/DoorLock.java | UTF-8 | 589 | 2 | 2 | [] | no_license | package com.example.zeyupeng.smarthome.Model.MyDevices;
import android.content.Context;
/**
* Created by zeyu peng on 2017-07-31.
*/
public interface DoorLock {
void addDoorLockToControlType();
void initPassword(String password);
void resetPassword(String oldPassword, String newPassword, Context context);
boolean checkPassword(String password);
void lock();
void unlock(String password,Context context);
String getLockStatus();
boolean getDoorLockModifyPermit();
void setDoorLockModifyPermit(boolean modifyPermit);
String getPassword();
}
| true |
cfbb37dd122a33d1578d8234c7f3c44678d0c47d | Java | AshishRKO/Codes | /LinkedList/src/ReverseList.java | UTF-8 | 2,368 | 4.34375 | 4 | [] | no_license | /* Reverse a Linked List both recursively and iteratively
/* Uncomment this if you are using this outside the package where Node.java is not available
/*
class Node
{
int data;
Node next;
public Node()
{
this.next=null;
}
public Node(int data)
{
this.data=data;
this.next=null;
}
}*/
public class ReverseList
{
// Function to print the List
public static void print(Node start)
{
Node temp=start;
while(temp!=null)
{
System.out.print(temp.data+" ");
temp=temp.next;
}
System.out.println();
}
// Head of Reversed list will be stored in this variable
public static Node head;
// Function to reverse a Linked List recursively
public static Node reverseRecursively(Node start)
{
if(start==null)
return null;
helper(start);
return head;
}
// Helper function for reversing the list
public static void helper(Node start)
{
if(start.next==null)
{
// This is the Last node of the list
// Make head point to last node of the list
head=start;
return ;
}
// Recursively calling helper to reach last node
helper(start.next);
// For the first time q is the last Node and start is second last Node
Node q=start.next;
// Make last Node point to second last
q.next=start;
// Make second last node null
start.next=null;
}
// Function to reverse List iteratively
public static Node reverse(Node start)
{
if(start==null)
return null;
// curr - To store the current Node
Node curr=start;
// prev - To store the previous Node
Node prev=null;
// NEXT - To store the next variabe in the node
Node NEXT;
while(curr!=null)
{
// Storing the next Node
NEXT=curr.next;
// Changing the link of a node to point to its previous node
curr.next=prev;
// Making previous node the current node
prev=curr;
// Current is now moving forward
curr=NEXT;
}
// prev is the last Node. Make the start point to prev
start=prev;
return start;
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
Node A=new Node(1);
A.next=new Node(2);
A.next.next=new Node(3);
A.next.next.next=new Node(4);
A.next.next.next.next=new Node(5);
A.next.next.next.next.next=new Node(6);
print(A);
//print(reverseRecursively(A));
print(reverse(A));
// Address of A is changed
print(A);
}
}
| true |
e03ecff5287f305a4b9793e2ad22a9f6c843e51b | Java | MoezAbid/Thinklance-pidev-java | /src/com/thinklance/pidev/GUI/InscriptionController.java | UTF-8 | 10,544 | 1.984375 | 2 | [
"MIT"
] | permissive | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.thinklance.pidev.GUI;
import com.thinklance.pidev.Service.Impl.UserService;
import com.thinklance.pidev.entities.User;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javafx.event.ActionEvent;
import javafx.scene.control.TextField;
import javafx.scene.control.Tooltip;
import javafx.scene.input.KeyEvent;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXPasswordField;
import com.jfoenix.controls.JFXRadioButton;
import com.jfoenix.controls.JFXTextField;
import com.jfoenix.validation.RequiredFieldValidator;
import com.thinklance.pidev.Utils.Section;
import com.thinklance.pidev.Utils.SectionManager;
import com.thinklance.pidev.Utils.UserManager;
import com.thinklance.pidev.Service.Impl.EmailService;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.animation.Interpolator;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.control.Alert;
import javafx.scene.control.Label;
import javafx.scene.control.ToggleGroup;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Window;
import javafx.util.Duration;
/**
* FXML Controller class
*
* @author ASUS
*/
public class InscriptionController implements Initializable {
private int verifData = 0;
@FXML
private AnchorPane anchorMere;
@FXML
private AnchorPane anchorPane;
@FXML
private JFXTextField emailText;
@FXML
private JFXPasswordField passwordText;
@FXML
private JFXButton btn_signUp;
@FXML
private JFXPasswordField passwordVerifText;
@FXML
private JFXTextField nomText;
@FXML
private JFXTextField prenomText;
@FXML
private JFXRadioButton roleEmployeur;
@FXML
private JFXRadioButton roleFreelancer;
@FXML
private Label labelStatus;
@FXML
private Label lblLogin;
ToggleGroup groupe = new ToggleGroup();
String role = "";
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
Pattern p = Pattern.compile("[a-zA-Z0-9][a-zA-Z0-9._]*@[a-zA-Z0-9]+([.][a-zA-Z]+)+");
Matcher m = p.matcher(emailText.getText());
roleEmployeur.setToggleGroup(groupe);
roleFreelancer.setToggleGroup(groupe);
if (roleEmployeur.isSelected()) {
role = "EMPLOYEUR";
}
if (roleFreelancer.isSelected()) {
role = "FREELANCER";
}
if (!nomText.getText().isEmpty()) {
nomText.getStyleClass().remove("alert-danger");
nomText.setTooltip(null);
} else {
RequiredFieldValidator validator = new RequiredFieldValidator();
validator.setMessage("Saisir un nom valide!");
nomText.getValidators().add(validator);
System.out.println("oui");
nomText.focusedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
if (!newValue) {
System.out.println("non");
nomText.validate();
}
}
});
}
if (!prenomText.getText().isEmpty()) {
prenomText.getStyleClass().remove("alert-danger");
prenomText.setTooltip(null);
} else {
RequiredFieldValidator validator = new RequiredFieldValidator();
validator.setMessage("Saisir un Pénom valide!");
prenomText.getValidators().add(validator);
prenomText.focusedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
if (!newValue) {
prenomText.validate();
}
}
});
}
if (!emailText.getText().isEmpty() && m.find() && m.group().equals(emailText.getText())) {
emailText.getStyleClass().remove("alert-danger");
emailText.setTooltip(null);
} else {
RequiredFieldValidator validator = new RequiredFieldValidator();
validator.setMessage("Saisir un email valide!");
emailText.getValidators().add(validator);
emailText.focusedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
if (!newValue) {
emailText.validate();
}
}
});
}
if (!passwordText.getText().isEmpty()) {
passwordText.getStyleClass().remove("alert-danger");
passwordText.setTooltip(null);
} else {
RequiredFieldValidator validator = new RequiredFieldValidator();
validator.setMessage("Saisir un mot de passe valide!");
passwordText.getValidators().add(validator);
passwordText.focusedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
if (!newValue) {
passwordText.validate();
}
}
});
}
if ((passwordVerifText.getText().equals(passwordText.getText()) == true) && !passwordVerifText.getText().isEmpty()) {
passwordVerifText.getStyleClass().remove("alert-danger");
passwordVerifText.setTooltip(null);
} else {
RequiredFieldValidator validator = new RequiredFieldValidator();
validator.setMessage("Les mots de passe ne correspondent pas!");
passwordVerifText.getValidators().add(validator);
passwordVerifText.focusedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
if (!newValue) {
passwordVerifText.validate();
}
}
});
}
}
public boolean verifDataEntered(KeyEvent event) {
return true;
}
public boolean verifDataEntered() {
Pattern p = Pattern.compile("[a-zA-Z0-9][a-zA-Z0-9._]*@[a-zA-Z0-9]+([.][a-zA-Z]+)+");
Matcher m = p.matcher(emailText.getText());
boolean result;
if (!nomText.getText().isEmpty()) {
if (!prenomText.getText().isEmpty()) {
if (!emailText.getText().isEmpty() && m.find() && m.group().equals(emailText.getText())) {
if (!passwordText.getText().isEmpty()) {
if ( (passwordVerifText.getText().equals(passwordText.getText()) == true) && !passwordVerifText.getText().isEmpty()) {
result= true ;
} else {
result= false;
}
} else {
result= false;
}
} else {
result= false;
}
} else {
result= false;
}
} else {
result= false;
}
return result;
}
@FXML
private void createaccount(MouseEvent event) {
User user = new User();
System.out.println("aaaaaaaaa"+verifDataEntered());
if (verifDataEntered()) {
labelStatus.setText("Votre compte est créer merci de valider votre compte par email");
labelStatus.getStyleClass().remove("alert-danger");
labelStatus.getStyleClass().add("alert-success");
btn_signUp.setDisable(false);
UserService userDAO = new UserService();
Section section = new Section(true,emailText.getText());
SectionManager.save(section);
user.setNom(nomText.getText());
user.setPrenom(prenomText.getText());
user.setEmail(emailText.getText());
user.setPassword(passwordText.getText());
user.setRoles(role);
UserManager.save(user);
if (userDAO.addUser(user, emailText.getText())) {
EmailService em = new EmailService();
try {
em.SendConfirmationEmail(user);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
} else {
labelStatus.setText("Ce compte existe Déja!");
labelStatus.getStyleClass().add("alert-danger");
//
}
} else {
labelStatus.setText("Verifiez les données saisies!");
labelStatus.getStyleClass().add("alert-danger");
}
}
@FXML
private void login(MouseEvent event) throws IOException {
Parent root = FXMLLoader.load(getClass().getResource("Login.fxml"));
Timeline timeline = new Timeline();
KeyValue keyvalue = new KeyValue(root.translateYProperty(), 0, Interpolator.EASE_IN);
KeyFrame keyframe = new KeyFrame(Duration.seconds(2), keyvalue);
anchorMere.getChildren().add(root);
timeline.getKeyFrames().add(keyframe);
timeline.play();
timeline.setOnFinished(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event5) {
anchorMere.getChildren().remove(anchorPane);
}
});
}
}
| true |
71463a999400bf961287de8bac408069071ed258 | Java | annbumagina/testcontainers | /stock-exchange/src/main/java/ru/annbumagina/dao/BourseInMemoryDao.java | UTF-8 | 1,782 | 2.796875 | 3 | [] | no_license | package ru.annbumagina.dao;
import org.springframework.stereotype.Component;
import ru.annbumagina.model.Company;
import java.util.HashMap;
import java.util.Map;
@Component
public class BourseInMemoryDao implements BourseDao {
private Map<String, Company> companies = new HashMap<>();
public BourseInMemoryDao() {}
@Override
public boolean addCompany(String name, int shares, double price) {
if (!companyExists(name)) {
companies.put(name, new Company(name, shares, price));
return true;
}
return false;
}
@Override
public boolean changePrice(String name, double price) {
if (companyExists(name)) {
Company company = companies.get(name);
company.setPrice(price);
return true;
}
return false;
}
@Override
public double getPrice(String name) {
return companies.get(name).getPrice();
}
@Override
public int countShares(String name) {
return companies.get(name).getCnt();
}
@Override
public boolean buyShares(String name, int cnt) {
if (companyExists(name)) {
Company company = companies.get(name);
if (company.getCnt() < cnt)
return false;
company.setCnt(company.getCnt() - cnt);
return true;
}
return false;
}
@Override
public boolean sellShares(String name, int cnt) {
if (companyExists(name)) {
Company company = companies.get(name);
company.setCnt(company.getCnt() + cnt);
return true;
}
return false;
}
@Override
public boolean companyExists(String name) {
return companies.containsKey(name);
}
}
| true |
b20df3fb676969ec010adbab2f506c15a700ad5c | Java | Rachel-hsw/ResManagerClient | /src/com/resmanager/client/home/AdViewPagerAdapter.java | UTF-8 | 1,995 | 2.203125 | 2 | [] | no_license | /**
* Copyright (C) 2014 XUNTIAN NETWORK
*
*
* @className:com.xtwl.jy.client.adapter.AdViewPagerAdapter
* @description:广告轮播Viewpager adapter
*
* @version:v1.0.0
* @author:shenyang
*
* Modification History:
* Date Author Version Description
* -----------------------------------------------------------------
* 2014-10-10 shenyang v1.0.0 create
*
*
*/
package com.resmanager.client.home;
import java.util.List;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
public class AdViewPagerAdapter extends PagerAdapter {
private List<View> adViews;
// 构造方法传参
public AdViewPagerAdapter(List<View> adViews) {
this.adViews = adViews;
}
@Override
public int getItemPosition(Object object) {
return super.getItemPosition(object);
}
/**
*
* @Description:获取某个View
* @param pos
* @return
* @version:v1.0
* @author:ShenYang
* @date:2015-4-22 上午9:43:28
*/
public View getItemView(int pos) {
return adViews.get(pos);
}
// 获取数据数量
@Override
public int getCount() {
return adViews.size(); // 显示内容的个数
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
@Override
public Object instantiateItem(View arg0, int arg1) {
((ViewPager) arg0).addView(adViews.get(arg1), 0);
return adViews.get(arg1); // 预加载下一个View
}
@Override
public void finishUpdate(View arg0) {
}
@Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView(adViews.get(arg1)); // 删除View
}
@Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {
}
@Override
public Parcelable saveState() {
return null;
}
@Override
public void startUpdate(View arg0) {
}
}
| true |
4ac35320d2e4c86e361cfec96761fa44342f377e | Java | iddi/oocsi-web | /app/model/clients/HeyOOCSIClient.java | UTF-8 | 9,211 | 2.25 | 2 | [
"BSD-3-Clause",
"MIT"
] | permissive | package model.clients;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.inject.Singleton;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.collect.Multimap;
import com.google.common.collect.MultimapBuilder;
import nl.tue.id.oocsi.server.OOCSIServer;
import nl.tue.id.oocsi.server.model.Client;
import nl.tue.id.oocsi.server.protocol.Message;
import play.libs.Json;
@Singleton
public class HeyOOCSIClient extends Client {
final private OOCSIServer server;
private Map<String, OOCSIDevice> clients;
@Inject
public HeyOOCSIClient(OOCSIServer server) {
super("heyOOCSIClient", server.getChangeListener());
this.server = server;
this.clients = new HashMap<>();
server.addClient(this);
server.subscribe(this, "heyOOCSI!");
}
@Override
public void disconnect() {
server.removeClient(this);
}
@Override
public boolean isConnected() {
return true;
}
@Override
public void ping() {
// do nothing
}
@Override
public void pong() {
// do nothing
}
@Override
public long lastAction() {
return System.currentTimeMillis();
}
/**
* parse the heyOOCSI! message and extract devices and their components
*
*/
@Override
public void send(Message event) {
// read and parse heyOOCSI message
if (event.getRecipient().equals("heyOOCSI!")) {
synchronized (clients) {
event.data.forEach((k, v) -> {
if (v instanceof ObjectNode) {
ObjectNode on = ((ObjectNode) v);
// seems we have an object, let's parse it
OOCSIDevice od = new OOCSIDevice();
od.name = k;
od.deviceId = on.at("/properties/device_id").asText("");
on.at("/components").fields().forEachRemaining(e -> {
DeviceEntity dc = new DeviceEntity();
dc.name = e.getKey();
JsonNode value = e.getValue();
dc.channel = value.get("channel_name").asText("");
dc.type = value.get("type").asText("");
dc.icon = value.get("icon").asText("");
// retrieve default value or state which are mutually exclusive
if (value.has("value")) {
dc.value = value.get("value").asText();
} else if (value.has("state")) {
dc.value = value.get("state").asText();
}
od.components.add(dc);
});
on.at("/location").fields().forEachRemaining(e -> {
if (e.getValue().isArray()) {
Float[] locationComponents = new Float[2];
locationComponents[0] = new Float(((ArrayNode) e.getValue()).get(0).asDouble());
locationComponents[1] = new Float(((ArrayNode) e.getValue()).get(1).asDouble());
od.locations.put(e.getKey(), locationComponents);
}
});
on.at("/properties").fields().forEachRemaining(e -> {
od.properties.put(e.getKey(), e.getValue().asText());
});
// check contents of device
// then add to clients
clients.put(k, od);
}
});
}
} else {
if (event.data.containsKey("clientHandle")) {
String clientHandle = (String) event.data.get("clientHandle");
if (clients.containsKey(clientHandle)) {
OOCSIDevice od = clients.get(clientHandle);
Client c = server.getClient(event.getSender());
if (c != null) {
c.send(new Message(token, event.getSender()).addData("clientHandle", clientHandle)
.addData("location", od.serializeLocations())
.addData("components", od.serializeComponents())
.addData("properties", od.serializeProperties()));
}
}
} else if (event.data.containsKey("x") && event.data.containsKey("y")
&& event.data.containsKey("distance")) {
try {
final float x = ((Number) event.data.get("x")).floatValue();
final float y = ((Number) event.data.get("y")).floatValue();
final float distance = ((Number) event.data.get("distance")).floatValue();
// check if we need to truncate the client list, according to the "n closest clients"
final int closest;
if (event.data.containsKey("closest")) {
closest = ((Number) event.data.get("closest")).intValue();
} else {
closest = 100;
}
// build list of all client within given distance
Map<Double, String> clientNames = new HashMap<>();
clients.values().stream().forEach(od -> {
od.locations.entrySet().forEach(loc -> {
Float[] location = loc.getValue();
double dist = Math.hypot(Math.abs(location[0] - x), Math.abs(location[1] - y));
if (dist < distance) {
clientNames.put(dist, od.deviceId);
}
});
});
// create sorted list of clients, potentially truncated by "closest"
List<String> cns = clientNames.entrySet().stream().sorted(Map.Entry.comparingByKey()).limit(closest)
.map(e -> e.getValue()).collect(Collectors.toList());
// assemble the clients within distance from reference point and send back
Client c = server.getClient(event.getSender());
if (c != null) {
c.send(new Message(token, event.getSender()).addData("x", x).addData("y", y)
.addData("distance", distance).addData("clients", cns.toArray(new String[] {})));
}
} catch (NumberFormatException | ClassCastException e) {
// could not parse the coordinates or distance, do nothing
}
} else if (event.data.containsKey("location")) {
String location = ((String) event.data.get("location")).trim();
Set<String> clientNames = new HashSet<>();
clients.values().stream().forEach(od -> {
od.locations.keySet().forEach(loc -> {
if (loc.equalsIgnoreCase(location)) {
clientNames.add(od.deviceId);
}
});
});
// assemble the clients within given location and send back
Client c = server.getClient(event.getSender());
if (c != null) {
c.send(new Message(token, event.getSender()).addData("location", location).addData("clients",
clientNames.toArray(new String[] {})));
}
}
}
}
/**
* remove devices that are not in the current server client list anymore
*
*/
private void purgeStaleClients() {
synchronized (clients) {
clients = clients.values().stream()
.filter(od -> this.server.getClients().stream().anyMatch(c -> c.getName().equals(od.deviceId))
|| !od.purgeable())
.collect(Collectors.toMap(od -> od.name, od -> od));
}
}
/**
* retrieve devices mapped by location
*
* @return
*/
public Multimap<String, OOCSIDevice> devicesByLocation() {
purgeStaleClients();
Multimap<String, OOCSIDevice> locationsMappedDevices = MultimapBuilder.hashKeys().linkedListValues().build();
clients.values().stream().forEach(
od -> od.locations.entrySet().stream().forEach(loc -> locationsMappedDevices.put(loc.getKey(), od)));
return locationsMappedDevices;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public String labelLocation(String location) {
return "📍 " + location;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static class OOCSIDevice {
public String name;
public String deviceId;
public Map<String, Float[]> locations = new HashMap<>();
public List<DeviceEntity> components = new LinkedList<>();
public Map<String, String> properties = new HashMap<>();
public String icon;
private long purgeTimestamp = -1;
public boolean purgeable() {
if (purgeTimestamp == -1) {
purgeTimestamp = System.currentTimeMillis();
}
return System.currentTimeMillis() - purgeTimestamp > 3600 * 1000;
}
@Override
public String toString() {
return "📦 " + name;
}
public ObjectNode serializeLocations() {
ObjectNode locs = Json.newObject();
locations.entrySet().stream().forEach(l -> {
ArrayNode an = locs.putArray(l.getKey());
an.add(l.getValue()[0]);
an.add(l.getValue()[1]);
});
return locs;
}
public ObjectNode serializeComponents() {
ObjectNode locs = Json.newObject();
components.stream().forEach(de -> {
ObjectNode on = locs.putObject(de.name);
on.put("channel_name", de.channel);
on.put("default_value", de.value);
on.put("type", de.type);
on.put("icon", de.icon);
});
return locs;
}
public ObjectNode serializeProperties() {
ObjectNode props = Json.newObject();
properties.entrySet().stream().forEach(de -> {
props.put(de.getKey(), de.getValue());
});
return props;
}
}
public static class DeviceEntity {
public String name;
public String channel;
public String value;
public String type;
public String icon;
@Override
public String toString() {
switch (type) {
case "switch":
return "🎚 " + name;
case "number":
return "🧮 " + name;
case "sensor":
case "binary_sensor":
return "🩺 " + name;
case "light":
return "💡 " + name;
default:
return name;
}
}
}
}
| true |
1ff4233c4732eb84e1efc2f3d3fcfa0244ca599c | Java | hibouhome/hibouhome-stockists | /xml/src/main/java/com/hibouhome/stockists/xml/ApplicationError.java | UTF-8 | 526 | 2.40625 | 2 | [] | no_license | package com.hibouhome.stockists.xml;
/**
* Represents an unrecoverable application error
*
* @author Jonathan Wright
*
*/
public class ApplicationError extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
* Constructs a new application error with the specified detail message and cause.
*
* @param message the error message
* @param cause the Throwable cause
*/
public ApplicationError(final String message, final Throwable cause) {
super(message, cause);
}
}
| true |
84beec6be4c60767fe4415395189d4f342698545 | Java | marcus-secato-symphony/symphony-api-client-java | /symphony-bdk-spring/symphony-bdk-core-spring-boot-starter/src/test/java/com/symphony/bdk/spring/slash/SlashAnnotationProcessorTest.java | UTF-8 | 1,372 | 2.09375 | 2 | [
"MIT"
] | permissive | package com.symphony.bdk.spring.slash;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.symphony.bdk.core.activity.ActivityRegistry;
import com.symphony.bdk.core.activity.command.SlashCommand;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
/**
* This test class ensures that methods annotated by {@link com.symphony.bdk.spring.annotation.Slash} annotation are
* registered withing the {@link com.symphony.bdk.core.activity.ActivityRegistry}.
*/
@SpringBootTest
@ExtendWith(SpringExtension.class)
public class SlashAnnotationProcessorTest {
@Autowired
private ActivityRegistry activityRegistry;
@Test
void slashMethodShouldBeRegistered() {
// 2 activities should be registered: slash cmd and form reply
assertThat(this.activityRegistry.getActivityList().size()).isEqualTo(2);
assertTrue(this.activityRegistry.getActivityList().stream().anyMatch(a -> a.getClass().equals(SlashCommand.class)));
assertTrue(this.activityRegistry.getActivityList().stream().anyMatch(a -> a.getClass().equals(TestFormReplyActivity.class)));
}
}
| true |
f72465370c59b70e9134b7e7d9072b1d15e16dee | Java | beyondray/MicPlayer | /app/src/main/java/com/beyondray/micplayer/Player/PlayList.java | UTF-8 | 2,136 | 3.03125 | 3 | [] | no_license | package com.beyondray.micplayer.Player;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* Created by beyondray on 2017/11/10.
*/
public class PlayList {
public enum PlayMode{
CYCLE, RANDOM, LOOP
}
public List<Music> queue = new ArrayList<Music>();
int queIdx = 0;
PlayMode playMode = PlayMode.CYCLE;
public PlayList(){};
public PlayList(List<Music> q, int idx)
{
queue = q;
queIdx = idx;
}
public int contains(Music m){
for(int i = 0; i < queue.size(); i++){
if(queue.get(i).get(Music.Attr.ID).equals(m.get(Music.Attr.ID))){
return i;
}
}
return -1;
}
public void add(Music m)
{
int i = contains(m);
if(i == -1)queue.add(m);
}
public void remvoe(Music m)
{
int i = contains(m);
if(i != -1)queue.remove(i);
}
public int size(){
return queue.size();
}
public void setPlayMode(PlayMode mode){ playMode = mode;}
public int getPlayIdx() { return queIdx; }
public void setPlayIdx(int idx){ queIdx = idx;}
public void fitPlayIdx() {
queIdx = queIdx >= queue.size() ? queue.size()-1 : (queIdx < 0 ? 0 : queIdx);
}
private int nextIdx(int i) {
int _t = (queIdx + i) % queue.size();
return _t >= 0 ? _t : _t + queue.size();
}
private int randomIdx() {
int idx;
do{
idx = new Random().nextInt(queue.size());
}while (idx == queIdx);
return idx;
}
public Music getNextMusic(int gap)
{
if(queue.isEmpty())return null;
switch (playMode)
{
case CYCLE: queIdx = nextIdx(gap);break;
case RANDOM: queIdx = randomIdx();break;
case LOOP: queIdx = nextIdx(gap);break;
}
return queue.get(queIdx);
}
public Music getCurMusic()
{
return queue.get(queIdx);
}
public Music getPrevMusic(){
return getNextMusic(-1);
}
public Music getNextMusic(){
return getNextMusic(1);
}
}
| true |
2fab1782f2969a96eb69086f340e59985d9b9aee | Java | okboy5555/MCBBS-Client | /native/desktop/javaServer/src/net/mcbbs/client/main/client/game/authentication/IAuthController.java | UTF-8 | 1,306 | 1.796875 | 2 | [
"Apache-2.0"
] | permissive | /*
Copyright 2019 langyo<langyo.china@gmail.com> and contributors
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 net.mcbbs.client.main.client.game.authentication;
import com.google.gson.JsonObject;
public interface IAuthController {
JsonObject authenticate(String name, int version, String username, String password, String clientToken, boolean requestUser) throws AuthenticationException;
JsonObject refresh(String accessToken, String clientToken, String id, String name, boolean requestUser) throws AuthenticationException;
boolean validate(String accessToken, String clientToken) throws AuthenticationException;
void signout(String username, String password) throws AuthenticationException;
void invalidate(String accessToken, String clientToken) throws AuthenticationException;
}
| true |
dc43f6296ad7b6a9f4e53dddb3f5358807914adb | Java | jgj1018/TIL | /Sources/JPA/src/main/java/com/orailly/persistance/entities/Rank.java | UTF-8 | 127 | 1.875 | 2 | [] | no_license | package com.orailly.persistance.entities;
public enum Rank {
ENSIGN, LIEUTENENT, COMMANDER, CAPTAIN, COMMODORE, ADMIRAL
}
| true |
f8d5d52a8670088afcf3df0376af18daa4d72225 | Java | xiaoqiangjava/netty-demo | /src/main/java/com/xq/learn/consumer/ResultHandler.java | UTF-8 | 564 | 2.484375 | 2 | [] | no_license | package com.xq.learn.consumer;
import java.util.concurrent.CountDownLatch;
public class ResultHandler
{
private String result;
private volatile boolean isSuccess = false;
CountDownLatch countDownLatch = new CountDownLatch(1);
public String getResponse() throws InterruptedException {
while (!isSuccess) {
countDownLatch.await();
}
return result;
}
public void setResponse(String response) {
this.result = response;
this.isSuccess = true;
countDownLatch.countDown();
}
}
| true |
3849c8f91c25c63c85a955cb503cae14c89c52a0 | Java | 1946472806/springboot | /shiro/src/main/java/org/sang/shiro/service/UserService.java | UTF-8 | 407 | 1.890625 | 2 | [] | no_license | package org.sang.shiro.service;
import org.sang.shiro.bean.UserBean;
import org.sang.shiro.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService {
@Autowired
UserMapper userMapper;
public List<UserBean> getUser(){
return userMapper.getUser();
}
}
| true |
087a23a97f4e80d33a086bbd2821164b196abbfc | Java | jessejgray/BakingApp | /app/src/main/java/com/example/android/bakingapp/utils/RecipeUtils.java | UTF-8 | 2,481 | 2.578125 | 3 | [] | no_license | package com.example.android.bakingapp.utils;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.StyleSpan;
import java.util.ArrayList;
public class RecipeUtils {
private static final String CARRIAGE_RETURN = "\n";
private static final String PREF_KEY = "shared-pref";
private static final String PREF_RECIPE_NAME_KEY = "pref-recipe-name";
private static final String PREF_INGREDIENTS_KEY = "pref-recipe-ingredients";
public static final String VIDEO_EXT = ".mp4";
public static String formatIngredients(ArrayList<Ingredient> ingredients) {
SpannableStringBuilder ssb = new SpannableStringBuilder();
if (ingredients != null && ingredients.size() > 0) {
for (Ingredient ingredient : ingredients) {
ssb.append(ingredient.getIngredient().toLowerCase());
int start = ssb.length();
ssb.append(" (");
ssb.append(ingredient.getQuantity().toString());
ssb.append(" ");
ssb.append(ingredient.getMeasure().toLowerCase());
ssb.append(")");
ssb.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), start, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
ssb.append(CARRIAGE_RETURN);
ssb.append(CARRIAGE_RETURN);
}
}
return ssb.toString();
}
public static String getPrefKey() {
return PREF_KEY;
}
public static String getPrefRecipeNameKey() {
return PREF_RECIPE_NAME_KEY;
}
public static String getPrefIngredientsKey() {
return PREF_INGREDIENTS_KEY;
}
public static String getVideoUrl(Step step) {
String videoUrl = null;
if (!step.getVideoUrl().equals("")) {
videoUrl = step.getVideoUrl();
} else if (!step.getThumbnailUrl().equals("") && step.getThumbnailUrl().contains(VIDEO_EXT)) {
videoUrl = step.getThumbnailUrl();
}
return videoUrl;
}
public static String formatDescription(Step step) {
String description = step.getDescription();
String replaceString;
if (step.getDescription().indexOf(".") > 0) {
replaceString = step.getDescription().substring(0, step.getDescription().indexOf(".") + 1);
description = step.getDescription().replace(replaceString, "").trim();
}
return description;
}
}
| true |
feb917174661739cf81856120698b802770d22bf | Java | bryantwilliam/ShiftKill | /src/main/java/com/gmail/gogobebe2/shiftkill/kits/Milestone5Kit.java | UTF-8 | 434 | 2.28125 | 2 | [] | no_license | package com.gmail.gogobebe2.shiftkill.kits;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
public class Milestone5Kit extends Kit {
@Override
protected void initItems() {
getITEMS().add(new ItemStack(Material.IRON_INGOT, 2));
}
@Override
protected String initName() {
return ChatColor.GRAY + "" + ChatColor.BOLD + "5 Kill Milestone Kit";
}
}
| true |
600ca1ddbb23a83deeeb52e26ad4bb4984493887 | Java | martinDP25/Test | /MARNS/src/Test.java | UTF-8 | 146 | 2.078125 | 2 | [] | no_license |
public class Test
{
public static void main(String[] args)
{
Bricks bricksObject = new Bricks();
bricksObject.takeMyBrick();
}
}
| true |
01d8cc55034822b343d712e8038425380fc4ec97 | Java | gugu-lee/as | /as/src/main/java/net/x_talker/as/im/container/MessageContentFileContainer.java | UTF-8 | 1,789 | 2.375 | 2 | [] | no_license |
package net.x_talker.as.im.container;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.log4j.Logger;
import net.x_talker.as.common.vo.BizConsts;
import net.x_talker.as.im.container.consumer.MessageContentFileConsumer;
import net.x_talker.as.im.container.entity.XTalkerSipMsgOpFile;
import net.x_talker.as.im.ha.HAQueue;
/**
* 【消息内容写入文件保存的缓存容器】
*
* @version
* @author xubo 2014-4-21 上午10:21:26
*
*/
public class MessageContentFileContainer extends HAQueue<XTalkerSipMsgOpFile> {
private static MessageContentFileContainer instance = new MessageContentFileContainer(
BizConsts.MESSAGE_CONTENT_FILE_CONTAINER);
private Logger logger = Logger.getLogger(MessageContentFileContainer.class);
/**
* MessageContentFileContainer 构造器 【请在此输入描述文字】
*
* @param queueName
*/
protected MessageContentFileContainer(String queueName) {
super(queueName);
ExecutorService pool = Executors.newCachedThreadPool();
for (int i = 0; i < 5; i++) {
logger.info("start message content file consumer.....");
MessageContentFileConsumer t = new MessageContentFileConsumer();
pool.execute(t);
}
}
/**
* 【请在此输入描述文字】
*
* (non-Javadoc)
*
* @see net.x_talker.as.im.ha.HAQueue#initQueue()
*/
@Override
protected void initQueue() {
super.queue = new ConcurrentLinkedQueue<XTalkerSipMsgOpFile>();
}
public static MessageContentFileContainer getInstance() {
return instance;
}
public void addMsgToWriteFile(XTalkerSipMsgOpFile sipMsgOpFile) {
this.addItem(sipMsgOpFile);
}
public XTalkerSipMsgOpFile getMsgToWriteFile() {
return this.pollItem();
}
}
| true |
a16c3dea23a1345f73e353b017bc2332a57eddbc | Java | ThanhxNguyen/wallet-movies | /app/src/main/java/com/nguyen/paul/thanh/walletmovie/utilities/Utils.java | UTF-8 | 1,785 | 2.265625 | 2 | [] | no_license | package com.nguyen.paul.thanh.walletmovie.utilities;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.support.design.widget.Snackbar;
import android.support.v4.content.res.ResourcesCompat;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import com.nguyen.paul.thanh.walletmovie.R;
/**
* Utility class provide a range of helper classes
*/
public class Utils {
public static Snackbar createSnackBar(Resources resources, View view, String message) {
int snackBarMessageColor = ResourcesCompat.getColor(resources, R.color.colorPrimaryText, null);
int snackBarActionBtnColor = ResourcesCompat.getColor(resources, R.color.colorAccent, null);
return createSnackBar(resources, view, message, snackBarMessageColor, snackBarActionBtnColor);
}
public static Snackbar createSnackBar(Resources resources, View view, String message, int messageColor, int actionBtnColor) {
Snackbar snackbar = Snackbar.make(view, message, Snackbar.LENGTH_LONG);
//set snackbar message color
snackbar.setActionTextColor(messageColor);
//set snackbar action button color
View snackbarView = snackbar.getView();
TextView textView = (TextView) snackbarView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(actionBtnColor);
textView.setTypeface(null, Typeface.BOLD);
return snackbar;
}
public static void hideKeyboard(Context context, View view) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
| true |
e3baebf74dbf5efdf1cae33f23cf080deb051b87 | Java | ShivamBansal0312/Test | /BankAccount/src/main/java/com/cognizant/account/validation/Validate.java | UTF-8 | 146 | 1.820313 | 2 | [] | no_license | package com.cognizant.account.validation;
public class Validate {
public static boolean check(String data) {
return data.equals("");
}
}
| true |
89e008839e6e94f73ebfe345fa2a1035e59b4efd | Java | l1sss/sandbox | /job/activemqexample/src/main/java/ru/slisenko/activemq/example/JmsProducer.java | UTF-8 | 1,223 | 2.65625 | 3 | [] | no_license | package ru.slisenko.activemq.example;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
public class JmsProducer extends Thread implements AutoCloseable {
private final static String DEF_QUEUE = "testQueue";
private final ActiveMQConnectionFactory connectionFactory;
private Connection connection;
private Session session;
private MessageProducer producer;
public JmsProducer(String url) throws JMSException {
connectionFactory = new ActiveMQConnectionFactory(url);
connection = connectionFactory.createConnection();
connection.start();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination dest = session.createQueue(DEF_QUEUE);
producer = session.createProducer(dest);
}
public void send(String text) throws JMSException {
TextMessage textMessage = session.createTextMessage();
textMessage.setText(text);
producer.send(textMessage);
}
public void close() {
if (connection != null) {
try {
connection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}
} | true |
6b9c13bac2a38088fd005b6806e0539fc6a14858 | Java | spacezyx/BookStore | /bookstore-all/bookstore_backend/src/main/java/com/reins/bookstore/serviceimpl/BookServiceImpl.java | UTF-8 | 1,320 | 2.296875 | 2 | [] | no_license | package com.reins.bookstore.serviceimpl;
import com.reins.bookstore.dao.BookDao;
import com.reins.bookstore.entity.Book;
import com.reins.bookstore.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.List;
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookDao bookDao;
@Override
public Book findBookById(Integer id){
return bookDao.findOne(id);
}
@Override
public List<Book> findBookByName(String partname){
return bookDao.findBookByName(partname);
}
@Override
public List<Book> getBooks() {
return bookDao.getBooks();
}
@Override
public void deleteOne(Integer id){
bookDao.deleteOne(id);
}
@Override
public void addNewBook(String isbn, String title, String type, String author, BigDecimal price, String description, Integer inventory, String image1) {
bookDao.addNewBook(isbn,title,type,author,price,description,inventory,image1);
}
@Override
public void modifyBook(Integer id, String isbn, String title, String author, Integer inventory, String image1) {
bookDao.modifyBook(id,isbn,title,author,inventory,image1);
}
}
| true |
a7af82b5aee7eb722c6a5596b45cb7973cc3284d | Java | rabinGurung/Toilet_Real_admin | /app/src/main/java/com/example/toilet_real_admin/Dashboard.java | UTF-8 | 3,810 | 2.109375 | 2 | [] | no_license | package com.example.toilet_real_admin;
import android.os.Bundle;
import android.os.StrictMode;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.anychart.AnyChart;
import com.anychart.AnyChartView;
import com.anychart.chart.common.dataentry.DataEntry;
import com.anychart.chart.common.dataentry.ValueDataEntry;
import com.anychart.charts.Cartesian;
import com.anychart.core.cartesian.series.Column;
import com.anychart.enums.Anchor;
import com.anychart.enums.HoverMode;
import com.anychart.enums.Position;
import com.anychart.enums.TooltipPositionMode;
import com.example.toilet_real_admin.Connection.API_CALL;
import com.example.toilet_real_admin.Interface.Visitors;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
public class Dashboard extends AppCompatActivity {
private int jan_count = 0, feb_count = 0, dec_count = 0;
private Retrofit retrofit;
private Visitors visitors;
List<DataEntry> data = new ArrayList<>();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dashboard);
retrofit = API_CALL.getAPI_Instance().getRetrofit();
visitors = retrofit.create(Visitors.class);
AnyChartView anyChartView = findViewById(R.id.any_chart_view);
anyChartView.setProgressBar(findViewById(R.id.progress_bar));
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
getData(anyChartView);
} catch (IOException e) {
e.printStackTrace();
}
Cartesian cartesian = AnyChart.column();
Column column = cartesian.column(data);
column.tooltip()
.titleFormat("{%X}")
.position(Position.CENTER_BOTTOM)
.anchor(Anchor.CENTER_BOTTOM)
.offsetX(0d)
.offsetY(5d)
.format("${%Value}{groupsSeparator: }");
cartesian.animation(true);
cartesian.title("Count of Public toilet used through app by month");
cartesian.yScale().minimum(0d);
cartesian.yAxis(0).labels().format("${%Value}{groupsSeparator: }");
cartesian.tooltip().positionMode(TooltipPositionMode.POINT);
cartesian.interactivity().hoverMode(HoverMode.BY_X);
cartesian.xAxis(0).title("Month");
cartesian.yAxis(0).title("Count");
anyChartView.setChart(cartesian);
}
private void getData(AnyChartView anyChartView ) throws IOException {
Call<ResponseBody> callDec = visitors.getDec();
Response<ResponseBody> response2 = callDec.execute();
String str = response2.body().string();
String str1 = str.substring(1,str.length()-1);
int dec_count1 = Integer.parseInt(str1);
data.add(new ValueDataEntry("Dec", dec_count1));
Call<ResponseBody> callJan = visitors.getJan();
Response<ResponseBody> response = callJan.execute();
String jan = response.body().string();
String jan1 = jan.substring(1,jan.length()-1);
int jan_count1 = Integer.parseInt(jan1);
data.add(new ValueDataEntry("Jan", jan_count1));
Call<ResponseBody> callFeb = visitors.getJan();
Response<ResponseBody> response1 = callFeb.execute();
String feb = response1.body().string();
String feb1 = feb.substring(1,feb.length()-1);
int feb_count1 = Integer.parseInt(str1);
data.add(new ValueDataEntry("Feb", feb_count1));
}
}
| true |
e370cd66fa0c9b12b8c4db82ec92bc503e0daeb9 | Java | hungnguyen94/BTrouble | /src/main/java/com/sem/btrouble/controller/Level.java | UTF-8 | 4,864 | 3.0625 | 3 | [] | no_license | package com.sem.btrouble.controller;
import com.sem.btrouble.model.Room;
import com.sem.btrouble.model.Player;
import com.sem.btrouble.model.PlayerInfo;
import com.sem.btrouble.model.Bubble;
import com.sem.btrouble.model.Rope;
import com.sem.btrouble.observering.LevelObserver;
import com.sem.btrouble.observering.LevelSubject;
import org.newdawn.slick.Graphics;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* Level class.
*/
public class Level implements LevelSubject {
private Room room;
private List<Player> players;
private List<LevelObserver> observersList;
private boolean levelRunning;
private Controller mainController;
private BubbleController bubbleController;
private RopeController ropeController;
/**
* Constructor for the level class with room parameter.
* @param room Room that the level should be started with.
*/
public Level(Room room) {
this.room = room;
this.players = new CopyOnWriteArrayList<>();
this.observersList = new ArrayList<>();
this.bubbleController = new BubbleController(new CollisionHandler());
this.ropeController = new RopeController(new PowerUpController(bubbleController));
this.mainController = new BorderController(ropeController,
room.getMoveableWalls(), room.getMoveableFloors());
this.mainController.addListReference(room.getCollidablesList());
this.mainController.addListReference(players);
}
/**
* Adds a player to the level.
* And put it on the room spawn position.
* @param player Player to be added.
*/
public void addPlayer(Player player) {
player.reset();
players.add(player);
player.setX(room.getSpawnPositionX());
player.setY(room.getSpawnPositionY());
PlayerInfo.getInstance().setPlayers(players);
}
/**
* This method adds a collection of bubbles to the list.
* @param bubbles These bubbles will be added.
*/
public void addBubble(Collection<Bubble> bubbles) {
bubbleController.addBubble(bubbles);
}
/**
* Adds a rope to the ropeController.
* @param rope rope that is added.
*/
public void addRope(Rope rope) {
ropeController.addRope(rope);
}
/**
* Checks if any player in this level is alive.
* @return True if there's a player alive.
*/
private boolean playersAlive() {
for(Player player : players) {
if(player.isAlive()) {
return true;
}
}
return false;
}
/**
* Calls the move method on all objects in the level.
*/
public synchronized void moveObjects() {
mainController.update();
for(Player player : players) {
player.move();
}
notifyObserver();
}
/**
* Stops the current level.
*/
public void stop() {
levelRunning = false;
}
/**
* Starts the current level.
*/
public void start() {
levelRunning = true;
}
/**
* Check if the level is running.
* @return True if level is running.
*/
public boolean isLevelRunning() {
return levelRunning;
}
/**
* This method will lose the level.
*/
public void loseLevel() {
stop();
for(LevelObserver obj: observersList) {
obj.levelLost();
}
}
/**
* This method will win the level.
*/
public void winLevel() {
stop();
for(LevelObserver obj: observersList) {
obj.levelWon();
}
}
/**
* Register an observer to the subject.
*
* @param observer Observer to be added.
*/
@Override
public void registerObserver(LevelObserver observer) {
if(observer == null || observersList.contains(observer)) {
return;
}
observersList.add(observer);
}
/**
* Remove an observer from the observersList list.
*
* @param observer Observer to be removed.
*/
@Override
public void removeObserver(LevelObserver observer) {
observersList.remove(observer);
}
/**
* Method to notify the observersList about a change.
*/
@Override
public void notifyObserver() {
if(!playersAlive()) {
loseLevel();
}
if(bubbleController.getBubblesAmount() <= 0) {
winLevel();
}
}
/**
* Draw the object.
*
* @param graphics The graphics
*/
public void draw(Graphics graphics) {
room.draw(graphics);
mainController.draw(graphics);
for(Player player : players) {
player.draw(graphics);
}
}
}
| true |
b526807d93c37eaadc946a128c7bb23a08519b47 | Java | skaleks/JavaSchool-DT | /src/main/java/com/magenta/crud/contract/dto/ContractPageDto.java | UTF-8 | 468 | 2 | 2 | [] | no_license | package com.magenta.crud.contract.dto;
import com.magenta.crud.tariff.dto.TariffDto;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@NoArgsConstructor
public class ContractPageDto {
private ContractDto contract;
private List<TariffDto> tariffDtoList;
public ContractPageDto(ContractDto contract, List<TariffDto> tariffDtoList) {
this.contract = contract;
this.tariffDtoList = tariffDtoList;
}
}
| true |
ca1c634a906bf879f0b4ef93354d991794b55268 | Java | andreho/structs | /src/main/java/net/andreho/struct/map/ImmutableEntry.java | UTF-8 | 277 | 2.09375 | 2 | [
"Apache-2.0"
] | permissive | package net.andreho.struct.map;
import net.andreho.struct.Structure;
/**
* <br/>Created by a.hofmann on 23.01.2016.<br/>
*/
public interface ImmutableEntry<K, V> extends Structure {
/**
* @return
*/
K getKey();
/**
* @return
*/
V getValue();
}
| true |
a06086a7f1d54512966d0bf00b2ea6b0871c7066 | Java | Yixf-Self/asgbook | /src/edu/ou/asgbook/histogram/Histogram.java | UTF-8 | 3,031 | 2.90625 | 3 | [] | no_license | /**
*
*/
package edu.ou.asgbook.histogram;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import edu.ou.asgbook.core.LatLonGrid;
import edu.ou.asgbook.dataset.SurfaceAlbedo;
import edu.ou.asgbook.io.OutputDirectory;
/**
* A histogram is an empirical probability distribution.
*
* @author v.lakshmanan
*
*/
public class Histogram {
private int min;
private int incr;
private int[] hist;
/**
* Values below min are ignored but the last bin is unbounded.
*
* @param min
* @param incr
* @param nbins
*/
public Histogram(int min, int incr, int nbins) {
super();
this.min = min;
this.incr = incr;
this.hist = new int[nbins];
}
public int getMin() {
return min;
}
public int getIncr() {
return incr;
}
public int[] getHist() {
return hist;
}
public void update(LatLonGrid data) {
final int nrows = data.getNumLat();
final int ncols = data.getNumLon();
for (int i = 0; i < nrows; ++i)
for (int j = 0; j < ncols; ++j) {
int val = data.getValue(i, j);
int bin_no = getBinNumber(val, data.getMissing());
if (bin_no != -1 ){
hist[bin_no]++;
}
}
}
public int getCenterValue(int bin_no, int missing){
if (bin_no < 0){
return missing;
}
return min + bin_no*incr + incr/2;
}
/** points outside the histogram have bin number of -1 */
public int getBinNumber(int val, int missing) {
if (val != missing && val >= min) {
int bin_no = (val - min) / incr;
// last bin is unbounded
if (bin_no >= hist.length)
bin_no = hist.length - 1;
return bin_no;
}
return -1;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hist.length; ++i) {
int sval = min + i * incr;
int eval = sval + incr;
sb.append(sval);
sb.append(" ");
sb.append(eval);
sb.append(" ");
sb.append(hist[i]);
sb.append("\n");
}
return sb.toString();
}
public float[] calcProb() {
float[] prob = new float[hist.length];
int tot = 0;
for (int i = 0; i < hist.length; ++i) {
tot += hist[i];
}
if (tot > 0) {
for (int i = 0; i < hist.length; ++i) {
prob[i] = hist[i] / (float) tot;
}
}
return prob;
}
public static void main(String[] args) throws Exception {
// create output directory
File outdir = OutputDirectory.getDefault("hist");
// read input
LatLonGrid conus = SurfaceAlbedo.read(SurfaceAlbedo.CONUS, 100);
// find histogram
final int MIN = 0;
final int MAX = 30;
for (int incr = 1; incr < 10; incr += 2) {
Histogram hist = new Histogram(MIN, incr, (MAX - MIN) / incr);
hist.update(conus);
System.out.println("INCR=" + incr + " nbins=" + hist.hist.length);
System.out.println(hist);
String filename = outdir.getAbsolutePath() + "/hist_" + incr
+ ".txt";
PrintWriter writer = new PrintWriter(new FileWriter(filename));
writer.println(hist);
writer.close();
System.out.println("Wrote to " + filename);
}
}
public int getNumBins() {
return hist.length;
}
}
| true |
bcbbbdd45b136c6ce97ab5b65c6baf7902b9f1fe | Java | nipunanz/CodeBrigade | /src/library/payfine/PayFineUI.java | UTF-8 | 3,373 | 2.6875 | 3 | [] | no_license | package library.payfine;
import java.util.Scanner;
// Author : Chiranga
// Reviwer : Dilanka
// Mediator : Subhashini
public class PayFineUI {
public static enum UiState { INITIALISED, READY, PAYING, COMPLETED, CANCELLED }; // changed the variable name "uI_sTaTe" to "UiState"
private PayFineControl control; // changed the variable name "pAY_fINE_cONTROL" to "payFineControl" & "CoNtRoL" to "control"
private Scanner input;
private UiState state; // changed the variable name "uI_sTaTe" to "UiState" & "StAtE" to "state"
public PayFineUI(PayFineControl control) { // chnage "CoNtRoL" to "control"
this.control = control; // "CoNtRoL" to "control"
input = new Scanner(System.in);
state = UiState.INITIALISED; // changed variable name "uI_sTaTe" to "UiState" & "StAtE" to "state"
control.setUi(this); // changed method "SeT_uI" to "setUi"
}
public void setState(UiState state) {// changed variable name "uI_sTaTe" to "UiState" & "SeT_StAtE" to "setState"
this.state = state; // changed "StAtE" to "state"
}
public void run() { // changed "RuN" to "run"
output("Pay Fine Use Case UI\n");
while (true) {
switch (state) { // changed "StAtE" to "state"
case READY:
String memStr = input("Swipe member card (press <enter> to cancel): "); // chanaged "Mem_Str" to "memStr "
if (memStr.length() == 0) { // chanaged "Mem_Str" to "memStr "
control.cancel(); // changed "CoNtRoL" to "control" & "CaNcEl" to "cancel"
break;
}
try {
int memberId = Integer.valueOf(memStr).intValue(); // chanaged "Mem_Str" to "memStr" & "Member_ID" to "memberId"
control.cardSwiped(memberId); // changed "CoNtRoL" to "control" & "Member_ID" to "memberId" & "CaRd_sWiPeD" to "cardSwiped"
}
catch (NumberFormatException e) {
output("Invalid memberId");
}
break;
case PAYING:
double amount = 0; // changed "AmouNT" to "amount"
String amtStr = input("Enter amount (<Enter> cancels) : "); // changed "Amt_Str" to "amtStr"
if (amtStr.length() == 0) { // changed "Amt_Str" to "amtStr"
control.cancel(); // changed "CoNtRoL" to "control" & "CaNcEl" to "cancel"
break;
}
try {
amount = Double.valueOf(amtStr).doubleValue(); // changed "AmouNT" to "amount" & "Amt_Str" to "amtStr"
}
catch (NumberFormatException e) {
output("Invalid number format");
}
if (amount <= 0) { // changed "AmouNT" to "amount"
output("Amount must be positive");
break;
}
control.payFine(amount); // changed "CoNtRoL" to "control" & "AmouNT" to "amount" & "PaY_FiNe" to "payFine"
break;
case CANCELLED:
output("Pay Fine process cancelled");
return;
case COMPLETED:
output("Pay Fine process complete");
return;
default:
output("Unhandled state");
throw new RuntimeException("FixBookUI : unhandled state :" + state); // chanaged variable "StAtE" to "state"
}
}
}
private String input(String prompt) {
System.out.print(prompt);
return input.nextLine();
}
private void output(Object object) {
System.out.println(object);
}
public void display(Object object) { // changed the method name "DiSplAY" to "display"
output(object);
}
}
| true |
e7e7b645eb375e6b92a2e59ca934573979d69f1f | Java | StillWaitfull/testItSave | /src/test/java/toolkit/METHODS.java | UTF-8 | 728 | 2.59375 | 3 | [] | no_license | package toolkit;
import org.apache.http.client.methods.*;
import java.net.URI;
public enum METHODS {
GET {
@Override
public HttpRequestBase getMethod(URI uri) {
return new HttpGet(uri);
}
}, POST {
@Override
public HttpRequestBase getMethod(URI uri) {
return new HttpPost(uri);
}
}, PUT {
@Override
public HttpRequestBase getMethod(URI uri) {
return new HttpPut(uri);
}
}, DELETE {
@Override
public HttpRequestBase getMethod(URI uri) {
return new HttpDelete(uri);
}
};
public abstract HttpRequestBase getMethod(URI uri);
} | true |
3d8ff32439ac7de0d301dda1ee2d55813b4b33bd | Java | EthanDamien/JavaCodingmindsApril2021 | /animaltest/Main.java | UTF-8 | 631 | 3.5625 | 4 | [] | no_license | package animaltest;
class Main {
public static void main(String[] args) {
//You can make Animal Class and give it a name
//You can set dog name in constructor
//You can also get the name by calling getName()
// String dogname = "dog";
// String dogsound = "bark";
// System.out.println(dogname);
//System.out.println("dog");
// Animal dog = new Animal("Dog", "Bark");
// dog.getName();
// System.out.println(dog.getSound());
// System.out.println(dog.getheightplusweight());
Animal cat = new Animal("Mittens", "Meow");
cat.getName();
}
} | true |
4aa9a1cf1278daaee779bd4a26e3fc8c33f2f73f | Java | Yenaviel/NaukaJavy | /Ksiazka/Zadanie5.6/src/Zadanie.java | UTF-8 | 354 | 3.078125 | 3 | [] | no_license | import java.lang.String;
public class Zadanie {
public static void main(String[] args) {
String tabica = "Lubie Javę!";
int x = 6;
int y;
System.out.println(tabica.length());
char znak = tabica.charAt(7);
System.out.println(znak);
y = (x < 0) ? 10 : 20;
System.out.println(y);
}
}
| true |
a022cb52616e4690d6d9c7e42aa2daa70e5c3ca2 | Java | outkst/CS1530_Laboon_Chess | /src/main/java/chess/view/GameResults.java | UTF-8 | 1,761 | 2.671875 | 3 | [] | no_license | package chess;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*; // awt.* does not import Action or Event Listeners
import java.io.*;
import javax.imageio.*;
public class GameResults extends JDialog {
private Toolkit t;
private Dimension screen;
//Modify startup screen sizes
private int screenWidth = 800;
private int screenHeight = 400;
//Size adjusted to include the video
private int screenWidthVideo = 800;
private int screenHeightVideo = 800;
protected static VideoPanel video;
public GameResults() {
//Find out whether the game was won, lost, draw
//Make dialog title based on the results
JDialog dialog = new JDialog(this, "Results of the Game!");
dialog.setModal(true);
Container content = dialog.getContentPane();
GameResultsPanel resultsPanel = new GameResultsPanel();
JPanel mainPanel = new JPanel();
//Room to add anything else
mainPanel.setLayout(new BorderLayout());
video = new VideoPanel();
mainPanel.add(video, BorderLayout.NORTH);
mainPanel.add(resultsPanel, BorderLayout.SOUTH);
content.add(mainPanel);
dialog.pack();
dialog.setSize(screenWidthVideo, screenHeightVideo);
//Get size of computer screen
//Set the screen so it appears in the middle
t = getToolkit();
screen = t.getScreenSize();
dialog.setLocation(screen.width/2-dialog.getWidth()/2,screen.height/2-dialog.getHeight()/2);
//Causes user to have to select one fo the options of the menu
dialog.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
//Test code
//dialog.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
}
public static void main(String[] args) {
GameResults results = new GameResults();
}
}
| true |
2c6c632bef95a2d5e6eb117bdeb9a82f51e9ea53 | Java | siddharthanG/Java-projects | /src/mar5/Removingspecialcharectors.java | UTF-8 | 755 | 2.8125 | 3 | [] | no_license | /*package mar5;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Removingspecialcharectors {
public static void main(String[] args) {
// TODO Auto-generated method stub
String b ="\\w{1,}";
String a ="{java}/\\*(selenium)";
Pattern c = Pattern.compile(b);
Matcher d = c.matcher(a);
while(d.find()) {
System.out.println(d.group());
}
}
}
*/
package mar5;
public class Removingspecialcharectors {
public static void main(String[] args) {
// TODO Auto-generated method stub
String a ="{java}/\\*(selenium)";
StringBuffer d = new StringBuffer(a.replaceAll("[^a-zA-Z0-9]", ""));
System.out.println(d);
}
}
| true |
a7f7ebd036522af695e2121953b72b394841f7ea | Java | 289562326/bigdata_mhm | /bg-manager/bg-designPattern/src/main/java/com/mhm/create/abstractFactory/DDM.java | UTF-8 | 369 | 2.3125 | 2 | [] | no_license | package com.mhm.create.abstractFactory;
/**
* @author Mhm
* @date 2020-4-17 9:01
*/
public class DDM extends RDBMSDeployment {
@Override
public void deplay() {
System.out.println("创建了分布式式数据库DDIM");
}
@Override
public void getDeploy() {
System.out.println("已经创建了分布式式数据库DDIM");
}
}
| true |
b2ed6985f2d10826d9e88621ad09d98504a9d8cd | Java | karthik-neelamegam/CourseworkGame | /src/core/RGPath.java | UTF-8 | 2,550 | 3.3125 | 3 | [] | no_license | package core;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class RGPath {
/*
* This class is used in the AIPlayer class to represent paths (i.e. an
* ordered list consisting of the two checkpoint RGVertex objects on either
* end and the path of RGVertex objects between them) connecting two
* checkpoint RGVertex objects together in a reduced graph.
*/
/*
* The RGVertex objects that make up the path ordered in the order they are
* in the path (although the RGVertex objects could be anything, they should
* be the checkpoint RGVertex objects on either end and the path of RGVertex
* objects between them). The List interface is used rather than a concrete
* class such as ArrayList because it separates the actual implementation of
* the List interface from this class's use of the interface's methods,
* allowing the implementation to change (say, from ArrayList to LinkedList)
* in the future. This is aggregation as the RGPath class has a HAS-A
* relationship with the RGVertex class but the RGVertex objects in the
* pathVertices list will not be destroyed if the RGPath object is
* destroyed.
*/
private List<RGVertex> pathVertices;
/*
* The weight of the path, i.e the sum of the weights of the RGEdge objects
* between each pair of consecutive RGVertex objects in the pathVertices
* list.
*/
private double totalWeight;
/*
* Constructor.
*/
public RGPath() {
/*
* An ArrayList implementation is used because it is efficient with
* respect to memory and iteration time complexity.
*/
pathVertices = new ArrayList<RGVertex>();
totalWeight = 0;
}
/*
* Adds nextVertex to the end of the pathVertices list and increases
* totalWeight by the weight of the RGEdge object between nextVertex and the
* previous RGVertex object in the pathVertices list (if there is one).
*/
public void appendVertex(RGVertex nextVertex) {
pathVertices.add(nextVertex);
if (pathVertices.size() > 1) {
totalWeight += nextVertex.getWeightToAdjacentVertex(pathVertices
.get(pathVertices.size() - 2));
}
}
/*
* Getters.
*/
public double getTotalWeight() {
return totalWeight;
}
public RGVertex getVertex1() {
return pathVertices.get(0);
}
public RGVertex getVertex2() {
return pathVertices.get(pathVertices.size() - 1);
}
public List<RGVertex> getPathVertices() {
return Collections.unmodifiableList(pathVertices);
}
}
| true |
4b6b618e696d7f11f9bb160a12d86eb8f1337da5 | Java | Doctor-Andonuts/MyLife | /app/src/main/java/com/doctor_andonuts/mylife/Chain/ChainListFragment.java | UTF-8 | 3,363 | 2.453125 | 2 | [] | no_license | package com.doctor_andonuts.mylife.Chain;
import android.app.AlertDialog;
import android.app.ListFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Toast;
import com.doctor_andonuts.mylife.R;
import java.util.ArrayList;
import java.util.List;
public class ChainListFragment extends ListFragment {
private final List<Chain> chains = new ArrayList<>();
private OnFragmentInteractionListener mListener;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
return inflater.inflate(R.layout.fragment_chain_list, container, false);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
mListener = (OnFragmentInteractionListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
refreshData();
ChainListArrayAdapter arrayAdapter = new ChainListArrayAdapter(getActivity(), chains, mListener);
arrayAdapter.notifyDataSetChanged();
setListAdapter(arrayAdapter);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.list_menu, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle item selection
switch (item.getItemId()) {
case R.id.item_resort:
refreshData();
ChainListArrayAdapter arrayAdapter = new ChainListArrayAdapter(getActivity(), chains, mListener);
arrayAdapter.notifyDataSetChanged();
setListAdapter(arrayAdapter);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void refreshData() {
ChainManager chainManager = new ChainManager(getActivity());
chains.clear();
chains.addAll(chainManager.getChains());
Log.d("FragmentList", "DATA REFRESH");
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Chain chain);
}
}
| true |
bbd300383837f652ffe7b3ab9ac4071bd11c211b | Java | Aristoeu/HUSTcanteen | /app/src/main/java/com/example/hustcanteen/select/SelectActivity.java | UTF-8 | 9,941 | 1.960938 | 2 | [] | no_license | package com.example.hustcanteen.select;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.hustcanteen.R;
import com.example.hustcanteen.model.Repos;
import com.example.hustcanteen.recommendation.RecommendationActivity;
import com.example.hustcanteen.model.Dish;
import java.util.ArrayList;
import java.util.List;
import static com.example.hustcanteen.model.Repos.RECOMENDATION;
import static com.example.hustcanteen.model.Repos.SelectedList;
import static com.example.hustcanteen.model.Repos.DishList;
public class SelectActivity extends AppCompatActivity implements SelectView {
private ViewPager tryNewViewPager;
private List<View> viewList;
private CheckBox less10,from10to20,from21to30,more30,zhongkou,qingdan,wusuowei,tian,mala,zhongyou,hunduo,suduo,tangduo,tangshao;
private ProgressBar progressBar;
private TextView next1,next2,next3,district1,district2,hall1,hall2,hall3,hall4,hall5,hall6,end;
private int d1 = 2,d2 = 3;
private SelectPresenter presenter = new SelectPresenter();
private Handler mHandler = new Handler(){
public void handleMessage(Message msg) {
switch (msg.what) {
case 1: setEastHall();break;
case 2: setWestHall();break;
case 3: setMiddleHall();break;
case 4:{
d1 = 1;
district1.setText("东边食堂");
break;
}
case 5:{
d1 = 2;
district1.setText("西边食堂");
break;
}
case 6:{
d1 = 3;
district1.setText("中间食堂");
break;
}
case 7:{
d2 = 1;
district2.setText("东边食堂");
break;
}
case 8:{
d2 = 2;
district2.setText("西边食堂");
break;
}
case 9:{
d2 = 3;
district2.setText("中间食堂");
break;
}
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_try_new);
initViews();
setClickListener();
}
public void initViews() {
tryNewViewPager = findViewById(R.id.try_new_viewpager);
final LayoutInflater inflater = getLayoutInflater();
View view1 = inflater.inflate(R.layout.try_new_1, null);
View view2 = inflater.inflate(R.layout.try_new_2, null);
View view3 = inflater.inflate(R.layout.try_new_3, null);
View view5 = inflater.inflate(R.layout.try_new_5, null);
viewList = new ArrayList<View>();
viewList.add(view1);
viewList.add(view2);
viewList.add(view3);
viewList.add(view5);
PagerAdapter pagerAdapter = new PagerAdapter() {
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
// TODO Auto-generated method stub
return arg0 == arg1;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return viewList.size();
}
@Override
public void destroyItem(ViewGroup container, int position,
Object object) {
// TODO Auto-generated method stub
container.removeView(viewList.get(position));
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
// TODO Auto-generated method stub
View v = viewList.get(position);
ViewGroup parent = (ViewGroup) v.getParent();
if (parent == null) {
// parent.removeAllViews();
container.addView(v);
}
return viewList.get(position);
}
};
tryNewViewPager.setAdapter(pagerAdapter);
next1 = view1.findViewById(R.id.certain_next1);
district1 = view1.findViewById(R.id.district1);
district2 = view1.findViewById(R.id.district2);
hall1 = view1.findViewById(R.id.hal1);
hall2 = view1.findViewById(R.id.hal2);
hall3 = view1.findViewById(R.id.hal3);
hall4 = view1.findViewById(R.id.hal4);
hall5 = view1.findViewById(R.id.hal5);
hall6 = view1.findViewById(R.id.hal6);
next2 = view2.findViewById(R.id.certain_next2);
zhongkou = view2.findViewById(R.id.zhongkou);
qingdan = view2.findViewById(R.id.qingdan);
wusuowei = view2.findViewById(R.id.wusuowei);
tian = view2.findViewById(R.id.tian);
next3 = view3.findViewById(R.id.certain_next3);
mala = view3.findViewById(R.id.mala);
zhongyou = view3.findViewById(R.id.zhongyou);
hunduo = view3.findViewById(R.id.hunduo);
suduo = view3.findViewById(R.id.suduo);
tangduo = view3.findViewById(R.id.tangduo);
tangshao = view3.findViewById(R.id.tangshao);
less10 = view5.findViewById(R.id.less10);
from10to20 = view5.findViewById(R.id.from10to20);
from21to30 = view5.findViewById(R.id.from21to30);
more30 = view5.findViewById(R.id.more30);
progressBar = view5.findViewById(R.id.loading);
end = view5.findViewById(R.id.end_certain);
}
public void setClickListener() {
end.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
UpdateCheckBox();
startActivity(new Intent(SelectActivity.this, RecommendationActivity.class));
//finish();
}
});
next1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
tryNewViewPager.setCurrentItem(1);
}
});
next2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
tryNewViewPager.setCurrentItem(2);
}
});
next3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
tryNewViewPager.setCurrentItem(3);
}
});
district1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
presenter.UpdateDistrict1(d1,d2,mHandler);
}
});
district2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
presenter.UpdateDistrict2(d1,d2,mHandler);
}
});
}
public void UpdateCheckBox() {
progressBar.setVisibility(View.VISIBLE);
SelectedList = new ArrayList<>();
Repos.p_10 = less10.isChecked();
Repos.p10_20 = from10to20.isChecked();
Repos.p21_30 = from21to30.isChecked();
Repos.p30_ = more30.isChecked();
Repos.zhongkou = zhongkou.isChecked();
Repos.qingdan = qingdan.isChecked();
Repos.tian = tian.isChecked();
Repos.wusuowei = wusuowei.isChecked();
Repos.mala = mala.isChecked();
Repos.zhongyou = zhongyou.isChecked();
Repos.hunduo = hunduo.isChecked();
Repos.suduo = suduo.isChecked();
Repos.tangduo = tangduo.isChecked();
Repos.tangshao = tangshao.isChecked();
SelectPresenter selectPresenter = new SelectPresenter();
for (int i = 0;i<DishList.size();i++){
if (selectPresenter.judge(i)){
SelectedList.add(DishList.get(i));
}
}
progressBar.setVisibility(View.INVISIBLE);
if(SelectedList.isEmpty()){
Looper.prepare();
Toast.makeText(SelectActivity.this,"没找到哦,换个口味试试吧",Toast.LENGTH_SHORT).show();
Looper.loop();
Log.d("~~~~~~","没找到");
}
for (int i = 0;i<SelectedList.size();i++){
Dish dish = SelectedList.get(i);
Log.d("~~~~~~","name:"+dish.name+" index:"+dish.index+" hall:"+dish.hall+" price:"+dish.price+" kind:"+dish.kind);
}
Repos.Choice = RECOMENDATION;
}
public void setEastHall() {
hall1.setText("韵苑食堂");
hall2.setText("东园食堂");
hall3.setText("东篱餐厅");
hall4.setText("学一食堂");
hall5.setText("学二食堂");
hall6.setText("东教工食堂");
}
public void setMiddleHall() {
hall1.setText("东一食堂");
hall2.setText("东三食堂");
hall3.setText("喻园餐厅");
hall4.setText(" 集锦园 ");
hall5.setText(" 集贤楼 ");
hall6.setText("紫荆园食堂");
}
public void setWestHall() {
hall1.setText("西一食堂");
hall2.setText("西二食堂");
hall3.setText(" 百景园 ");
hall4.setText(" 西华园 ");
hall5.setText(" 百惠园 ");
hall6.setText("枫林湾食堂");
}
}
| true |
8a7aa1a0ccb1be09b49ef68482c4a7572444d6b1 | Java | ATM006/sitewhere-microservice-core | /sitewhere-grpc-client/src/main/java/com/sitewhere/grpc/client/spi/server/IGrpcApiImplementation.java | UTF-8 | 787 | 1.539063 | 2 | [] | no_license | /*
* Copyright (c) SiteWhere, LLC. All rights reserved. http://www.sitewhere.com
*
* The software in this package is published under the terms of the CPAL v1.0
* license, a copy of which has been included with this distribution in the
* LICENSE.txt file.
*/
package com.sitewhere.grpc.client.spi.server;
import com.sitewhere.spi.microservice.IFunctionIdentifier;
import com.sitewhere.spi.microservice.IMicroservice;
import com.sitewhere.spi.microservice.IMicroserviceConfiguration;
/**
* Provides a common interface for gRPC API implementations.
*/
public interface IGrpcApiImplementation {
/**
* Get parent microservice.
*
* @return
*/
public IMicroservice<? extends IFunctionIdentifier, ? extends IMicroserviceConfiguration> getMicroservice();
} | true |
5235f3ce8a3ee618ac2a001f44c14c389fa9ec9b | Java | apanesar96/shopping-basket | /src/main/java/com/amanshoppingbasket/shoppingbasket/ProductType.java | UTF-8 | 95 | 1.742188 | 2 | [] | no_license | package com.amanshoppingbasket.shoppingbasket;
public enum ProductType {
DVD,
BOOK;
}
| true |
c3c4f093828f6ac14c3ca5f6c3f84a3d6e11b08b | Java | reoo/chargeanywhere | /app/src/main/java/com/raulomana/chargeanywhere/db/ListingDAO.java | UTF-8 | 871 | 2.109375 | 2 | [] | no_license | package com.raulomana.chargeanywhere.db;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
@Dao
public interface ListingDAO {
@Query("SELECT * FROM listing")
LiveData<List<Listing>> getAll();
@Query("SELECT * FROM listing ORDER BY id")
LiveData<List<Listing>> getAllSortById();
@Query("SELECT * FROM listing ORDER BY name")
LiveData<List<Listing>> getAllSortByName();
@Query("SELECT * FROM listing ORDER BY datetime(date) DESC")
LiveData<List<Listing>> getAllSortByDate();
@Insert(onConflict = OnConflictStrategy.IGNORE)
long save(@NonNull Listing listing);
@Query("SELECT * FROM listing ORDER BY id DESC LIMIT 1")
LiveData<Listing> getLast();
}
| true |
788cf101b54a3a9918f4c147ab39959b39c3a683 | Java | chshimotake/OldMacDonald | /NamedCow.java | UTF-8 | 304 | 2.734375 | 3 | [] | no_license | class NamedCow extends Cow
{
String nem="";
public NamedCow()
{
nem="Cowlvin";
sou="moo";
typ="cow";
}
public NamedCow(String beef, String kobe, String steak)
{
typ=beef;
sou=steak;
nem=kobe;
}
public String getName()
{
return nem;
}
} | true |
77fe1f9724f1751b6244ac4bb77067318f23be22 | Java | germuth/3D-HP-Protein-Folding | /src/org/jmol/jvxl/data/MeshData.java | UTF-8 | 11,005 | 2.28125 | 2 | [] | no_license | /* $RCSfile$
* $Author: hansonr $
* $Date: 2007-03-30 11:40:16 -0500 (Fri, 30 Mar 2007) $
* $Revision: 7273 $
*
* Copyright (C) 2007 Miguel, Bob, Jmol Development
*
* Contact: hansonr@stolaf.edu
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/*
* The JVXL file format
* --------------------
*
* as of 3/29/07 this code is COMPLETELY untested. It was hacked out of the
* Jmol code, so there is probably more here than is needed.
*
*
*
* see http://www.stolaf.edu/academics/chemapps/jmol/docs/misc/JVXL-format.pdf
*
* The JVXL (Jmol VoXeL) format is a file format specifically designed
* to encode an isosurface or planar slice through a set of 3D scalar values
* in lieu of a that set. A JVXL file can contain coordinates, and in fact
* it must contain at least one coordinate, but additional coordinates are
* optional. The file can contain any finite number of encoded surfaces.
* However, the compression of 300-500:1 is based on the reduction of the
* data to a SINGLE surface.
*
*
* The original Marching Cubes code was written by Miguel Howard in 2005.
* The classes Parser, ArrayUtil, and TextFormat are condensed versions
* of the classes found in org.jmol.util.
*
* All code relating to JVXL format is copyrighted 2006/2007 and invented by
* Robert M. Hanson,
* Professor of Chemistry,
* St. Olaf College,
* 1520 St. Olaf Ave.
* Northfield, MN. 55057.
*
* Implementations of the JVXL format should reference
* "Robert M. Hanson, St. Olaf College" and the opensource Jmol project.
*
*
* implementing marching squares; see
* http://www.secam.ex.ac.uk/teaching/ug/studyres/COM3404/COM3404-2006-Lecture15.pdf
*
* lines through coordinates are identical to CUBE files
* after that, we have a line that starts with a negative number to indicate this
* is a JVXL file:
*
* line1: (int)-nSurfaces (int)edgeFractionBase (int)edgeFractionRange
* (nSurface lines): (float)cutoff (int)nBytesData (int)nBytesFractions
*
* definition1
* edgedata1
* fractions1
* colordata1
* ....
* definition2
* edgedata2
* fractions2
* colordata2
* ....
*
* definitions: a line with detail about what sort of compression follows
*
* edgedata: a list of the count of vertices ouside and inside the cutoff, whatever
* that may be, ordered by nested for loops for(x){for(y){for(z)}}}.
*
* nOutside nInside nOutside nInside...
*
* fractions: an ascii list of characters represting the fraction of distance each
* encountered surface point is along each voxel cube edge found to straddle the
* surface. The order written is dictated by the reader algorithm and is not trivial
* to describe. Each ascii character is constructed by taking a base character and
* adding onto it the fraction times a range. This gives a character that can be
* quoted EXCEPT for backslash, which MAY be substituted for by '!'. Jmol uses the
* range # - | (35 - 124), reserving ! and } for special meanings.
*
* colordata: same deal here, but with possibility of "double precision" using two bytes.
*
*
*
* THIS READER
* -----------
*
* This is a first attempt at a generic JVXL file reader and writer class.
* It is an extraction of Jmol org.jmol.viewer.Isosurface.Java and related pieces.
*
* The goal of the reader is to be able to read CUBE-like data and
* convert that data to JVXL file data.
*
*
*/
package org.jmol.jvxl.data;
import java.util.Arrays;
import java.util.Comparator;
import org.jmol.util.ArrayUtil;
import org.jmol.util.BS;
import org.jmol.util.MeshSurface;
import org.jmol.util.P3;
import org.jmol.util.V3;
public class MeshData extends MeshSurface {
public final static int MODE_GET_VERTICES = 1;
public final static int MODE_GET_COLOR_INDEXES = 2;
public final static int MODE_PUT_SETS = 3;
public final static int MODE_PUT_VERTICES = 4;
private boolean setsSuccessful;
public int vertexIncrement = 1;
public String polygonColorData;
public int addVertexCopy(P3 vertex, float value, int assocVertex) {
if (assocVertex < 0)
vertexIncrement = -assocVertex; //3 in some cases
return addVCVal(vertex, value);
}
public BS[] getSurfaceSet() {
return (surfaceSet == null ? getSurfaceSetForLevel(0) : surfaceSet);
}
public BS[] getSurfaceSetForLevel(int level) {
if (level == 0) {
surfaceSet = new BS[100];
nSets = 0;
}
setsSuccessful = true;
for (int i = 0; i < polygonCount; i++)
if (polygonIndexes[i] != null) {
if (bsSlabDisplay != null && !bsSlabDisplay.get(i))
continue;
int[] p = polygonIndexes[i];
int pt0 = findSet(p[0]);
int pt1 = findSet(p[1]);
int pt2 = findSet(p[2]);
if (pt0 < 0 && pt1 < 0 && pt2 < 0) {
createSet(p[0], p[1], p[2]);
continue;
}
if (pt0 == pt1 && pt1 == pt2)
continue;
if (pt0 >= 0) {
surfaceSet[pt0].set(p[1]);
surfaceSet[pt0].set(p[2]);
if (pt1 >= 0 && pt1 != pt0)
mergeSets(pt0, pt1);
if (pt2 >= 0 && pt2 != pt0 && pt2 != pt1)
mergeSets(pt0, pt2);
continue;
}
if (pt1 >= 0) {
surfaceSet[pt1].set(p[0]);
surfaceSet[pt1].set(p[2]);
if (pt2 >= 0 && pt2 != pt1)
mergeSets(pt1, pt2);
continue;
}
surfaceSet[pt2].set(p[0]);
surfaceSet[pt2].set(p[1]);
}
int n = 0;
for (int i = 0; i < nSets; i++)
if (surfaceSet[i] != null)
n++;
BS[] temp = new BS[surfaceSet.length];
n = 0;
for (int i = 0; i < nSets; i++)
if (surfaceSet[i] != null)
temp[n++] = surfaceSet[i];
nSets = n;
surfaceSet = temp;
if (!setsSuccessful && level < 2)
getSurfaceSetForLevel(level + 1);
if (level == 0) {
sortSurfaceSets();
setVertexSets(false);
}
return surfaceSet;
}
private class SSet {
BS bs;
int n;
protected SSet (BS bs) {
this.bs = bs;
n = bs.cardinality();
}
}
protected class SortSet implements Comparator<SSet> {
public int compare(SSet o1, SSet o2) {
return (o1.n > o2.n ? -1 : o1.n < o2.n ? 1 : 0);
}
}
private void sortSurfaceSets() {
SSet[] sets = new SSet[nSets];
for (int i = 0; i < nSets; i++)
sets[i] = new SSet(surfaceSet[i]);
Arrays.sort(sets, new SortSet());
for (int i = 0; i < nSets; i++)
surfaceSet[i] = sets[i].bs;
}
public void setVertexSets(boolean onlyIfNull) {
if (surfaceSet == null)
return;
int nNull = 0;
for (int i = 0; i < nSets; i++) {
if (surfaceSet[i] != null && surfaceSet[i].cardinality() == 0)
surfaceSet[i] = null;
if (surfaceSet[i] == null)
nNull++;
}
if (nNull > 0) {
BS[] bsNew = new BS[nSets - nNull];
for (int i = 0, n = 0; i < nSets; i++)
if (surfaceSet[i] != null)
bsNew[n++] = surfaceSet[i];
surfaceSet = bsNew;
nSets -= nNull;
} else if (onlyIfNull) {
return;
}
vertexSets = new int[vertexCount];
for (int i = 0; i < nSets; i++)
for (int j = surfaceSet[i].nextSetBit(0); j >= 0; j = surfaceSet[i]
.nextSetBit(j + 1))
vertexSets[j] = i;
}
private int findSet(int vertex) {
for (int i = 0; i < nSets; i++)
if (surfaceSet[i] != null && surfaceSet[i].get(vertex))
return i;
return -1;
}
private void createSet(int v1, int v2, int v3) {
int i;
for (i = 0; i < nSets; i++)
if (surfaceSet[i] == null)
break;
if (i == surfaceSet.length)
surfaceSet = (BS[]) ArrayUtil.ensureLength(surfaceSet, surfaceSet.length + 100);
surfaceSet[i] = new BS();
surfaceSet[i].set(v1);
surfaceSet[i].set(v2);
surfaceSet[i].set(v3);
if (i == nSets)
nSets++;
}
private void mergeSets(int a, int b) {
surfaceSet[a].or(surfaceSet[b]);
surfaceSet[b] = null;
}
public void invalidateSurfaceSet(int i) {
for (int j = surfaceSet[i].nextSetBit(0); j >= 0; j = surfaceSet[i].nextSetBit(j + 1))
vertexValues[j] = Float.NaN;
surfaceSet[i] = null;
}
public static boolean checkCutoff(int iA, int iB, int iC, float[] vertexValues) {
// never cross a +/- junction with a triangle in the case of orbitals,
// where we are using |psi| instead of psi for the surface generation.
// note that for bicolor maps, where the values are all positive, we
// check this later in the meshRenderer
if (iA < 0 || iB < 0 || iC < 0)
return false;
float val1 = vertexValues[iA];
float val2 = vertexValues[iB];
float val3 = vertexValues[iC];
return (val1 >= 0 && val2 >= 0 && val3 >= 0
|| val1 <= 0 && val2 <= 0 && val3 <= 0);
}
public Object calculateVolumeOrArea(int thisSet, boolean isArea, boolean getSets) {
if (getSets)
getSurfaceSet();
boolean justOne = (nSets == 0 || thisSet >= 0);
int n = (justOne ? 1 : nSets);
double[] v = new double[n];
V3 vAB = new V3();
V3 vAC = new V3();
V3 vTemp = new V3();
for (int i = polygonCount; --i >= 0;) {
if (!setABC(i))
continue;
int iSet = (nSets == 0 ? 0 : vertexSets[iA]);
if (thisSet >= 0 && iSet != thisSet)
continue;
if (isArea) {
vAB.sub2(vertices[iB], vertices[iA]);
vAC.sub2(vertices[iC], vertices[iA]);
vTemp.cross(vAB, vAC);
v[justOne ? 0 : iSet] += vTemp.length();
} else {
// volume
vAB.setT(vertices[iB]);
vAC.setT(vertices[iC]);
vTemp.cross(vAB, vAC);
vAC.setT(vertices[iA]);
v[justOne ? 0 : iSet] += vAC.dot(vTemp);
}
}
double factor = (isArea ? 2 : 6);
for (int i = 0; i < n; i++)
v[i] /= factor;
if (justOne && thisSet != Integer.MIN_VALUE)
return Float.valueOf((float) v[0]);
return v;
}
public void updateInvalidatedVertices(BS bs) {
bs.clearAll();
for (int i = 0, ipt = 0; i < vertexCount; i += vertexIncrement, ipt++)
if (Float.isNaN(vertexValues[i]))
bs.set(i);
}
public void invalidateVertices(BS bsInvalid) {
for (int i = bsInvalid.nextSetBit(0); i >= 0; i = bsInvalid.nextSetBit(i + 1))
vertexValues[i] = Float.NaN;
}
}
| true |
5270ebf097e07e38423fbbf158e8132a8474562c | Java | 7216nat/TFG_Comprobador-de-equivalencia-entre-especificaciones-basadas-en-expresiones-regulares | /Equivalencias_ERs/src/objects/Simbolo.java | UTF-8 | 2,453 | 2.765625 | 3 | [
"MIT"
] | permissive | package objects;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import automata.*;
// Comentarios en ExpressionBase
public class Simbolo extends Lenguaje implements Comparable<Simbolo> {
/**
* construtora por defecto
*/
public Simbolo() {
super(null, Tipo.SIMB);
}
/**
* constructora
*
* @param er: simbolo
*/
public Simbolo(String er) {
super(er, Tipo.SIMB);
}
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Simbolo)) {
return false;
}
Simbolo sim = (Simbolo) o;
return _sim.equals(sim._sim);
}
@Override
public int hashCode() {
return _sim.hashCode();
}
@Override
public AutomataTS ThomsonAFN(IdEstado id) {
int ini = id.nextId();
int acept = id.nextId();
AutomataTS aut = new AutomataTS(ini, acept);
aut.addTransicion(ini, acept, _sim);
return aut;
}
@Override
public AutomataTS ThomsonSimplAFN(IdEstado id) {
int ini = id.nextId();
int acept = id.nextId();
AutomataTS aut = new AutomataTS(ini, acept);
aut.addTransicion(ini, acept, _sim);
return aut;
}
@Override
public BerrySethiNode createBerrySethiNode(Map<Integer, BerrySethiNode> map, IdEstado id) {
Set<Integer> tmp = new HashSet<>();
BerrySethiNode bs = new BerrySethiNode();
bs.setEmpty(false);
bs.setSim(_sim);
bs.setTipo(getType());
int iD = id.nextId();
tmp.add(iD);
bs.setFirst(tmp);
tmp = new HashSet<>();
tmp.add(iD);
bs.setLast(tmp);
map.put(iD, bs);
return bs;
}
@Override
public int compareTo(Simbolo o) {
return _sim.compareTo(o._sim);
}
@Override
public void getSimbolosRangos(Set<String> set, List<UnionRangos> array, Set<Character> inis, Set<Character> fins) {
set.add(_sim);
inis.add(_sim.charAt(0));
fins.add(_sim.charAt(0));
}
public boolean contiene(String sim) {
return (sim.equals(this._sim));
}
@Override
public String getVal() {
return this._sim;
}
@Override
public ExpressionBase derivada(String sim) {
if(sim.equals(this._sim))
return new Lambdaa();
else
return new Vacio();
}
@Override
public Set<ExpressionBase> derivadaParcial(String sim) {
Set<ExpressionBase> ret = new HashSet<>();
if(this._sim.equals(sim))
ret.add(new Lambdaa());
else ret.add(new Vacio());
return ret;
}
@Override
public ExpressionBase copy() {
// TODO Auto-generated method stub
return new Simbolo(_sim);
}
}
| true |
958822d28e234c929d4bcf2ef915cb7aa02b75e9 | Java | caio000/web2 | /src/dao/AuthorDAO.java | UTF-8 | 309 | 2.09375 | 2 | [] | no_license | package dao;
import java.util.List;
import models.Author;
public class AuthorDAO extends DAO<Author> {
@Override
public Author getById(long id) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Author> getAll() {
// TODO Auto-generated method stub
return null;
}
}
| true |
b9669148abaad88602096875a22e8190302ff0f2 | Java | rafizanbaharum/core-rnd | /src/main/java/net/canang/corernd/core/model/RndGroup.java | UTF-8 | 258 | 1.796875 | 2 | [
"Apache-2.0"
] | permissive | package net.canang.corernd.core.model;
import java.util.Set;
/**
* @author rafizan.baharum
* @since 7/10/13
*/
public interface RndGroup extends RndPrincipal {
Set<RndGroupMember> getMembers();
void setMembers(Set<RndGroupMember> members);
}
| true |
96289748680f44b6e69bca1d9fa89c2e1207df0f | Java | dengjiaping/xiangniAndroidCode | /xiangniAndroidCode/app/src/main/java/com/ixiangni/interfaces/OnGroupMemberChang.java | UTF-8 | 439 | 1.960938 | 2 | [] | no_license | package com.ixiangni.interfaces;
/**
* Created by Administrator on 2017/7/7 0007.
*/
/**
* 群成员变化
* @ClassName:OnGroupMemberChang
* @PackageName:com.ixiangni.interfaces
* @Create On 2017/7/7 0007 17:41
* @Site:http://www.handongkeji.com
* @author:xuchuanting
* @Copyrights 2017/7/7 0007 handongkeji All rights reserved.
*/
public interface OnGroupMemberChang {
void onMemberChange();
}
| true |
d61922d56a0fdc52940a4cac313a30f8fd93cb0a | Java | vjetteam/vjet | /extmod/dltk/javascript/org.eclipse.dltk.javascript.launching/src/org/eclipse/dltk/mod/javascript/internal/launching/GenericJavaScriptInstall.java | UTF-8 | 2,030 | 2.25 | 2 | [] | no_license | package org.eclipse.dltk.mod.javascript.internal.launching;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.dltk.mod.javascript.core.JavaScriptNature;
import org.eclipse.dltk.mod.launching.AbstractInterpreterInstall;
import org.eclipse.dltk.mod.launching.IInterpreterInstallType;
import org.eclipse.dltk.mod.launching.IInterpreterRunner;
public class GenericJavaScriptInstall extends AbstractInterpreterInstall {
private static final String BUILTINS_JS = "builtins.js"; //$NON-NLS-1$
public String getBuiltinModuleContent(String name) {
InputStream stream = GenericJavaScriptInstall.class
.getResourceAsStream(BUILTINS_JS);
DataInputStream st = new DataInputStream(stream);
StringBuffer buf = new StringBuffer();
try {
while (st.available() >= 0) {
String line = st.readLine();
if (line == null)
break;
buf.append(line);
buf.append('\n');
}
} catch (IOException e) {
// should not happen
}
return buf.toString();
}
public String[] getBuiltinModules() {
return new String[] { "builtins.js" }; //$NON-NLS-1$
}
public long lastModified() {
try {
return GenericJavaScriptInstall.class.getResource(BUILTINS_JS)
.openConnection().getLastModified();
} catch (IOException e) {
return 0;
}
}
public GenericJavaScriptInstall(IInterpreterInstallType type, String id) {
super(type, id);
}
public IInterpreterRunner getInterpreterRunner(String mode) {
IInterpreterRunner runner = super.getInterpreterRunner(mode);
if (runner != null) {
return runner;
}
if (mode.equals(ILaunchManager.RUN_MODE)) {
return new JavaScriptInterpreterRunner(this);
}
/*
* else if (mode.equals(ILaunchManager.DEBUG_MODE)) { return new
* JavaScriptInterpreterDebugger(this); }
*/
return null;
}
public String getNatureId() {
return JavaScriptNature.NATURE_ID;
}
}
| true |
dd0abfa37578518f5d3ac95cc625f6a6afa66933 | Java | zengyuanyang/test | /Test/src/Test.java | GB18030 | 1,049 | 3.390625 | 3 | [] | no_license |
class Test {
public static void main(String[] args) {
//ת
Fu f = new Zi();
System.out.println(f.age);
f.show();
f.tst();
// f.play; //
//ת
System.out.println("===================================================");
System.out.println(((Zi)f).age);
System.out.println(((Zi)f).length);
System.out.println(((Zi)f).size);
((Zi)f).show();
((Zi)f).tst();
((Zi)f).play();
}
}
class Fu{
int age = 30;
int length = 18;
Fu(){
System.out.println("췽");
}
public void show() {
System.out.println("Ա");
}
public static void tst() {
System.out.println("̬");
}
}
class Zi extends Fu{
int age = 10;
int size = 3;
Zi(){
System.out.println("ӹ췽");
}
public void show() {
System.out.println("ӳԱ");
}
public void play() {
System.out.println("Ϸ");
}
public static void tst() {
System.out.println("Ӿ̬");
}
}
| true |
1502b73680eb24eb91b748ec4e72f5ccd0b1a0b6 | Java | inferno1988/jPogiEngine | /src/ua/com/ifno/pogi/TileInfo.java | UTF-8 | 468 | 2.609375 | 3 | [] | no_license | package ua.com.ifno.pogi;
import java.net.URL;
class TileInfo {
private URL url;
private int i;
private int j;
public TileInfo(URL url, int i, int j) {
this.url = url;
this.i = i;
this.j = j;
}
public URL getUrl() {
return url;
}
public void setUrl(URL url) {
this.url = url;
}
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
public int getJ() {
return j;
}
public void setJ(int j) {
this.j = j;
}
}
| true |
e052209ac610d7e457594592a44814707a62cc60 | Java | LynnKdG/upvote | /src/test/java/be/kdg/prog3/upvote/test/ControllerTests.java | UTF-8 | 2,976 | 1.914063 | 2 | [
"MIT"
] | permissive | package be.kdg.prog3.upvote.test;
import be.kdg.prog3.upvote.Application;
import be.kdg.prog3.upvote.services.QuestionAnswerService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.test.context.support.WithUserDetails;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrlPattern;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { Application.class, SpringSecurityWebTestConfig.class })
@WebAppConfiguration
@EnableWebSecurity
public class ControllerTests {
@MockBean
private QuestionAnswerService questionAnswerService;
@Autowired
private WebApplicationContext wac;
private MockMvc mvc;
@Before
public void setup(){
MockitoAnnotations.initMocks(this);
this.mvc = MockMvcBuilders
.webAppContextSetup(wac)
.apply(springSecurity())
.build();
}
@Test
@WithUserDetails("jos")
public void testPostAnswerLoggedIn() throws Exception {
this.mvc.perform(post("/a")
.with(csrf())
.accept(MediaType.TEXT_HTML)
.param("body", "BODY")
.param("parentId", "1"))
.andDo(print())
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrlPattern("/**/q/1"));
}
@Test
public void testPostAnswerNotLoggedIn() throws Exception {
this.mvc.perform(post("/a")
.with(csrf())
.accept(MediaType.TEXT_HTML)
.param("body", "BODY")
.param("parentId", "1"))
.andDo(print())
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrlPattern("**/login"));
}
}
| true |
99319faf4772874736dd57f9b52b2945212c8df8 | Java | tkrajina/GraphAnything | /graphanything/src/main/java/info/puzz/graphanything/fragments/GraphEntriesArrayAdapter.java | UTF-8 | 2,697 | 2.125 | 2 | [
"Apache-2.0"
] | permissive | package info.puzz.graphanything.fragments;
import android.content.Context;
import android.databinding.DataBindingUtil;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.sql.Timestamp;
import java.util.Map;
import info.puzz.graphanything.R;
import info.puzz.graphanything.activities.BaseActivity;
import info.puzz.graphanything.activities.GraphEntryActivity;
import info.puzz.graphanything.databinding.GraphEntryBinding;
import info.puzz.graphanything.models2.FormatVariant;
import info.puzz.graphanything.models2.Graph;
import info.puzz.graphanything.models2.GraphColumn;
import info.puzz.graphanything.models2.GraphEntry;
import info.puzz.graphanything.utils.StringUtils;
import info.puzz.graphanything.utils.TimeUtils;
public class GraphEntriesArrayAdapter extends ArrayAdapter<GraphEntry> {
private static final String TAG = GraphEntriesArrayAdapter.class.getSimpleName();
private final Context context;
private final GraphEntry[] values;
private final Graph graph;
private final GraphColumn column;
public GraphEntriesArrayAdapter(Context context, Graph graph, GraphEntry[] values, Map<Integer, GraphColumn> columns) {
super(context, R.layout.graph, values);
this.context = context;
this.graph = graph;
this.values = values;
this.column = columns.get(0);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
GraphEntryBinding binding;
if (convertView == null) {
binding = DataBindingUtil.inflate(inflater, R.layout.graph_entry, parent, false);
} else {
binding = DataBindingUtil.findBinding(convertView);
}
final GraphEntry graphEntry = values[position];
binding.graphValueTitle.setText(column.formatValueWithUnit(graphEntry.get(0), FormatVariant.LONG));
binding.graphValueSubtitleCreated.setText(TimeUtils.YYYYMMDDHHMMSS_FORMATTER.format(new Timestamp(graphEntry.created)));
binding.entryComment.setText(StringUtils.isEmpty(graphEntry.getComment()) ? "..." : StringUtils.ellipses(graphEntry.getComment().replace("\n", " "), 40));
binding.getRoot().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
GraphEntryActivity.start((BaseActivity) context, graph._id, graphEntry);
}
});
return binding.getRoot();
}
}
| true |
4254da3fc1cb0c380795329f355ccd0639cc9712 | Java | bellmit/FMS-1 | /core/src/main/java/clb/core/system/service/impl/ClbCodeServiceImpl.java | UTF-8 | 8,149 | 2.171875 | 2 | [] | no_license | /*
* #{copyright}#
*/
package clb.core.system.service.impl;
import com.github.pagehelper.PageHelper;
import com.hand.hap.core.ILanguageProvider;
import com.hand.hap.core.IRequest;
import com.hand.hap.system.dto.Language;
import clb.core.cache.impl.ClbSysCodeCache;
import clb.core.system.dto.ClbCode;
import clb.core.system.dto.ClbCodeValue;
import clb.core.system.mapper.ClbCodeMapper;
import clb.core.system.mapper.ClbCodeValueMapper;
import clb.core.system.service.IClbCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author wanjun.feng@hand-china.com
*/
@Service
@Transactional
public class ClbCodeServiceImpl implements IClbCodeService {
@Autowired
private ClbCodeMapper clbCodeMapper;
@Autowired
private ClbCodeValueMapper clbCodeValueMapper;
@Autowired
private ILanguageProvider languageProvider;
@Autowired
private ClbSysCodeCache clbCodeCache;
/**
* 批量操作快码行数据.
*
* @param code
* 头行数据
*/
private void processCodeValues(ClbCode code) {
for (ClbCodeValue codeValue : code.getClbCodeValues()) {
if (codeValue.getCodeValueId() == null) {
codeValue.setCodeId(code.getCodeId()); // 设置头ID跟行ID一致
clbCodeValueMapper.insertSelective(codeValue);
} else if (codeValue.getCodeValueId() != null) {
clbCodeValueMapper.updateByPrimaryKeySelective(codeValue);
}
}
}
@Override
@Transactional(propagation = Propagation.SUPPORTS)
public List<ClbCode> selectCodes(IRequest request, ClbCode code, int page, int pagesize) {
PageHelper.startPage(page, pagesize);
List<ClbCode> codes = clbCodeMapper.selectCode(code);
return codes;
}
@Override
public List<ClbCodeValue> selectCodeValues(IRequest request, ClbCodeValue value) {
return clbCodeValueMapper.selectCodeValuesByCodeId(value);
}
@Override
public List<ClbCodeValue> selectCodeValuesByCodeName(IRequest request, String codeName) {
ClbCode code = clbCodeCache.getValue(codeName + "." + request.getLocale());
if (code != null) {
return code.getClbCodeValues();
} else {
return clbCodeValueMapper.selectCodeValuesByCodeName(codeName);
}
}
/**
* 根据代码和值获取CodeValue.
* <p>
* 从 cache 直接取值.
*
* @param request
* 请求上下文
* @param codeName
* 代码
* @param value
* 代码值
* @return codeValue 代码值DTO
* @author frank.li
*/
@Override
public ClbCodeValue getCodeValue(IRequest request, String codeName, String value) {
ClbCode code = clbCodeCache.getValue(codeName + "." + request.getLocale());
if (code == null) {
return null;
}
if (code.getClbCodeValues() == null) {
return null;
}
for (ClbCodeValue v : code.getClbCodeValues()) {
if (value.equals(v.getValue())) {
return v;
}
}
return null;
};
/**
* 根据代码和含义获取代码值.
* <p>
* 从 cache 直接取值.
*
* @param request
* 请求上下文
* @param codeName
* 代码
* @param meaning
* 含义
* @return value 代码值
* @author frank.li
*/
@Override
public String getCodeValueByMeaning(IRequest request, String codeName, String meaning) {
ClbCode code = clbCodeCache.getValue(codeName + "." + request.getLocale());
if (code == null) {
return null;
}
if (code.getClbCodeValues() == null) {
return null;
}
for (ClbCodeValue v : code.getClbCodeValues()) {
if (meaning.equals(v.getMeaning())) {
return v.getValue();
}
}
return null;
};
/**
* 根据代码和值获取含义.
*
* @param codeName
* 代码
* @param value
* 代码值
* @return meaning 含义
*/
@Override
public String getCodeMeaningByValue(IRequest request, String codeName, String value) {
ClbCode code = clbCodeCache.getValue(codeName + "." + request.getLocale());
if (code == null) {
return null;
}
if (code.getClbCodeValues() == null) {
return null;
}
for (ClbCodeValue v : code.getClbCodeValues()) {
if (value.equals(v.getValue())) {
return v.getMeaning();
}
}
return null;
};
/**
* 根据代码和值获取描述.
*
* @param codeName
* 代码
* @param value
* 代码值
* @return description 描述
*/
@Override
public String getCodeDescByValue(IRequest request, String codeName, String value) {
ClbCode code = clbCodeCache.getValue(codeName + "." + request.getLocale());
if (code == null) {
return null;
}
if (code.getClbCodeValues() == null) {
return null;
}
for (ClbCodeValue v : code.getClbCodeValues()) {
if (value.equals(v.getValue())) {
return v.getDescription();
}
}
return null;
};
@Override
public ClbCode createCode(ClbCode code) {
// 插入头行
clbCodeMapper.insertSelective(code);
// 判断如果行不为空,则迭代循环插入
if (code.getClbCodeValues() != null) {
processCodeValues(code);
}
for (Language lang : languageProvider.getSupportedLanguages()) {
clbCodeCache.setValue(code.getCode() + "." + lang.getLangCode(), code);
}
return code;
}
@Override
public boolean batchDelete(IRequest request, List<ClbCode> codes) {
// 删除头行
for (ClbCode code : codes) {
ClbCodeValue codeValue = new ClbCodeValue();
codeValue.setCodeId(code.getCodeId());
// 首先删除行的多语言数据
clbCodeValueMapper.deleteTlByCodeId(codeValue);
// 然后删除行
clbCodeValueMapper.deleteByCodeId(codeValue);
// 最后删除头
clbCodeMapper.deleteByPrimaryKey(code);
clbCodeCache.remove(code.getCode());
}
return true;
}
@Override
public boolean batchDeleteValues(IRequest request, List<ClbCodeValue> values) {
Set<Long> codeIdSet = new HashSet<>();
for (ClbCodeValue value : values) {
clbCodeValueMapper.deleteByPrimaryKey(value);
codeIdSet.add(value.getCodeId());
}
for (Long codeId : codeIdSet) {
clbCodeCache.reload(codeId);
}
return true;
}
@Override
public ClbCode updateCode(ClbCode code) {
clbCodeMapper.updateByPrimaryKeySelective(code);
// 判断如果行不为空,则迭代循环插入
if (code.getClbCodeValues() != null) {
processCodeValues(code);
}
clbCodeCache.remove(code.getCode());
clbCodeCache.reload(code.getCodeId());
return code;
}
@Override
public List<ClbCode> batchUpdate(IRequest request, List<ClbCode> codes) {
for (ClbCode code : codes) {
if (code.getCodeId() == null) {
self().createCode(code);
} else if (code.getCodeId() != null) {
self().updateCode(code);
}
}
return codes;
}
@Override
public List<ClbCodeValue> selectCodeValuesByParam(ClbCodeValue code) {
return clbCodeValueMapper.selectCodeValuesByParam(code);
}
} | true |
02a33c3accf790624abaa83849a18fadf29b8ace | Java | Gambareh/scale-handler | /src/main/java/models/HibernateInit.java | UTF-8 | 873 | 2.359375 | 2 | [] | no_license | package models;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateInit {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
Configuration cfg = new Configuration().configure("hibernate.cfg.xml");
ServiceRegistry registry = new StandardServiceRegistryBuilder()
.applySettings(cfg.getProperties()).build();
SessionFactory sf = cfg.buildSessionFactory(registry);
return sf;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void close() {
getSessionFactory().close();
}
}
| true |
326b243854ef34e62f4b9e8495c08fbf4e4078a2 | Java | justtimo/springInAction4 | /src/main/java/com/example/springinaction4/第一部分Spring核心/node2装配bean/charactor3通过Java装配bean/config/Text.java | UTF-8 | 4,485 | 2.90625 | 3 | [] | no_license | package com.example.springinaction4.第一部分Spring核心.node2装配bean.charactor3通过Java装配bean.config;
import com.example.springinaction4.第一部分Spring核心.node2装配bean.charactor1组件扫描.CompactDisc;
import com.example.springinaction4.第一部分Spring核心.node2装配bean.charactor1组件扫描.SgtPeppers;
import com.example.springinaction4.第一部分Spring核心.node2装配bean.charactor2自动化装配.CDPlayer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Random;
/**
* 我们看看Spring如何显示的装配bean
* 多数场景下通过组件扫描+自动装配实现SPring的自动化配置是推荐的方式.
* 但是想要将第三方库组件装配到应用中,你无法在他的类上添加@Component和@Autowaire,此时就不能使用自动化配置了
*
* 显示配置有两种方案: JavaConfig 和 XML
* JavaConfig更类型安全,强大且容易重构
* JavaConfig是配置代码,意味着他不应该包含业务逻辑,同时也不应该侵入业务代码中.尽管不是必需的
*
* 创建Config类的关键在于@Configuration注解,该注解表名这个类是配置类,该类应该包含在Spring应用上下文中如何创建bean的细节
*
* 尽管我们可以使用组件扫描和显示配置,但本节中,我们更关注显示配置,因此移除了@ComponentScan.
*
* 要在Config中声明bean,需要编写一个方法,并添加@Bean注解.
* @Bean 注解告诉Spring这个方法将会返回一个对象,该对象要注册为Spring上下文中的bean.默认情况下,bean的ID与方法名相同,可以通过name属性指定bean ID
*
* 还可以做些疯狂的事情,比如在一组CD中随机选择一个CompactDisc来播放:randomCompactDisc()
*
* 现在我们想要创建CDPlayer bean,CDPlayer依赖于CompactDisc.如何装配到一起呢?
* 在JavaConfig中最简单的方式就是引用创建bean的方法: cDPlayer()
* 看起来,CompactDisc是通过sgtPeppers()方法得到的,但并非如此.因为sgtPeppers()方法上有@Bean注解,Spring将会拦截所有对他的调用,并确保直接返回该方法
* 所创建的bean,而不是每次都对其进行实际的调用.
* 比如在引入一个CDPlayer anotherCDPlayer(),他和之前的bean一样.假如sgtPeppers()的调用像其他方法调用一样的话,那么每个CDPlayer都会有自己特有的SgtPeppers
* 实例.如果在现实生活中,这么做是有意义的,因为两台播放器不能使用同一张CD光盘.但是在软件领域,我们完全可以将同一个SgtPeppers实例注入到任意数量的其他bean中.
* 默认情况下,Spring中的bean都是单例的,我们没必要为第二个播放器创建完全相同的SgtPeppers实例.
* 所以,Spring会拦截对SgtPeppers()的调用,并确保返回的是Spring所创建的bean,也就是Spring本身在调用sgtPeppers()时所创建的CompactDisc bean,因此,
* 两个播放器会得到相同的SgtPeppers实例
*
* 还有另一种方式可以实现装配依赖:cDPlayer1().Spring调用cDPlayer1()创建CDPlayer时,会自动装配一个CompactDisc到方法中.借助这种技术,cDPlayer1()也能够将
* CompactDisc注入到CDPlayer的构造器中,而且不用明确指定CompactDisc的@Bean方法
*
* 还可以采用Setter的方式注入CompactDisc: cDPlayer2()
*
* 带有@Bean注解的方法可以采用任何必要的Java功能来产生bean实例.
*/
@Configuration
class CDPlayerConfig1111 {
@Bean(name = "wby")
public CompactDisc sgtPeppers(){
return new SgtPeppers();
}
@Bean
public CompactDisc randomCompactDisc() {
Random random = new Random();
int i = random.nextInt(5);
if (i==0){
return new SgtPeppers();
}else if (i == 1) {
return new SgtPeppers();
}else {
return new SgtPeppers();
}
}
@Bean
public CDPlayer cDPlayer(){
return new CDPlayer(sgtPeppers());
}
@Bean
public CDPlayer anotherCDPlayer(){
return new CDPlayer(sgtPeppers());
}
@Bean
public CDPlayer cDPlayer1(CompactDisc compactDisc111){
return new CDPlayer(compactDisc111);
}
@Bean
public CDPlayer cDPlayer2(CompactDisc compactDisc111){
CDPlayer cdPlayer = new CDPlayer(compactDisc111);
cdPlayer.setCd(compactDisc111);
return cdPlayer;
}
}
public class Text {
}
| true |
671195eae8e76aeefd867e06611196f380a42157 | Java | vksatish-lab/aws-exploration | /src/main/java/com/vadaks/aws/lambda/SavePersonHandler.java | UTF-8 | 2,148 | 2.65625 | 3 | [] | no_license | package com.vadaks.aws.lambda;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.PutItemOutcome;
import com.amazonaws.services.dynamodbv2.document.spec.PutItemSpec;
import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.vadaks.aws.model.PersonRequest;
import com.vadaks.aws.model.PersonResponse;
/**
* Sample lambda function for dynamo db read/write
*/
public class SavePersonHandler implements RequestHandler<PersonRequest, PersonResponse> {
private DynamoDB dynamoDb;
private String DYNAMODB_TABLE_NAME = "Person";
private Regions REGION = Regions.US_EAST_2;
public PersonResponse handleRequest(
PersonRequest personRequest, Context context) {
context.getLogger().log("Request received... - " + personRequest.getFirstName());
this.initDynamoDbClient();
persistData(personRequest);
PersonResponse personResponse = new PersonResponse();
personResponse.setMessage("Saved Successfully!!!");
return personResponse;
}
private PutItemOutcome persistData(PersonRequest personRequest)
throws ConditionalCheckFailedException {
return this.dynamoDb.getTable(DYNAMODB_TABLE_NAME)
.putItem(
new PutItemSpec().withItem(new Item()
.withNumber("id", Math.round(Math.random()))
.withString("firstName", personRequest.getFirstName())
.withString("lastName", personRequest.getLastName())));
}
private void initDynamoDbClient() {
AmazonDynamoDBClient client = new AmazonDynamoDBClient();
client.setRegion(Region.getRegion(REGION));
this.dynamoDb = new DynamoDB(client);
}
} | true |
ad3099cf983f5cc97e52e6601b94f930ef0a6b00 | Java | Chatzimichail/Car_manager_back | /src/main/java/com/luv2code/springboot/cruddemo/dao/EmployeeDAOHibernateImpl.java | UTF-8 | 6,542 | 2.703125 | 3 | [] | no_license | package com.luv2code.springboot.cruddemo.dao;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import com.luv2code.springboot.cruddemo.entity.Service;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.luv2code.springboot.cruddemo.entity.Car;
import org.springframework.transaction.annotation.Transactional;
@Repository
public class EmployeeDAOHibernateImpl implements EmployeeDAO {
// define field for entitymanager
private EntityManager entityManager;
// set up constructor injection
@Autowired
public EmployeeDAOHibernateImpl(EntityManager theEntityManager) {
entityManager = theEntityManager;
}
private static Connection con;
//UPDATE table_name SET field1 = new-value1, field2 = new-value2
public static void connectToDb(){
{
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/kogas?useUnicode=yes&characterEncoding=UTF-8","root","root");
//?useUnicode=yes&characterEncoding=UTF-8
//?useSSL=false&serverTimezone=UTC
System.out.println("Connected to DB");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
@Override
public int saveCar(Car theCar) {
connectToDb();
try {
PreparedStatement stmt=con.prepareStatement("INSERT INTO kogas.car (name, lastName, plaisio, pinakida, kibika, aloga, kodikosKinitira, xronologia, marka, modelo) " +
"VALUES(?,?,?,?,?,?,?,?,?,?)");
stmt.setString(1,theCar.getName());
stmt.setString(2,theCar.getLastName());
stmt.setString(3,theCar.getPlaisio());
stmt.setString(4,theCar.getPinakida());
stmt.setString(5,theCar.getKibika());
stmt.setString(6,theCar.getAloga());
stmt.setString(7,theCar.getKodikosKinitira());
stmt.setString(8,theCar.getXronologia());
stmt.setString(9,theCar.getMarka());
stmt.setString(10,theCar.getModelo());
int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
System.out.println("to modelo ine "+theCar.getModelo());
stmt.close();
} catch (Exception e) {
e.printStackTrace();
return 0;
}
return 1;
}
@Override
public int updateCar(Car theCar) {
connectToDb();
//UPDATE car SET name = ?, lastName= ?, plaisio= ?, kibika= ?, aloga=?, kodikosKinitira=?,xronologia=?, marka= ?, modelo=? WHERE pinakida = ?;
try {
PreparedStatement stmt=con.prepareStatement("UPDATE car SET name = ?, lastName= ?, plaisio= ?, aloga=?,kibika= ?, kodikosKinitira=?,xronologia=?, marka= ?, modelo=? WHERE pinakida = ?");
stmt.setString(1,theCar.getName());
stmt.setString(2,theCar.getLastName());
stmt.setString(3,theCar.getPlaisio());
stmt.setString(9,theCar.getModelo());
stmt.setString(5,theCar.getKibika());
stmt.setString(4,theCar.getAloga());
stmt.setString(6,theCar.getKodikosKinitira());
stmt.setString(7,theCar.getXronologia());
stmt.setString(8,theCar.getMarka());
stmt.setString(10,theCar.getPinakida());
int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
System.out.println("to plaisio ine "+theCar.getPlaisio());
stmt.close();
} catch (Exception e) {
e.printStackTrace();
return 0;
}
return 1;
}
@Override
public Car findCar(String thePinakida) {
connectToDb();
ResultSet rs = null;
PreparedStatement stmt = null;
Car tempCar = new Car();
try {
stmt=con.prepareStatement("select * from kogas.car where pinakida = ?");
stmt.setString(1,thePinakida);
rs=stmt.executeQuery();
//System.out.println(i+" records inserted");
} catch (Exception e) {
e.printStackTrace();
return tempCar;
}
try {
while (rs.next()) {
tempCar.setName(rs.getString("name"));
tempCar.setLastName(rs.getString("lastName"));
tempCar.setPlaisio(rs.getString("plaisio"));
tempCar.setKibika(rs.getString("kibika"));
tempCar.setAloga(rs.getString("aloga"));
tempCar.setKodikosKinitira(rs.getString("kodikosKinitira"));
tempCar.setXronologia(rs.getString("xronologia"));
tempCar.setMarka(rs.getString("marka"));
tempCar.setModelo(rs.getString("modelo"));
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
return tempCar;
}
@Override
public List<Service> findServises(String thePinakida) {
List<Service> myList = new ArrayList();
connectToDb();
ResultSet rs = null;
PreparedStatement stmt = null;
try {
stmt=con.prepareStatement("select * from kogas.service where pinakida = ? ORDER BY id DESC");
stmt.setString(1,thePinakida);
rs=stmt.executeQuery();
//System.out.println(i+" records inserted");
} catch (Exception e) {
e.printStackTrace();
return myList;
}
try {
while (rs.next()) {
Service service = new Service();
service.setPinakida(rs.getString("pinakida"));
service.setSxolia(rs.getString("sxolia"));
service.setXml1(rs.getString("xlm1"));
service.setXlm2(rs.getString("xlm2"));
service.setId(rs.getInt("id"));
myList.add(service);
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
return myList;
}
@Override
public int saveService(Service theService) {
connectToDb();
try {
PreparedStatement stmt=con.prepareStatement("INSERT INTO kogas.service (pinakida, xlm1, xlm2, sxolia) VALUES(?,?,?,?)");
stmt.setString(1,theService.getPinakida());
stmt.setString(2,theService.getXml1());
stmt.setString(3,theService.getXlm2());
stmt.setString(4,theService.getSxolia());
System.out.println("ta sxolia ine " + stmt);
int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
stmt.close();
} catch (Exception e) {
e.printStackTrace();
return 0;
}
return 1;
}
@Override
public int updateService (Service theService) {
connectToDb();
try {
PreparedStatement stmt=con.prepareStatement("UPDATE service SET sxolia = ?, xlm2 = ?, xlm1 = ? WHERE id = ?");
stmt.setString(1,theService.getSxolia());
stmt.setString(2,theService.getXlm2());
stmt.setString(3,theService.getXml1());
stmt.setInt(4,theService.getId());
int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
stmt.close();
} catch (Exception e) {
e.printStackTrace();
return 0;
}
return 1;
}
}
| true |
706055686e2f2065ae70602fdcd4ccca9c024848 | Java | idris/terptorrents | /terptorrents/src/terptorrents/models/LocalPieceComparatorLRU.java | UTF-8 | 404 | 2.578125 | 3 | [] | no_license | /**
*
*/
package terptorrents.models;
import java.util.Comparator;
/**
* @author Jonathan
*
*/
public class LocalPieceComparatorLRU implements Comparator<LocalPiece> {
public int compare(LocalPiece o1, LocalPiece o2) {
if(o1.getNumRequest() == o2.getNumRequest())
return 0;
else if(o1.getNumRequest() < o2.getNumRequest())
return -1;
else
return 1;
}
}
| true |
ec92131e68f7be590e2bd014ec68a860601755da | Java | arkhan2977/smart-timetable | /SmartTimeTable/src/com/ajouroid/timetable/DBAdapter.java | UTF-8 | 28,761 | 2.21875 | 2 | [] | no_license | package com.ajouroid.timetable;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.IBinder;
import android.util.Log;
public class DBAdapter {
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb; // 데이터베이스를 저장
private static final int DATABASE_VERSION = 7;
private final Context mCtx;
public static final int TYPE_ASSIGNMENT = 0;
public static final int TYPE_TEST = 1;
public static final int TYPE_EXTRA = 2;
public static final int TYPE_ETC = 3;
private class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context) {
super(context, "timetable.db", null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE subject (_id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "`name` TEXT UNIQUE,"
+ "`classroom` TEXT,"
+ "`professor` TEXT,"
+ "`email` TEXT," + "`color` INTEGER)");
db.execSQL("CREATE TABLE times ("
+ "`_id` INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "`subject` TEXT,"
+ "`day` INTEGER,"
+ "`starttime` INTEGER,"
+ "`endtime` INTEGER, "
+ "FOREIGN KEY(subject) REFERENCES subject(name) ON DELETE CASCADE ON UPDATE CASCADE)");
db.execSQL("CREATE TABLE tasks ("
+ "`_id` INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "`subject` TEXT,"
+ "`type` INTEGER,"
+ "`title` TEXT,"
+ "`desc` TEXT,"
+ "`taskdate` TEXT,"
+ "`usetime` INTEGER,"
+ "FOREIGN KEY(subject) REFERENCES subject(name) ON DELETE CASCADE ON UPDATE CASCADE)");
db.execSQL("CREATE TABLE stations ("
+ "`_id` INTEGER PRIMARY KEY, "
+ "`station_nm` text, "
+ "`station_number` int, "
+ "`start` integer)");
db.execSQL("CREATE TABLE favorite ("
+ "_id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "START_ID TEXT,"
+ "START_NM TEXT,"
+ "DEST_ID TEXT,"
+ "DEST_NM TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
backup("upgrade.db", db);
db.execSQL("DROP TABLE IF EXISTS subject");
db.execSQL("DROP TABLE IF EXISTS times");
db.execSQL("DROP TABLE IF EXISTS tasks");
db.execSQL("DROP TABLE IF EXISTS stations");
db.execSQL("DROP TABLE IF EXISTS favorite");
onCreate(db);
restore("upgrade.db", db);
}
}
public DBAdapter(Context ctx) {
this.mCtx = ctx;
}
public void open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
}
public void close() {
mDbHelper.close();
}
public Cursor getFavoriteCursor() {
Cursor cursor = mDb.rawQuery("SELECT * FROM favorite", null);
cursor.moveToFirst();
return cursor;
}
public void addFavoriteInfo(String s_id, String s_nm, String d_id, String d_nm){
ContentValues initialValues = new ContentValues();
initialValues.clear();
initialValues.put("START_ID", s_id);
initialValues.put("START_NM", s_nm);
initialValues.put("DEST_ID", d_id);
initialValues.put("DEST_NM", d_nm);
mDb.insert("favorite", null, initialValues);
}
public void deleteFavoriteInfo(int id){
mDb.delete("favorite", "_id = '" + id + "'", null);
}
public boolean addSubject(String name, String classroom, String professor,
String email, int color) {
ContentValues row = new ContentValues();
row.put("name", name);
row.put("classroom", classroom);
row.put("professor", professor);
row.put("email", email);
row.put("color", color);
long result = mDb.insert("subject", null, row);
if (result == -1)
return false;
else {
Log.d("database", name + " (" + classroom
+ ") : Added to the Database");
return true;
}
}
public boolean addSubject(Subject newSubject) {
return addSubject(newSubject.getName(), newSubject.getClassRoom(),
newSubject.getProfessor(), newSubject.getEmail(),
newSubject.getColor());
}
public boolean addTime(String subject, ClassTime time) {
time.setSubject(subject);
boolean valid = isValid(time);
if (!valid)
return false;
int startMin = time.getStartTime().toMinute();
int endMin = time.getEndTime().toMinute();
Cursor c = mDb.rawQuery("SELECT * FROM times WHERE subject = '"
+ subject + "' and day = '" + time.getDay()
+ "' AND (startTime <= '" + endMin + "' AND endTime >= '"
+ startMin + "') ORDER BY starttime ASC", null);
int iStart = c.getColumnIndex("starttime");
int iEnd = c.getColumnIndex("endtime");
while (c.moveToNext()) {
int start = c.getInt(iStart);
int end = c.getInt(iEnd);
// 연결되는 시간을 합침
if (end > endMin) {
time.setEndTime(new Time(end));
endMin = time.getEndTime().toMinute();
}
if (start < startMin) {
time.setStartTime(new Time(start));
startMin = time.getStartTime().toMinute();
}
mDb.delete("times", "_id = '" + c.getInt(0) + "'", null);
}
c.close();
ContentValues row = new ContentValues();
row.put("subject", subject);
row.put("day", time.getDay());
row.put("starttime", startMin);
row.put("endtime", endMin);
long result = mDb.insert("times", null, row);
if (result == -1)
return false;
else {
Intent updater = new Intent();
updater.setAction(AlarmService.UPDATE_ACTION);
mCtx.sendBroadcast(updater);
return true;
}
}
AlarmService morningCallService;
public void bind() {
Intent i = new Intent(mCtx, AlarmService.class);
// startService(i);
mCtx.bindService(i, conn, Context.BIND_AUTO_CREATE);
if (morningCallService != null) {
morningCallService.setMorningCall();
morningCallService.setNextClassStartCall();
morningCallService.setTaskTimeCall();
}
}
public void unbind() {
mCtx.unbindService(conn);
}
private ServiceConnection conn = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder rawBinder) {
morningCallService = ((AlarmService.AlarmBinder) rawBinder)
.getService();
}
public void onServiceDisconnected(ComponentName name) {
morningCallService = null;
}
};
public Subject getSubject(String name) {
Cursor c = mDb.rawQuery("SELECT * FROM subject WHERE name = '" + name
+ "'", null);
if (c.moveToNext()) {
int iName = c.getColumnIndex("name");
int iClass = c.getColumnIndex("classroom");
int iProf = c.getColumnIndex("professor");
int iEmail = c.getColumnIndex("email");
int iColor = c.getColumnIndex("color");
Subject retVal = new Subject(c.getString(iName),
c.getString(iClass), c.getString(iProf),
c.getString(iEmail), c.getInt(iColor));
c.close();
return retVal;
} else {
c.close();
return null;
}
}
public Subject getSubject(int id) {
Cursor c = mDb.rawQuery("SELECT * FROM subject WHERE _id = '" + id
+ "'", null);
if (c.moveToNext()) {
int iName = c.getColumnIndex("name");
int iClass = c.getColumnIndex("classroom");
int iProf = c.getColumnIndex("professor");
int iEmail = c.getColumnIndex("email");
int iColor = c.getColumnIndex("color");
Subject retVal = new Subject(c.getString(iName),
c.getString(iClass), c.getString(iProf),
c.getString(iEmail), c.getInt(iColor));
c.close();
return retVal;
} else {
c.close();
return null;
}
}
public String getSubjectName(int id) {
Cursor c = mDb.rawQuery("SELECT name FROM subject WHERE _id = '" + id
+ "'", null);
String name = null;
if (c.getCount() > 0) {
c.moveToFirst();
name = c.getString(0);
}
c.close();
return name;
}
public Cursor getSubjectCursor() {
Cursor cursor = mDb.rawQuery("SELECT * FROM subject ORDER BY name asc",
null);
return cursor;
}
public Cursor getSubjectCursor(String subject) {
Cursor cursor = mDb.rawQuery("SELECT * FROM subject WHERE name = '"
+ subject + "'", null);
cursor.moveToFirst();
return cursor;
}
public Cursor getSubjectCursor(int id) {
Cursor cursor = mDb.rawQuery("SELECT * FROM subject WHERE _id = '"
+ id + "'", null);
cursor.moveToFirst();
return cursor;
}
public boolean updateSubject(int _id, Subject updater, String oldName) {
ContentValues row = new ContentValues();
row.put("name", updater.getName());
row.put("classroom", updater.getClassRoom());
row.put("professor", updater.getProfessor());
row.put("email", updater.getEmail());
row.put("color", updater.getColor());
Cursor tempC = mDb.rawQuery("select _id, name from subject where name = '" + updater.getName() + "'", null);
if (tempC.getCount() > 0)
{
tempC.moveToFirst();
String name = tempC.getString(tempC.getColumnIndex("name"));
tempC.close();
if (name.compareTo(updater.getName()) != 0)
return false;
}
mDb.update("subject", row, "_id = '" + _id + "'", null);
mDb.delete("times", "subject = '" + oldName + "'", null);
ArrayList<ClassTime> times = updater.getTime();
for (int i = 0; i < times.size(); i++) {
this.addTime(updater.getName(), times.get(i));
}
if (updater.getName().compareTo(oldName) != 0) {
mDb.execSQL("UPDATE tasks SET subject = '" + updater.getName()
+ "' WHERE subject = '" + oldName + "'");
}
return true;
}
public Cursor getTimeCursor(String subject) {
Cursor cursor = mDb.rawQuery("select * from times where subject = '"
+ subject + "' ORDER BY day asc, starttime asc", null);
return cursor;
}
public Subject[] getAllSubjects() {
Cursor c = mDb
.rawQuery("SELECT * FROM subject ORDER BY name asc", null);
Subject[] retVal = null;
if (c.getCount() > 0) {
retVal = new Subject[c.getCount()];
int i = 0;
while (c.moveToNext()) {
int iName = c.getColumnIndex("name");
int iClass = c.getColumnIndex("classroom");
int iProf = c.getColumnIndex("professor");
int iEmail = c.getColumnIndex("email");
int iColor = c.getColumnIndex("color");
retVal[i] = new Subject(c.getString(iName),
c.getString(iClass), c.getString(iProf),
c.getString(iEmail), c.getInt(iColor));
i++;
}
}
c.close();
return retVal;
}
public ClassTime[] getTimes(String subject) {
Cursor c = mDb.rawQuery("SELECT * FROM times" + " WHERE subject = '"
+ subject + "' ORDER BY day asc, starttime asc", null);
int iDay = c.getColumnIndex("day");
int iStart = c.getColumnIndex("starttime");
int iEnd = c.getColumnIndex("endtime");
if (c.getCount() > 0) {
ClassTime[] retVal = new ClassTime[c.getCount()];
int i = 0;
while (c.moveToNext()) {
retVal[i] = new ClassTime(c.getInt(iDay), new Time(
c.getInt(iStart)), new Time(c.getInt(iEnd)));
retVal[i].setSubject(subject);
i++;
}
c.close();
return retVal;
} else {
c.close();
return null;
}
}
public void deleteSubject(String subject) {
mDb.delete("tasks", "subject = '" + subject + "'", null);
mDb.delete("times", "subject = '" + subject + "'", null);
mDb.delete("subject", "name = '" + subject + "'", null);
}
public boolean isValid(ClassTime time) {
int day = time.getDay();
int startMin = time.getStartTime().toMinute();
int endMin = time.getEndTime().toMinute();
Cursor cursor = mDb.rawQuery("SELECT * FROM times WHERE day = '" + day
+ "' AND (startTime < '" + endMin + "' AND endTime > '"
+ startMin + "')", null);
if (cursor.getCount() > 0)
{
cursor.moveToFirst();
String subject = cursor.getString(cursor.getColumnIndex("subject"));
if (subject.compareTo(time.getSubject()) == 0)
return true;
else return false;
}
else
return true;
}
public void init() {
open();
mDb.execSQL("DROP TABLE IF EXISTS subject");
mDb.execSQL("DROP TABLE IF EXISTS times");
mDb.execSQL("DROP TABLE IF EXISTS tasks");
mDb.execSQL("DROP TABLE IF EXISTS stations");
mDb.execSQL("DROP TABLE IF EXISTS favorite");
mDbHelper.onCreate(mDb);
close();
}
public Cursor getSelectedTimes(int startDay, int endDay, int startMin,
int endMin) {
Cursor cursor;
cursor = mDb.rawQuery("SELECT * FROM times WHERE (day >= '" + startDay
+ "' AND day <= '" + endDay + "') AND (startTime < '" + endMin
+ "' AND endTime > '" + startMin + "')", null);
return cursor;
}
public Cursor getTaskCursor() {
Cursor cursor;
cursor = mDb.rawQuery("SELECT * FROM tasks ORDER BY taskdate asc", null);
return cursor;
}
public Cursor getValidTaskCursor() {
Cursor cursor;
cursor = mDb.rawQuery("SELECT * FROM tasks WHERE taskdate > '" + System.currentTimeMillis() + "' ORDER BY taskdate asc", null);
return cursor;
}
public Cursor getTaskCursor(String subject) {
Cursor cursor;
long now = System.currentTimeMillis();
cursor = mDb.rawQuery("SELECT * FROM tasks WHERE subject = '" + subject
+ "' AND taskdate > '" + now + "' ORDER BY taskdate asc", null);
return cursor;
}
public ArrayList<Task> getTask(String subject) {
SimpleDateFormat form = new SimpleDateFormat(mCtx.getResources()
.getString(R.string.dateformat), Locale.US);
String dateStr;
dateStr = form.format(new Date(System.currentTimeMillis()));
Cursor cursor = mDb.rawQuery("SELECT * FROM tasks WHERE subject = '" + subject
+ "' AND taskdate > '" + dateStr + "' ORDER BY taskdate asc", null);
ArrayList<Task> taskList = new ArrayList<Task>();
int iId = cursor.getColumnIndex("_id");
int itaskDate = cursor.getColumnIndex("taskdate");
int itaskTitle = cursor.getColumnIndex("title");
int itaskType = cursor.getColumnIndex("type");
int iSubject = cursor.getColumnIndex("subject");
int iUsetime = cursor.getColumnIndex("usetime");
Task task;
while(cursor.moveToNext())
{
task = new Task(cursor.getString(iSubject), cursor.getString(itaskTitle), cursor.getLong(itaskDate), cursor.getInt(itaskType));
task.setId(cursor.getInt(iId));
if (cursor.getInt(iUsetime) == 1)
task.setUsetime(true);
else
task.setUsetime(false);
Date taskDate = new Date(task.getTaskDate());
Long dist = taskDate.getTime() - System.currentTimeMillis();
task.setRemain(dist);
taskList.add(task);
}
cursor.close();
Cursor dCursor = mDb.rawQuery("SELECT * FROM tasks WHERE subject = '" + subject
+ "' AND taskdate <= '" + dateStr + "' ORDER BY taskdate asc", null);
while(dCursor.moveToNext())
{
task = new Task(dCursor.getString(iSubject), dCursor.getString(itaskTitle), dCursor.getLong(itaskDate), dCursor.getInt(itaskType));
task.setId(dCursor.getInt(iId));
if (dCursor.getInt(iUsetime) == 1)
task.setUsetime(true);
else
task.setUsetime(false);
task.setRemain(-1);
taskList.add(task);
}
dCursor.close();
return taskList;
}
public void addTask(String subject, int type, String title, String desc,
long datetime, boolean useTime) {
ContentValues row = new ContentValues();
row.put("subject", subject);
row.put("type", type);
row.put("title", title);
row.put("desc", desc);
row.put("taskdate", datetime);
if (useTime)
row.put("usetime", 1);
else
row.put("usetime", 0);
mDb.insert("tasks", null, row);
Intent updater = new Intent();
updater.setAction(AlarmService.UPDATE_ACTION);
mCtx.sendBroadcast(updater);
}
public void updateTask(int _id, String subject, int type, String title,
String desc, long datetime, boolean useTime) {
ContentValues row = new ContentValues();
row.put("subject", subject);
row.put("type", type);
row.put("title", title);
row.put("desc", desc);
row.put("taskdate", datetime);
if (useTime)
row.put("usetime", 1);
else
row.put("usetime", 0);
mDb.update("tasks", row, "_id = '" + _id + "'", null);
Intent updater = new Intent();
updater.setAction(AlarmService.UPDATE_ACTION);
mCtx.sendBroadcast(updater);
}
public Cursor getTask(int _id) {
Cursor cursor = mDb.rawQuery("SELECT * FROM tasks WHERE _id = '" + _id
+ "'", null);
cursor.moveToFirst();
return cursor;
}
public void deleteTask(int _id) {
mDb.delete("tasks", "_id = '" + _id + "'", null);
}
public void deleteTime(int _id) {
mDb.delete("times", "_id = '" + _id + "'", null);
}
public boolean isOpen() {
if (mDb == null)
return false;
return mDb.isOpen();
}
public static long distance(Date task, Date now) {
if (task.compareTo(now) < 0)
return -1;
else
return task.getTime() - now.getTime();
}
public Time getFirstClassTime(int day) {
Cursor c = mDb.rawQuery("SELECT * FROM times WHERE day = '" + day + "'"
+ " ORDER BY starttime asc", null);
int iStart = c.getColumnIndex("starttime");
Time t = null;
if (c.moveToFirst()) {
int time = c.getInt(iStart);
t = new Time(time);
}
c.close();
return t;
}
public Task getTaskTime() {
Task task = null;
Calendar curTime = Calendar.getInstance();
curTime.add(Calendar.HOUR_OF_DAY, 1);
Date date = curTime.getTime();
SimpleDateFormat format = new SimpleDateFormat(mCtx.getResources().getString(R.string.dateformat), Locale.US);
String currentTime = format.format(date);
Cursor tcursor = mDb.rawQuery("SELECT * FROM tasks WHERE taskdate > '"
+ currentTime + "' AND usetime = 1 ORDER BY taskdate asc", null);
int iId = tcursor.getColumnIndex("_id");
int itaskDate = tcursor.getColumnIndex("taskdate");
int itaskTitle = tcursor.getColumnIndex("title");
int itaskType = tcursor.getColumnIndex("type");
int iSubject = tcursor.getColumnIndex("subject");
if (tcursor.moveToFirst()) {
task = new Task(tcursor.getString(iSubject), tcursor.getString(itaskTitle), tcursor.getLong(itaskDate), tcursor.getInt(itaskType));
task.setId(tcursor.getInt(iId));
}
tcursor.close();
return task;
}
public ArrayList<Task> getNextDayTasks() {
Calendar date = Calendar.getInstance();
date.set(Calendar.HOUR_OF_DAY, 0);
date.set(Calendar.MINUTE, 0);
date.set(Calendar.SECOND, 0);
date.add(Calendar.DAY_OF_MONTH, 1);
Date today = date.getTime();
date.add(Calendar.DAY_OF_MONTH, 1);
Date nextday = date.getTime();
SimpleDateFormat format = new SimpleDateFormat(mCtx.getResources()
.getString(R.string.dateformat), Locale.US);
Cursor ycursor = mDb.rawQuery(
"SELECT * FROM tasks WHERE taskdate >= '"
+ format.format(today) + "' AND taskdate < '"
+ format.format(nextday) + "' ORDER BY taskdate asc",
null);
ArrayList<Task> list = new ArrayList<Task>();
int itaskDate = ycursor.getColumnIndex("taskdate");
int itaskType = ycursor.getColumnIndex("type");
int itaskTitle = ycursor.getColumnIndex("title");
int iSubject = ycursor.getColumnIndex("subject");
while (ycursor.moveToNext()) {
Task temp = new Task(ycursor.getString(iSubject), ycursor.getString(itaskTitle), ycursor.getLong(itaskDate), ycursor.getInt(itaskType));
list.add(temp);
}
ycursor.close();
return list;
}
public AlarmTime getNextClassTime(int day, Time beforeTime) {
int beforeTimeMinute = beforeTime.toMinute();
boolean today = true;
Cursor c = mDb.rawQuery("SELECT * FROM times WHERE (day = '" + day
+ "'" + " AND starttime > '" + beforeTimeMinute
+ "') OR day > '" + day + "' ORDER BY day asc, starttime asc",
null);
if (c.getCount() == 0) // 아무것도 찾지 못했을 경우 이전 요일에서도 찾음
{
c.close();
c = mDb.rawQuery(
"SELECT * FROM times ORDER BY day asc, starttime asc", null);
if (c.getCount() == 0) // 여기서도 찾지 못하면 null
return null;
else
today = false;
}
int iSubject = c.getColumnIndex("subject");
int iDay = c.getColumnIndex("day");
int iStart = c.getColumnIndex("starttime");
AlarmTime t = null;
if (c.moveToFirst()) {
t = new AlarmTime(c.getInt(iDay), c.getInt(iStart));
t.setIsToday(today);
t.setSubject(c.getString(iSubject));
}
c.close();
return t;
}
public boolean isNowClassTime(int day, Time t, Time restTime)
{
int tMin = t.toMinute();
String sql = "SELECT * FROM times WHERE day = '" + day + "' AND starttime < '" + tMin + "' AND endtime > '" + (tMin + restTime.toMinute()) + "'";
Cursor c = mDb.rawQuery(sql, null);
if (c.getCount() > 0)
return true;
else return false;
}
public int getIdFromTitle(String title)
{
int id;
String sql = "SELECT _id FROM subject WHERE name = '" + title + "'";
Cursor c = mDb.rawQuery(sql, null);
if (c.getCount() > 0)
{
c.moveToFirst();
id = c.getInt(0);
}
else
id = -1;
c.close();
return id;
}
public static final String SEP = "\n";
public void backup(String filename, SQLiteDatabase db)
{
String dir = "/sdcard/SmartTimeTable";
File dirFile = new File(dir);
if (!dirFile.exists())
{
dirFile.mkdirs();
}
//String file = dir + "/backup" + System.currentTimeMillis() + ".txt";
String file = dir + "/" + filename;
File output = new File(file);
try {
FileOutputStream fos = new FileOutputStream(output);
// 과목 정보 입력
Cursor subjectCursor = db.rawQuery("SELECT * FROM subject", null);
int iId = subjectCursor.getColumnIndex("_id");
int iName = subjectCursor.getColumnIndex("name");
int iClassRoom = subjectCursor.getColumnIndex("classroom");
int iProf = subjectCursor.getColumnIndex("professor");
int iEmail = subjectCursor.getColumnIndex("email");
int iColor = subjectCursor.getColumnIndex("color");
fos.write(new String(subjectCursor.getCount() + "_SUBJECTS").getBytes());
String data = SEP;
while(subjectCursor.moveToNext())
{
int _id = subjectCursor.getInt(iId);
String name = subjectCursor.getString(iName);
String classroom = subjectCursor.getString(iClassRoom);
String prof = subjectCursor.getString(iProf);
String email = subjectCursor.getString(iEmail);
int color = subjectCursor.getInt(iColor);
data += _id + SEP + name + SEP + classroom + SEP + prof
+ SEP + email + SEP + color;
fos.write(data.getBytes());
data = SEP;
}
subjectCursor.close();
Cursor timeCursor = db.rawQuery("SELECT * FROM times", null);
iId = timeCursor.getColumnIndex("_id");
int iSubject = timeCursor.getColumnIndex("subject");
int iDay = timeCursor.getColumnIndex("day");
int iStart = timeCursor.getColumnIndex("starttime");
int iEnd = timeCursor.getColumnIndex("endtime");
fos.write((SEP + timeCursor.getCount() + "_TIMES").getBytes());
data = SEP;
while(timeCursor.moveToNext())
{
int _id = timeCursor.getInt(iId);
String subject = timeCursor.getString(iSubject);
int day = timeCursor.getInt(iDay);
int start = timeCursor.getInt(iStart);
int end = timeCursor.getInt(iEnd);
data += _id + SEP + subject + SEP + day + SEP + start + SEP + end;
fos.write(data.getBytes());
data=SEP;
}
timeCursor.close();
Cursor taskCursor = db.rawQuery("SELECT * FROM tasks", null);
iId = taskCursor.getColumnIndex("_id");
iSubject = taskCursor.getColumnIndex("subject");
int iType = taskCursor.getColumnIndex("type");
int iTitle = taskCursor.getColumnIndex("title");
int iDesc = taskCursor.getColumnIndex("desc");
int iTaskdate = taskCursor.getColumnIndex("taskdate");
int iUsetime = taskCursor.getColumnIndex("usetime");
fos.write((SEP + taskCursor.getCount() + "_TASKS").getBytes());
data = SEP;
while(taskCursor.moveToNext())
{
int _id = taskCursor.getInt(iId);
String subject = taskCursor.getString(iSubject);
int type = taskCursor.getInt(iType);
String title = taskCursor.getString(iTitle);
String desc = taskCursor.getString(iDesc);
desc = desc.replace("\n", "\t");
String taskdate = taskCursor.getString(iTaskdate);
int usetime = taskCursor.getInt(iUsetime);
data += _id + SEP + subject + SEP + type + SEP + title + SEP + desc + SEP + taskdate + SEP + usetime;
fos.write(data.getBytes());
data=SEP;
}
taskCursor.close();
fos.flush();
fos.close();
//restore(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void backup(String filename)
{
open();
backup(filename, mDb);
close();
}
public void restore(String filename, SQLiteDatabase db)
{
mDb = db;
File file = new File("/sdcard/SmartTimeTable/" + filename);
try {
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[8192];
int n;
String data = "";
while ((n=fis.read(buffer)) != -1)
{
data += new String(buffer, 0, n);
}
fis.close();
String[] parsedData = data.split(SEP);
int cnt=0;
String[] temp = parsedData[cnt].split("_");
int subCount = Integer.parseInt(temp[0]);
cnt++;
for (int j=0; j<subCount; j++)
{
int _id;
String name;
String classroom;
String prof;
String email;
int color;
_id = Integer.parseInt(parsedData[cnt++]);
name = parsedData[cnt++];
classroom = parsedData[cnt++];
prof = parsedData[cnt++];
email = parsedData[cnt++];
color = Integer.parseInt(parsedData[cnt++]);
this.addSubject(name, classroom, prof, email, color);
Log.d("SmartTimeTable", "Restore Subject:" + _id + "," + name + "," + classroom + "," + prof + "," + email + "," + color);
}
temp = parsedData[cnt].split("_");
int timeCount = Integer.parseInt(temp[0]);
cnt++;
for (int j=0; j<timeCount; j++)
{
int _id;
String subject;
int day;
int starttime;
int endtime;
_id = Integer.parseInt(parsedData[cnt++]);
subject = parsedData[cnt++];
day = Integer.parseInt(parsedData[cnt++]);
starttime = Integer.parseInt(parsedData[cnt++]);
endtime = Integer.parseInt(parsedData[cnt++]);
this.addTime(subject, new ClassTime(day, new Time(starttime), new Time(endtime)));
Log.d("SmartTimeTable", "Restore Time:" + _id + "," + subject + "," + day + "," + starttime + "," + endtime);
}
temp = parsedData[cnt].split("_");
int taskCount = Integer.parseInt(temp[0]);
cnt++;
for (int j=0; j<taskCount; j++)
{
try
{
int _id = Integer.parseInt(parsedData[cnt++]);
String subject = parsedData[cnt++];
int type = Integer.parseInt(parsedData[cnt++]);
String title = parsedData[cnt++];
String desc = parsedData[cnt++];
desc = desc.replace("\t", "\n");
long taskdate = Long.parseLong(parsedData[cnt++]);
int usetime = Integer.parseInt(parsedData[cnt++]);
boolean bUsetime;
if (usetime == 1)
bUsetime = true;
else
bUsetime = false;
this.addTask(subject, type, title, desc, taskdate, bUsetime);
Log.d("SmartTimeTable", "Restore Task:" + _id + "," + subject + "," + type + "," + title + "," + desc + "," + taskdate + "," + usetime);
} catch (NumberFormatException e)
{
e.printStackTrace();
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void restore(String filename)
{
init();
open();
restore(filename, mDb);
close();
}
}
| true |
6334c6bb1f42148e5a5952542147bcf865bd9d2b | Java | anilpank/java8examples | /src/org/anon/ListExample.java | UTF-8 | 2,912 | 3.4375 | 3 | [
"MIT"
] | permissive | package org.anon;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
*
* @author averma
*
*/
public class ListExample {
public static void main(String[] args) {
ListExample listEx = new ListExample();
listEx.ex();
}
public void ex() {
List<String> list = new ArrayList<>();
list.add("John");
list.add("Mary");
list.add("Steve");
list.add("Abraham");
list.add("Bill");
list.add("Donald");
list.add("Joe");
list.add("Angela");
//print all items in list
list.stream().forEach(val -> System.out.print(val+","));
System.out.println();
//print items starting with A
list.stream().filter(val -> val.startsWith("A")).forEach(val -> System.out.print(val+","));
System.out.println();
System.out.println(list.stream().allMatch(val-> val.contains("m")));
System.out.println(list.stream().anyMatch(val -> val.startsWith("M")));
System.out.println();
list.stream().filter(val -> val.startsWith("P")).collect(Collectors.toList()).forEach(v -> System.out.print(v+","));
System.out.println();
System.out.println(list.stream().count());
System.out.println(list.stream().distinct().count());
System.out.println(list.stream().filter(v -> v.endsWith("i")).findAny());
System.out.println(list.stream().findFirst().get());
int[][] arr2d = {{1,2}, {5,6}, {7,8}, {9,10}};
String[][] multiArray = {{"1","2","3"},{"4","5","6"}};
String[] strings = Arrays.stream(multiArray)
.flatMap(Arrays::stream)
.toArray(size -> new String[size]);
list.stream().limit(2).forEach(System.out::print);
System.out.println();
list.stream().map(v-> v.length()*3).forEach(System.out::print);
System.out.println();
list.forEach(v -> System.out.print(v.length()*5));
System.out.println();
list.stream().mapToInt(v -> v.length()).forEach(w->System.out.print(w*w));
System.out.println();
list.stream().map(v -> v.length()).forEach(w->System.out.print(w*w));
System.out.println();
System.out.println(list.stream().max((a,b) -> a.length() - b.length()).get());
System.out.println(list.stream().min((a,b) -> a.compareTo(b)).get());
System.out.println(list.stream().noneMatch(a-> a.equals("Anila")));
List<Integer> intList = new ArrayList<>();
intList.add(1);
intList.add(2);
intList.add(3);
intList.add(4);
intList.add(5);
intList.add(6);
System.out.println(intList.stream().reduce(1,(a,b) -> a*b));
System.out.println(intList.stream().reduce(Integer::max).get());
list.stream().skip(1).forEach(System.out::print);
System.out.println();
list.stream().sorted((a,b) -> a.length()-b.length()).forEach(System.out::print);
System.out.println();
list.stream().sorted((a,b) -> a.compareTo(b)).forEach(System.out::print);
System.out.println();
System.out.println(list.stream().toArray().length);
}
}
| true |
919862136a0ab932be9ef1870321267898d6c9d9 | Java | jeanlks/blog_posts | /CQRS/QueryModel/src/test/java/com/example/dealership/query/repo/QueryRepoITest.java | UTF-8 | 2,183 | 2.046875 | 2 | [] | no_license | package com.example.dealership.query.repo;
import com.example.dealership.query.datamodel.CarOfferQuickDescriptionDTO;
import com.example.dealership.query.repo.CarOffersRepo;
import org.assertj.core.api.Assertions;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@SpringBootTest({"spring.datasource.driver-class-name=org.h2.Driver",
"spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1",
"spring.datasource.username=sa",
"spring.datasource.password=sa",
"spring.activemq.broker-url=vm://embedded?broker.persistent=false,useShutdownHook=false",
"spring.activemq.in-memory=true",
"domain.events.offer.admitted=x1",
"domain.events.offer.sold=x2"
})
@FixMethodOrder(value = MethodSorters.NAME_ASCENDING)
public class QueryRepoITest {
public static final CarOfferQuickDescriptionDTO audi = new CarOfferQuickDescriptionDTO("1", "audi", "A8");
@Autowired
CarOffersRepo carOffersRepo;
@Test
public void canaryTest() {
assertThat(carOffersRepo).isNotNull();
}
@Test
public void fetchCarsForSale_listInFutureNotNull() {
final Flux<CarOfferQuickDescriptionDTO> carForSaleDTOFlux = carOffersRepo.findAll();
StepVerifier
.create(carForSaleDTOFlux)
.expectSubscription()
.assertNext((car) -> Assertions.assertThat(car.id).isEqualTo("1"))
.verifyComplete();
}
@Before
public void putDataInCache() {
carOffersRepo.save(audi).subscribe();
}
@SpringBootApplication
public static class DummyStarter {
}
}
| true |
0a317378589ccefe22bd46e5683935f5e0c19abe | Java | DelvairJr/biblioteva_JavaJPA | /src/br/com/biblioteca/model/Livro.java | UTF-8 | 1,336 | 2.171875 | 2 | [] | no_license | package br.com.biblioteca.model;
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
@Entity
public class Livro implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String titulo;
@OneToOne(cascade = CascadeType.ALL)
private Resumo resumo;
@JoinColumn(name = "editora_id") //para informar qual coluna que uni as duas tabelas
@ManyToOne(cascade = CascadeType.ALL) //Vários livros pertencem a uma editora
private Editora editora;
public Editora getEditora() {
return editora;
}
public void setEditora(Editora editora) {
this.editora = editora;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitulo() {
return titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public Resumo getResumo() {
return resumo;
}
public void setResumo(Resumo resumo) {
this.resumo = resumo;
}
}
| true |
fa6ced506c7255c290da7e34378f59e21a6f05d8 | Java | JojoGelb/Minecraft_plugin_vrac | /src/mc_plugin/TimerTask.java | UTF-8 | 390 | 2.203125 | 2 | [] | no_license | package mc_plugin;
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitRunnable;
public class TimerTask extends BukkitRunnable {
private int timer = 10;
@Override
public void run() {
if(timer == 0) {
Bukkit.broadcastMessage("Fin du Timer");
cancel();
}
//Bukkit.broadcastMessage("Timer: " + timer);
timer = timer -1; // ou aussi timer --;
}
}
| true |
82194b2a91ee0ac14697d28b000dcbe074adfa87 | Java | dianasosamazariegos/HDT7 | /BinaryTree.java | UTF-8 | 2,748 | 3.6875 | 4 | [] | no_license | /*
Universidad del Valle de Guatemala
Algoritmos y Estructuras de Datos
Autor: Diana Sosa 18842 -Fecha: 18/03/2020
*/
package hdt7;
/**
*
* @author diana
*/
public class BinaryTree {
Asociacion<String,String> data;
BinaryTree left;
BinaryTree right;
//Extraído de: https://www.baeldung.com/java-binary-tree
public BinaryTree() {
data = null;
left = null;
right = null;
}
public BinaryTree(Asociacion<String,String> data) {
this.data = data;
left = null;
right = null;
}
public void setData(Asociacion<String,String> data) {
this.data = data;
}
public Asociacion<String,String> getValue() {
return data;
}
//Metodo para insertar nodos
public void insert(Asociacion<String,String> value) {
int res = stringCompare(value.getKey(), data.getKey());
if (res <= 0) {
if (left == null) {
left = new BinaryTree(value);
} else {
left.insert(value);
}
} else {
if (right == null) {
right = new BinaryTree(value);
} else {
right.insert(value);
}
}
}
//Metodo para encontrar un nodo
public boolean contains(String value) {
int res = stringCompare(value, data.getKey());
if (res == 0) {
return true;
} else if (res < 0) {
if (left == null) {
return false;
} else {
return left.contains(value);
}
} else {
if (right == null) {
return false;
} else {
return right.contains(value);
}
}
}
//Metodo que hace las traducciones
public String get(String key) {
int res = stringCompare(key, data.getKey());
if (res == 0) {
return data.getValue();
} else {
if (res < 0) {
return left.get(key);
} else {
return right.get(key);
}
}
}
//Metodo para mostrar los nodos en orden
public void printInOrder() {
if (left != null) {
left.printInOrder();
}
System.out.println(this.data.toString());
if (right != null) {
right.printInOrder();
}
}
//Metodo que compara las asociaciones
public int stringCompare(String str1, String str2) {
int l1 = str1.length();
int l2 = str2.length();
int lmin = Math.min(l1, l2);
for (int i = 0; i < lmin; i++) {
int str1_ch = (int)str1.charAt(i);
int str2_ch = (int)str2.charAt(i);
if (str1_ch != str2_ch) {
return str1_ch - str2_ch;
}
}
if (l1 != l2) {
return l1 - l2;
} else {
return 0;
}
}
}
| true |
ffcc4d33777e905de942f444c1776722dcfbbcbe | Java | liweizhihd/dailyPractice | /z-before/src/main/java/test/java8/stream/Test002.java | UTF-8 | 632 | 2.921875 | 3 | [] | no_license | package test.java8.stream;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
/**
* @auther: liweizhi
* Date: 2019/3/27 17:07
* Description:
*/
public class Test002 {
@Test
public void mapTest(){
Map<Integer, String> map = new HashMap<>();
for (int i = 0; i < 10; i++) {
map.putIfAbsent(i, "val" + i);
}
map.computeIfPresent(3, (num, val) -> val + num);
System.out.println(map.get(3));
map.computeIfAbsent(3, num -> "bam");
System.out.println(map.get(3));
System.out.println(map.getOrDefault("a", "axiba"));
}
}
| true |
85677be310a677dd9d044f29d6e631fb5cf7c98c | Java | Chuyinzki/leet-code | /src/CountingBits.java | UTF-8 | 640 | 3.625 | 4 | [] | no_license | import java.util.ArrayList;
import java.util.List;
public class CountingBits {
public static void main(String[] args) {
//2 -> [0,1,1]
countBits(2);
}
public static int[] countBits(int num) {
List<Integer> retList = new ArrayList<>();
for (int i = 0; i <= num; i++) {
retList.add(countBitsHelper(i));
}
return retList.stream().mapToInt(Integer::intValue).toArray();
}
public static int countBitsHelper(int num) {
int count = 0;
while (num > 0) {
count += num & 1;
num >>= 1;
}
return count;
}
}
| true |
c992f5ffe3c2b0ba00c1469b07fb5d62c804fbbc | Java | Bhargav505/SeleniumDemo | /Selenium Demo/src/classDemo/SeleniumTestng.java | UTF-8 | 639 | 2.09375 | 2 | [] | no_license | package classDemo;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;
public class SeleniumTestng {
public static WebDriver driver;
@Test
public void display() {
System.out.println("In Test method");
driver.findElement(By.linkText("Gmail")).click();
}
@BeforeMethod
public void Launch() {
driver=new ChromeDriver();
driver.get("https://google.com");
}
@AfterMethod
public void closeApp() {
driver.close();
}
}
| true |
12aa41f10ca46c4a7ac8a83be4d54d47634c6e18 | Java | dilipkrish/swagger-springmvc | /springfox-swagger1/src/main/java/springfox/documentation/swagger1/mappers/Mappers.java | UTF-8 | 2,497 | 1.953125 | 2 | [
"Apache-2.0"
] | permissive | /*
*
* Copyright 2015-2019 the original author or authors.
*
* 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 springfox.documentation.swagger1.mappers;
import org.springframework.web.util.UriComponents;
import springfox.documentation.swagger1.dto.ApiListing;
import javax.servlet.http.HttpServletRequest;
import java.util.AbstractMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import static java.util.stream.Collectors.*;
import static org.springframework.util.StringUtils.*;
import static springfox.documentation.swagger.common.HostNameProvider.*;
public class Mappers {
private Mappers() {
throw new UnsupportedOperationException();
}
public static Function<Map.Entry<String, List<springfox.documentation.service.ApiListing>>, Map.Entry<String,
List<ApiListing>>>
toApiListingDto(
final HttpServletRequest servletRequest,
final String host,
final ServiceModelToSwaggerMapper mapper) {
return entry -> {
List<ApiListing> newApiListings = entry.getValue().stream().map(value -> {
ApiListing apiListing = mapper.toSwaggerApiListing(value);
UriComponents uriComponents = componentsFrom(servletRequest, apiListing.getBasePath());
apiListing.setBasePath(adjustedBasePath(uriComponents, host, apiListing.getBasePath()));
return apiListing;
}).collect(toList());
return new AbstractMap.SimpleEntry<>(entry.getKey(), newApiListings);
};
}
private static String adjustedBasePath(
UriComponents uriComponents,
String hostNameOverride,
String basePath) {
if (!isEmpty(hostNameOverride)) {
int port = uriComponents.getPort();
if (port > -1) {
return String.format("%s://%s:%d%s", uriComponents.getScheme(), hostNameOverride, port, basePath);
}
return String.format("%s://%s%s", uriComponents.getScheme(), hostNameOverride, basePath);
}
return basePath;
}
}
| true |
5d2e35a969439ad55a9be7f698db2bcbe78725c9 | Java | thoaitran2000dt/TestSubjectApp | /app/src/main/java/android/uit/testsubjectsapp/question/SearchQuestionFragment.java | UTF-8 | 4,965 | 2.15625 | 2 | [] | no_license | package android.uit.testsubjectsapp.question;
import android.database.Cursor;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.uit.testsubjectsapp.MainActivity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.uit.testsubjectsapp.R;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.PopupMenu;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class SearchQuestionFragment extends Fragment {
ListView lvQuestion;
QuestionController questionController;
QuestionAdapter adapter;
EditText edtSearch;
ImageButton imgSubject;
String subject ="";
public SearchQuestionFragment() {
// Required empty public constructor
}
public void begin() {
lvQuestion = (ListView) getActivity().findViewById(R.id.lvQuestion);
edtSearch = (EditText) getActivity().findViewById(R.id.edtSearch);
imgSubject = (ImageButton) getActivity().findViewById(R.id.imgSubject);
questionController = new QuestionController(getActivity());
listCursor(questionController.getSearchQuestion(subject, edtSearch.getText().toString()));
}
public void listCursor(Cursor cursor) {
adapter = new QuestionAdapter(getActivity(), cursor, true);
lvQuestion.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
((MainActivity) getActivity()).getSupportActionBar().setTitle("Danh sách câu hỏi");
return inflater.inflate(R.layout.fragment_search_question, container, false);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
begin();
edtSearch.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
listCursor(questionController.getSearchQuestion(subject, edtSearch.getText().toString()));
}
@Override
public void afterTextChanged(Editable editable) {
}
});
imgSubject.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showMenu(v);
}
});
}
public void showMenu (View v){
PopupMenu popupMenu = new PopupMenu(getActivity(), v);
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.quesAll:
subject="";
listCursor(questionController.getSearchQuestionBySubject(subject));
break;
case R.id.qGDCD:
subject="GDCD";
listCursor(questionController.getSearchQuestionBySubject(subject));
break;
case R.id.qTH:
subject="TH";
listCursor(questionController.getSearchQuestionBySubject(subject));
break;
case R.id.qLS:
subject="LS";
listCursor(questionController.getSearchQuestionBySubject(subject));
break;
}
return false;
}
});
popupMenu.inflate(R.menu.menu_question);
setForceShowIcon(popupMenu);
popupMenu.show();
}
public static void setForceShowIcon(PopupMenu popupMenu) {
try {
Field[] fields = popupMenu.getClass().getDeclaredFields();
for (Field field : fields) {
if ("mPopup".equals(field.getName())) {
field.setAccessible(true);
Object menuPopupHelper = field.get(popupMenu);
Class<?> classPopupHelper = Class.forName(menuPopupHelper
.getClass().getName());
Method setForceIcons = classPopupHelper.getMethod(
"setForceShowIcon", boolean.class);
setForceIcons.invoke(menuPopupHelper, true);
break;
}
}
} catch (Throwable e) {
e.printStackTrace();
}
}
} | true |
f0dd95acd7548843560380d9e45d55e9b531a2e0 | Java | linux86/AndoirdSecurity | /apps_final/mobi.dream.neko/apk/mobi/monaca/framework/plugin/MonacaPlugin.java | UTF-8 | 919 | 1.546875 | 2 | [] | no_license | package mobi.monaca.framework.plugin;
import mobi.monaca.utils.MonacaDevice;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaInterface;
import org.apache.cordova.api.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MonacaPlugin
extends CordovaPlugin
{
public boolean execute(String paramString, JSONArray paramJSONArray, CallbackContext paramCallbackContext)
throws JSONException
{
if (paramString.equals("getRuntimeConfiguration"))
{
paramString = new JSONObject();
paramString.put("deviceId", MonacaDevice.getDeviceId(cordova.getActivity()));
paramCallbackContext.success(paramString);
return true;
}
return false;
}
}
/* Location:
* Qualified Name: mobi.monaca.framework.plugin.MonacaPlugin
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | true |
a770e14b70c08ed5fe8295138acb32ab4b8bfcbf | Java | zaid5548/HB-Code | /Practice_All_Types/src/Practice/MaximumSumPathInTwoArray.java | UTF-8 | 879 | 3.546875 | 4 | [] | no_license | package Practice;
import java.util.Scanner;
public class MaximumSumPathInTwoArray {
public static void main(String[] args) {
Scanner d=new Scanner(System.in);
int n=d.nextInt();
int m=d.nextInt();
int[] arr1=new int[n];
int[] arr2=new int[m];
for(int i=0;i<arr1.length;i++)
{
arr1[i]=d.nextInt();
}
for(int i=0;i<arr2.length;i++)
{
arr2[i]=d.nextInt();
}
Maximumpath(arr1,arr2);
}
public static void Maximumpath(int[] one,int[] two)
{
int s1=0,s2=0;
int i=0,j=0;
int rs=0;
while(i<one.length && j<two.length)
{
if(one[i]<two[j])
{
s1+=one[i];
i++;
}
else if(one[i]>two[j])
{
s2+=two[j];
j++;
}
else
{
rs+=Math.max(s1, s2)+one[i];
s1=0;
s2=0;
i++;
j++;
}
}
while(i<one.length)
{
rs+=one[i];
i++;
}
while(j<two.length)
{
rs+=two[j];
j++;
}
System.out.println(rs+" ");
}
} | true |
0a65ae6125e7e63db4ab13fcf93bea5c943c47ba | Java | Shifat63/PetClinic | /src/test/java/PetClinic/Controllers/PetControllerTest.java | UTF-8 | 12,521 | 2.1875 | 2 | [] | no_license | package PetClinic.Controllers;
import PetClinic.Converters.StringToOwner;
import PetClinic.Converters.StringToPetType;
import PetClinic.Model.Owner;
import PetClinic.Model.Pet;
import PetClinic.Model.PetType;
import PetClinic.Service.OwnerService;
import PetClinic.Service.PetService;
import PetClinic.Service.PetTypeService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.format.support.DefaultFormattingConversionService;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.HashSet;
import java.util.Set;
import static org.hamcrest.Matchers.hasSize;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@ExtendWith(MockitoExtension.class)
class PetControllerTest {
@Mock
PetService petService;
@Mock
OwnerService ownerService;
@Mock
PetTypeService petTypeService;
StringToOwner stringToOwner = new StringToOwner();
StringToPetType stringToPetType = new StringToPetType();
Long petId = 1L;
Long ownerId = 1L;
Long petTypeId = 1L;
Pet pet = new Pet();
Owner owner = new Owner();
PetType petType = new PetType();
Set<Pet> pets = new HashSet<>();
Set<Owner> owners = new HashSet<>();
Set<PetType> petTypes = new HashSet<>();
MockMvc mockMvc;
@InjectMocks
PetController petController;
@BeforeEach
void setUp() {
pet.setId(petId);
pets.add(pet);
owner.setId(ownerId);
owners.add(owner);
petType.setId(petTypeId);
petTypes.add(petType);
DefaultFormattingConversionService formattingConversionService = new DefaultFormattingConversionService();
formattingConversionService.addConverter(stringToOwner);
formattingConversionService.addConverter(stringToPetType);
mockMvc = MockMvcBuilders.standaloneSetup(petController).setConversionService(formattingConversionService).build();
}
@Test
void index() throws Exception {
when(petService.findAll()).thenReturn(pets);
mockMvc.perform(get("/pets"))
.andExpect(status().isOk())
.andExpect(model().attribute("pets", hasSize(1)))
.andExpect(view().name("pets/index"));
mockMvc.perform(get("/pets/"))
.andExpect(status().isOk())
.andExpect(model().attribute("pets", hasSize(1)))
.andExpect(view().name("pets/index"));
mockMvc.perform(get("/pets/index"))
.andExpect(status().isOk())
.andExpect(model().attribute("pets", hasSize(1)))
.andExpect(view().name("pets/index"));
verify(petService, times(3)).findAll();
}
@Test
void viewPetDetails() throws Exception {
when(petService.findById(any())).thenReturn(pet);
mockMvc.perform(get("/pets/viewPetDetails/1"))
.andExpect(status().isOk())
.andExpect(model().attributeExists("pet"))
.andExpect(view().name("pets/viewPetDetails"));
verify(petService, times(1)).findById(any());
}
@Test
void registerPetGet() throws Exception {
when(ownerService.findAll()).thenReturn(owners);
when(petTypeService.findAll()).thenReturn(petTypes);
mockMvc.perform(get("/pets/registerPet"))
.andExpect(status().isOk())
.andExpect(model().attributeExists("pet"))
.andExpect(model().attribute("owners", hasSize(1)))
.andExpect(model().attribute("petTypes", hasSize(1)))
.andExpect(view().name("pets/registerPet"));
verify(ownerService, times(1)).findAll();
verify(petTypeService, times(1)).findAll();
}
@Test
void registerPetPost() throws Exception {
when(petService.save(any())).thenReturn(pet);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
mockMvc.perform(post("/pets/registerPet")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("id", "")
.param("name", "mock name")
.param("birthDate", formatter.format(LocalDate.now()))
.param("petType", petTypeId.toString())
.param("owner", ownerId.toString())
)
.andExpect(status().is3xxRedirection())
.andExpect(view().name("redirect:/pets/viewPetDetails/" + petId));
verify(petService, times(1)).save(any());
}
@Test
void registerPetPostOwnerValidationFail() throws Exception {
when(ownerService.findAll()).thenReturn(owners);
when(petTypeService.findAll()).thenReturn(petTypes);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
mockMvc.perform(post("/pets/registerPet")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("id", "")
.param("name", "mock name")
.param("birthDate", formatter.format(LocalDate.now()))
.param("petType", petTypeId.toString())
.param("owner", "") //There must be no pet without owner. So validation failed
)
.andExpect(status().isOk())
.andExpect(view().name("pets/registerPet"))
.andExpect(model().attributeExists("pet"))
.andExpect(model().attribute("owners", hasSize(1)))
.andExpect(model().attribute("petTypes", hasSize(1)));
verify(petService, times(0)).save(any());
verify(ownerService, times(1)).findAll();
verify(petTypeService, times(1)).findAll();
}
@Test
void registerPetPostPetTypeValidationFail() throws Exception {
when(ownerService.findAll()).thenReturn(owners);
when(petTypeService.findAll()).thenReturn(petTypes);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
mockMvc.perform(post("/pets/registerPet")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("id", "")
.param("name", "mock name")
.param("birthDate", formatter.format(LocalDate.now()))
.param("petType", "") //Every pet must have a pet type. So validation failed
.param("owner", ownerId.toString())
)
.andExpect(status().isOk())
.andExpect(view().name("pets/registerPet"))
.andExpect(model().attributeExists("pet"))
.andExpect(model().attribute("owners", hasSize(1)))
.andExpect(model().attribute("petTypes", hasSize(1)));
verify(petService, times(0)).save(any());
verify(ownerService, times(1)).findAll();
verify(petTypeService, times(1)).findAll();
}
@Test
void registerPetPostBirthDateValidationFail() throws Exception {
when(ownerService.findAll()).thenReturn(owners);
when(petTypeService.findAll()).thenReturn(petTypes);
DateTimeFormatter correctFormat = DateTimeFormatter.ofPattern("dd-MM-yyyy");
DateTimeFormatter wrongFormat = DateTimeFormatter.ofPattern("dd/MM/yyyy");
mockMvc.perform(post("/pets/registerPet")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("id", "")
.param("name", "mock name")
//birthDate must be present date or any past date. So validation failed
.param("birthDate", correctFormat.format(LocalDate.now().plus(1, ChronoUnit.DAYS)))
.param("petType",petTypeId.toString())
.param("owner", ownerId.toString())
)
.andExpect(status().isOk())
.andExpect(view().name("pets/registerPet"))
.andExpect(model().attributeExists("pet"))
.andExpect(model().attribute("owners", hasSize(1)))
.andExpect(model().attribute("petTypes", hasSize(1)));
mockMvc.perform(post("/pets/registerPet")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("id", "")
.param("name", "mock name")
//birthDate format mismatch. So validation failed
.param("birthDate", wrongFormat.format(LocalDate.now()))
.param("petType",petTypeId.toString())
.param("owner", ownerId.toString())
)
.andExpect(status().isOk())
.andExpect(view().name("pets/registerPet"))
.andExpect(model().attributeExists("pet"))
.andExpect(model().attribute("owners", hasSize(1)))
.andExpect(model().attribute("petTypes", hasSize(1)));
verify(petService, times(0)).save(any());
verify(ownerService, times(2)).findAll();
verify(petTypeService, times(2)).findAll();
}
@Test
void registerPetPostNameValidationFail() throws Exception {
when(ownerService.findAll()).thenReturn(owners);
when(petTypeService.findAll()).thenReturn(petTypes);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
String overSizedName = "abcdefghijklmnopqrstuvwxyz";
mockMvc.perform(post("/pets/registerPet")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("id", "")
.param("name", "")//Name must not be empty. So validation failed
.param("birthDate", formatter.format(LocalDate.now()))
.param("petType", petTypeId.toString())
.param("owner", ownerId.toString())
)
.andExpect(status().isOk())
.andExpect(view().name("pets/registerPet"))
.andExpect(model().attributeExists("pet"))
.andExpect(model().attribute("owners", hasSize(1)))
.andExpect(model().attribute("petTypes", hasSize(1)));
mockMvc.perform(post("/pets/registerPet")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("id", "")
.param("name", overSizedName)//Name must be between 1 to 20 characters. So validation failed
.param("birthDate", formatter.format(LocalDate.now()))
.param("petType", petTypeId.toString())
.param("owner", ownerId.toString())
)
.andExpect(status().isOk())
.andExpect(view().name("pets/registerPet"))
.andExpect(model().attributeExists("pet"))
.andExpect(model().attribute("owners", hasSize(1)))
.andExpect(model().attribute("petTypes", hasSize(1)));
verify(petService, times(0)).save(any());
verify(ownerService, times(2)).findAll();
verify(petTypeService, times(2)).findAll();
}
@Test
void editPet() throws Exception {
when(ownerService.findAll()).thenReturn(owners);
when(petService.findById(any())).thenReturn(pet);
when(petTypeService.findAll()).thenReturn(petTypes);
mockMvc.perform(get("/pets/editPet/1"))
.andExpect(status().isOk())
.andExpect(model().attributeExists("pet"))
.andExpect(model().attribute("owners", hasSize(1)))
.andExpect(model().attribute("petTypes", hasSize(1)))
.andExpect(view().name("pets/registerPet"));
verify(ownerService, times(1)).findAll();
verify(petService, times(1)).findById(any());
verify(petTypeService, times(1)).findAll();
}
@Test
void deletePet() throws Exception {
mockMvc.perform(get("/pets/deletePet/1"))
.andExpect(status().is3xxRedirection())
.andExpect(view().name("redirect:/pets/index"));
verify(petService, times(1)).deleteById(any());
}
} | true |
b50d9d9f1e1b85a0510b692927422c4bbbc3ba7a | Java | duozi123/leetcode | /zxwork/oj/src/zx/Maximum_Product_Subarray.java | UTF-8 | 1,257 | 3.546875 | 4 | [] | no_license | package zx;
import java.util.ArrayList;
public class Maximum_Product_Subarray {
/**
* @param args
*/
public static void main(String[] args) {
int[] a = { -1, 0, -4,3 };
System.out.println(maxProduct(a));
}
public static int maxProduct(int[] A) {
if (A == null || A.length == 0)
return 0;
if (A.length == 1)
return A[0];
return product(A, 0, A.length - 1);
}
public static int product(int[] A, int low, int high) {
if (low > high)
return -65536;
if (low == high)
return A[low];
int flag = 0;
for (int i = low; i <= high; i++) {
if (A[i] == 0) {
flag = 1;
return Math.max(0, Math.max(product(A, low, i - 1),
product(A, i + 1, high)));
}
}
ArrayList<Integer> index = new ArrayList<Integer>();
for (int i = low; i <= high; i++) {
if (A[i] < 0 && flag == 0) {
index.add(i);
}
}
if (index.size() % 2 == 0) {
int product = 1;
for (int i = low; i <= high; i++) {
product = product * A[i];
}
return product;
} else {
return Math.max(Math.max(product(A, low, index.get(0) - 1),
product(A, index.get(0) + 1, high)), Math.max(
product(A, low, index.get(index.size() - 1) - 1),
product(A, index.get(index.size() - 1) + 1, high)));
}
}
}
| true |
9eee956403d572470df52b55bda4eac6dcb3d20a | Java | sazro19/PBZ_LAB_2 | /PBZ_2/src/sample/controller/AgentListController.java | UTF-8 | 3,992 | 2.578125 | 3 | [] | no_license | package sample.controller;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import sample.Main;
import sample.database.Agent;
import java.io.IOException;
import java.sql.SQLException;
public class AgentListController {
@FXML
private TableView<Agent> agentTableView;
@FXML
private TableColumn<Agent, String> fullnameColumn;
@FXML
private TableColumn<Agent, String> passportDataColumn;
@FXML
private Button addButton;
@FXML
private Button deleteButton;
@FXML
private Button editButton;
@FXML
private Button cancelButton;
private static Agent selectedAgent;
private static ObservableList<Agent> agents;
private void createAgentTable() {
agents = FXCollections.observableArrayList(Controller.getDatabase().getAgentList());
agentTableView.setItems(agents);
fullnameColumn.setCellValueFactory(new PropertyValueFactory<Agent, String>("fullName"));
passportDataColumn.setCellValueFactory(new PropertyValueFactory<Agent, String>("passportData"));
}
@FXML
void initialize() throws SQLException, ClassNotFoundException {
createAgentTable();
addButton.setOnAction(event -> {
try {
Parent root = FXMLLoader.load(Main.class.getResource("view/addAgent.fxml"));
Stage stage = (Stage) addButton.getScene().getWindow();
stage.setTitle("Adding");
stage.setScene(new Scene(root, 650, 350));
} catch (IOException e) {
e.printStackTrace();
}
});
editButton.setOnAction(event -> {
try {
selectedAgent = agentTableView.getSelectionModel().getSelectedItem();
if (selectedAgent != null) {
Parent root = FXMLLoader.load(Main.class.getResource("view/editAgent.fxml"));
Stage stage = (Stage) editButton.getScene().getWindow();
stage.setTitle("Edit");
stage.setScene(new Scene(root, 650, 350));
} else {
showError();
}
} catch (IOException e) {
e.printStackTrace();
}
});
deleteButton.setOnAction(event -> {
try {
selectedAgent = agentTableView.getSelectionModel().getSelectedItem();
if (selectedAgent != null){
Controller.getDatabase().deleteAgent(getSelectedAgent());
agents = FXCollections.observableArrayList(Controller.getDatabase().getAgentList());
agentTableView.setItems(agents);
} else {
showError();
}
} catch (SQLException e) {
e.printStackTrace();
}
});
cancelButton.setOnAction(event -> {
try {
Parent root = FXMLLoader.load(Main.class.getResource("view/sample.fxml"));
Stage stage1 = (Stage) cancelButton.getScene().getWindow();
stage1.setTitle("Учет договоров страхования");
stage1.setScene(new Scene(root, 650, 350));
} catch (IOException e) {
e.printStackTrace();
}
});
}
public static Agent getSelectedAgent(){
return selectedAgent;
}
private void showError(){
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Error");
alert.setContentText("Select your agent");
alert.showAndWait();
}
} | true |
0b9766cfb06ab52444b887c51f55be859d2b992f | Java | pboechat/xithcluster | /xithcluster/src/br/edu/univercidade/cc/xithcluster/nodes/primitives/Torus.java | UTF-8 | 2,249 | 2.3125 | 2 | [
"BSD-2-Clause"
] | permissive | package br.edu.univercidade.cc.xithcluster.nodes.primitives;
import org.xith3d.scenegraph.Appearance;
import org.xith3d.scenegraph.Node;
import org.xith3d.scenegraph.Shape3D;
public class Torus extends org.xith3d.scenegraph.primitives.Torus {
private float radius;
private float alpha;
private Object radSlices;
private int conSlices;
private int features;
private boolean colorAlpha;
private int texCoordsSize;
public Torus(String name, float radius, float alpha, int radSlices, int conSlices, int features, boolean colorAlpha, int texCoordsSize, Appearance appearance) {
super(radius, alpha, radSlices, conSlices, features, colorAlpha, texCoordsSize);
this.setName(name);
this.radius = radius;
this.alpha = alpha;
this.radSlices = radSlices;
this.conSlices = conSlices;
this.features = features;
this.colorAlpha = colorAlpha;
this.texCoordsSize = texCoordsSize;
this.setAppearance(appearance);
}
public float getRadius() {
return radius;
}
public float getAlpha() {
return alpha;
}
public Object getRadSlices() {
return radSlices;
}
public int getConSlices() {
return conSlices;
}
public int getFeatures() {
return features;
}
public boolean isColorAlpha() {
return colorAlpha;
}
public int getTexCoordsSize() {
return texCoordsSize;
}
@Override
protected void copy(Shape3D arg0) {
Torus torus;
torus = (Torus) arg0;
torus.setName(getName());
torus.radius = radius;
torus.alpha = alpha;
torus.radSlices = radSlices;
torus.conSlices = conSlices;
torus.features = features;
torus.colorAlpha = colorAlpha;
torus.texCoordsSize = texCoordsSize;
torus.setAppearance(getAppearance());
torus.setBoundsAutoCompute(false);
torus.setBounds(getBounds());
torus.boundsDirty = true;
torus.updateBounds(false);
torus.setPickable(isPickable());
torus.setRenderable(isRenderable());
}
@Override
protected Shape3D newInstance() {
Torus newTorus;
boolean globalIgnoreBounds;
globalIgnoreBounds = Node.globalIgnoreBounds;
Node.globalIgnoreBounds = isIgnoreBounds();
newTorus = new Torus(null, 1.0f, 1.0f, 5, 5, 11, false, 2, null);
Node.globalIgnoreBounds = globalIgnoreBounds;
return newTorus;
}
}
| true |