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
10b713d222f012783878fca67f2f614239c1532e
Java
yuexiaoguang/spring4
/spring-context/src/main/java/org/springframework/format/datetime/standard/Jsr310DateTimeFormatAnnotationFormatterFactory.java
UTF-8
3,281
2.515625
3
[]
no_license
package org.springframework.format.datetime.standard; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.OffsetDateTime; import java.time.OffsetTime; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.TemporalAccessor; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.springframework.context.support.EmbeddedValueResolutionSupport; import org.springframework.format.AnnotationFormatterFactory; import org.springframework.format.Parser; import org.springframework.format.Printer; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.lang.UsesJava8; /** * 使用JDK 8中的JSR-310 <code>java.time</code>包格式化带{@link DateTimeFormat}注解的字段. */ @UsesJava8 public class Jsr310DateTimeFormatAnnotationFormatterFactory extends EmbeddedValueResolutionSupport implements AnnotationFormatterFactory<DateTimeFormat> { private static final Set<Class<?>> FIELD_TYPES; static { // 创建可以使用@DateTimeFormat注解的字段类型集合. Set<Class<?>> fieldTypes = new HashSet<Class<?>>(8); fieldTypes.add(LocalDate.class); fieldTypes.add(LocalTime.class); fieldTypes.add(LocalDateTime.class); fieldTypes.add(ZonedDateTime.class); fieldTypes.add(OffsetDateTime.class); fieldTypes.add(OffsetTime.class); FIELD_TYPES = Collections.unmodifiableSet(fieldTypes); } @Override public final Set<Class<?>> getFieldTypes() { return FIELD_TYPES; } @Override public Printer<?> getPrinter(DateTimeFormat annotation, Class<?> fieldType) { DateTimeFormatter formatter = getFormatter(annotation, fieldType); // 用于打印的高效ISO_LOCAL_* 变体, 因为它们的速度是原来的两倍... if (formatter == DateTimeFormatter.ISO_DATE) { if (isLocal(fieldType)) { formatter = DateTimeFormatter.ISO_LOCAL_DATE; } } else if (formatter == DateTimeFormatter.ISO_TIME) { if (isLocal(fieldType)) { formatter = DateTimeFormatter.ISO_LOCAL_TIME; } } else if (formatter == DateTimeFormatter.ISO_DATE_TIME) { if (isLocal(fieldType)) { formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME; } } return new TemporalAccessorPrinter(formatter); } @Override @SuppressWarnings("unchecked") public Parser<?> getParser(DateTimeFormat annotation, Class<?> fieldType) { DateTimeFormatter formatter = getFormatter(annotation, fieldType); return new TemporalAccessorParser((Class<? extends TemporalAccessor>) fieldType, formatter); } /** * 用于创建{@link DateTimeFormatter}的工厂方法. * * @param annotation 字段的格式注解 * @param fieldType 声明的字段类型 * * @return {@link DateTimeFormatter}实例 */ protected DateTimeFormatter getFormatter(DateTimeFormat annotation, Class<?> fieldType) { DateTimeFormatterFactory factory = new DateTimeFormatterFactory(); factory.setStylePattern(resolveEmbeddedValue(annotation.style())); factory.setIso(annotation.iso()); factory.setPattern(resolveEmbeddedValue(annotation.pattern())); return factory.createDateTimeFormatter(); } private boolean isLocal(Class<?> fieldType) { return fieldType.getSimpleName().startsWith("Local"); } }
true
f1d2a9f0349977d375166f4676ce4ed3a73a33cf
Java
weiju-xi/RT-JAR-CODE
/sun/java2d/cmm/PCMM.java
UTF-8
948
1.828125
2
[]
no_license
package sun.java2d.cmm; import java.awt.color.ICC_Profile; public abstract interface PCMM { public abstract long loadProfile(byte[] paramArrayOfByte); public abstract void freeProfile(long paramLong); public abstract int getProfileSize(long paramLong); public abstract void getProfileData(long paramLong, byte[] paramArrayOfByte); public abstract void getTagData(long paramLong, int paramInt, byte[] paramArrayOfByte); public abstract int getTagSize(long paramLong, int paramInt); public abstract void setTagData(long paramLong, int paramInt, byte[] paramArrayOfByte); public abstract ColorTransform createTransform(ICC_Profile paramICC_Profile, int paramInt1, int paramInt2); public abstract ColorTransform createTransform(ColorTransform[] paramArrayOfColorTransform); } /* Location: C:\Program Files\Java\jdk1.7.0_79\jre\lib\rt.jar * Qualified Name: sun.java2d.cmm.PCMM * JD-Core Version: 0.6.2 */
true
a4098d034eaf68d294fad37ed77cd06b97cb6aa1
Java
Nerses83/restourant-sfl
/src/main/java/com/interview/test/sfl/restourant/service/impl/RestourantServiceImpl.java
UTF-8
1,112
2.109375
2
[]
no_license
package com.interview.test.sfl.restourant.service.impl; import com.interview.test.sfl.restourant.model.RestourantTable; import com.interview.test.sfl.restourant.model.User; import com.interview.test.sfl.restourant.repository.RestourantDao; import com.interview.test.sfl.restourant.service.RestourantService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class RestourantServiceImpl implements RestourantService { @Autowired RestourantDao restourantDao; @Override public List<RestourantTable> findRestourantTablesByUser(User user) { return restourantDao.findRestourantTablesByUser(user); } @Override public RestourantTable getRestourantTable(Long id) { return restourantDao.getOne(id); } @Override public List<RestourantTable> getRestourantTables() { return restourantDao.findAll(); } @Override public RestourantTable save(RestourantTable restourantTable) { return restourantDao.saveAndFlush(restourantTable); } }
true
f29bb1e2eb6ae30990b3ec2855be8df0b3662a5d
Java
AlisonRodriguesGit/SpringBootFinanceiro
/src/main/java/br/com/devspring/util/LocalDateTimeUtils.java
UTF-8
2,591
3.03125
3
[]
no_license
package br.com.devspring.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; public class LocalDateTimeUtils { private static String TIMEZONE = "America/Sao_Paulo"; private static String FORMATODATA = "yyyy-MM-dd'T'HH:mm:ss"; private LocalDateTimeUtils() { } public static Date converterStringParaDate(String data){ SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm"); try { return sdf.parse(data); } catch (ParseException e) { Calendar c = Calendar.getInstance(); Date dataAtual = c.getTime(); return dataAtual; } } public static LocalDateTime converterStringParaLocalDateTime(String data) { try { DateTimeFormatter formatter = DateTimeFormatter.ofPattern(FORMATODATA); return LocalDateTime.parse(data, formatter.withZone(getZoneId())); } catch (Exception e) { try { return LocalDateTime.parse(data, DateTimeFormatter.ISO_DATE_TIME); } catch (Exception e1) { // Não implementado para retornar data atual } return dataAtual(); } } public static String converterLocalDateTimeParaString(LocalDateTime localDateTime) { String formattedDateTime = ""; DateTimeFormatter formatter = DateTimeFormatter.ofPattern(FORMATODATA); try { formattedDateTime = localDateTime.format(formatter); } catch (Exception e) { formattedDateTime = LocalDateTime.now().format(formatter); } return formattedDateTime; } public static LocalDateTime dataAtual() { return LocalDateTime.ofInstant(Instant.now(), getZoneId()); } private static ZoneId getZoneId() { return TimeZone.getTimeZone(TIMEZONE).toZoneId(); } public static String converterLongParaString(Long currentTimeMillis) { String formattedDateTime = ""; SimpleDateFormat formatter = new SimpleDateFormat(FORMATODATA); DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern(FORMATODATA); try { formattedDateTime = formatter.format(currentTimeMillis); } catch (Exception e) { formattedDateTime = LocalDateTime.now().format(formatter1); } return formattedDateTime; } }
true
9e62b90a02d384bad7cb1c45e01bb0b8cd46e49e
Java
samramez/FlightInfoApp
/app/src/main/java/com/yiptv/sam/flightinfoapp/AirlinesFragment.java
UTF-8
3,966
2.265625
2
[]
no_license
package com.yiptv.sam.flightinfoapp; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.yiptv.sam.flightinfoapp.Model.AirlineInfo; import com.yiptv.sam.flightinfoapp.Service.AirlineInfoService; import com.yiptv.sam.flightinfoapp.Utils.AirlineRecyclerAdapter; import com.yiptv.sam.flightinfoapp.Utils.RecyclerItemClickListener; import java.util.List; import retrofit.Callback; import retrofit.Response; /** * Created by Sam on 5/1/16. */ public class AirlinesFragment extends Fragment { private RecyclerView mRecyclerView; private AirlineRecyclerAdapter mAdapter; private AirlineInfoService mAirlineInfoService; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_airlines, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mRecyclerView = (RecyclerView) view.findViewById(R.id.airlineRecyclerView); mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext())); mRecyclerView.setHasFixedSize(true); mAirlineInfoService = new AirlineInfoService(); // mRecyclerView.setAdapter(new AirlineRecyclerAdapter(view.getContext(),null)); getAirlineInfo(); } private void getAirlineInfo(){ try { mAirlineInfoService.getFlightInfo(new Callback<List<AirlineInfo>>() { @Override public void onResponse(Response<List<AirlineInfo>> response) { //Log.e("###########",response.errorBody().toString()); final List<AirlineInfo> airlineInfo = response.body(); mAdapter = new AirlineRecyclerAdapter(getActivity(),airlineInfo); mRecyclerView.setAdapter(mAdapter); //Toast.makeText(getActivity(),"Success" , Toast.LENGTH_LONG).show(); mRecyclerView.addOnItemTouchListener( new RecyclerItemClickListener(getActivity(), mRecyclerView, new RecyclerItemClickListener.OnItemClickListener() { @Override public void onItemClick(View view, int position) { airlineInfo.get(position).getLogoURL(); Intent myIntent = new Intent(getActivity(), DetailActivity.class); myIntent.putExtra("image", airlineInfo.get(position).getLogoURL() ); myIntent.putExtra("name", airlineInfo.get(position).getName() ); myIntent.putExtra("website", airlineInfo.get(position).getSite() ); myIntent.putExtra("phone", airlineInfo.get(position).getPhone() ); getActivity().startActivity(myIntent); //Toast.makeText(getActivity(),"Success" , Toast.LENGTH_LONG).show(); } })); } @Override public void onFailure(Throwable t) { Toast.makeText(getActivity(),"Failure" , Toast.LENGTH_LONG).show(); } }); } catch (Exception e) { e.printStackTrace(); } } }
true
744ae6829ca973907b9bd06acf4a581042994dee
Java
sgabalda/jsfexample
/src/main/java/net/sergigabol/jsfexample/converters/DniConverter.java
UTF-8
2,010
2.71875
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 net.sergigabol.jsfexample.converters; import java.text.DecimalFormat; import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.ConverterException; import javax.faces.convert.FacesConverter; import net.sergigabol.jsfexample.model.Dni; /** * * @author gabalca */ //@FacesConverter("conversorDni") @FacesConverter(forClass = Dni.class) public class DniConverter implements Converter<Dni>{ @Override public Dni getAsObject(FacesContext fc, UIComponent uic, String string) { Dni dni = new Dni(); if(string==null || string.length()!=9){ //Error, el DNI no es podrà convertir FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error en la conversió del DNI al camp "+uic.getClientId(), "La llargada ha de ser 9 caràcters"); fc.addMessage(uic.getClientId(), message); throw new ConverterException(message); } try{ dni.setNumero(Integer.parseInt(string.substring(0, 8))); }catch(NumberFormatException ex){ FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error en la conversió del DNI al camp "+uic.getClientId(), "Els primers 8 caràcters han de ser un número"); fc.addMessage(uic.getClientId(), message); throw new ConverterException(message); } dni.setLletra(string.charAt(8)); return dni; } @Override public String getAsString(FacesContext fc, UIComponent uic, Dni t) { return new DecimalFormat("########").format(t.getNumero())+t.getLletra(); } }
true
21b4e2574b710b8dc5380cbecef9ff710fa722bc
Java
vampyremathematician/BPHXCLASSAID
/app/src/main/java/com/counterbalancegaming/bphxclassaid/Student.java
UTF-8
2,866
2.96875
3
[]
no_license
package com.counterbalancegaming.bphxclassaid; /** * Created by Nicholas on 3/13/2018. */ import java.util.HashMap; import java.util.Map; public class Student { private String firstName; private String lastName; private String studentID; private HashMap<Integer, Data> studentData = new HashMap<Integer, Data>(); public Student(String first, String last, String id) { setFirstName(first); setLastName(last); setID(id); } public void newDay(int day, int month, int year) { int dateKey = Integer.parseInt(""+ year + month + day); Data dateData = new Data(); studentData.put(dateKey, dateData); } public void absent(int year, int month, int day) { int dateKey = Integer.parseInt(""+ year + month + day); if(studentData.containsKey(dateKey)) { Data editData = studentData.get(dateKey); editData.absentToTrue(); studentData.put(dateKey, editData); } } public void homework(int day, int month, int year) { int dateKey = Integer.parseInt(""+ year + month + day); if(studentData.containsKey(dateKey)) { Data editData = studentData.get(dateKey); editData.homeworkToTrue(); studentData.put(dateKey, editData); } } public void participation(int day, int month, int year) { int dateKey = Integer.parseInt(""+ year + month + day); if(studentData.containsKey(dateKey)) { Data editData = studentData.get(dateKey); editData.participationToTrue(); studentData.put(dateKey, editData); } } public void ticket(int day, int month, int year) { int dateKey = Integer.parseInt(""+ year + month + day); if(studentData.containsKey(dateKey)) { Data editData = studentData.get(dateKey); editData.ticketToTrue(); studentData.put(dateKey, editData); } } public String printData() { String s = ""; for(Map.Entry<Integer, Data> entry : studentData.entrySet()) { Integer key = entry.getKey(); Data value = entry.getValue(); s = s + ""+key+" "+ value.getAbsentAsString()+" "+value.getHomeworkAsString()+ " "+value.getParticipationAsString()+" "+value.getTicketAsString()+"\n"; } return s; } public String getFirstName() { return this.firstName; } public String getLastName() { return this.lastName; } private void setFirstName (String first) { this.firstName = first; } private void setLastName (String last) { this.lastName = last; } private void setID (String id) { this.studentID = id; } public int getDataSize() { return studentData.size(); } }
true
9f6b8a2501ec2d1de3ced8b910decd63630f2601
Java
spoto/ProgrammazioneJava
/compiti/2018-02-27/it/univr/esami/VerbalizzazioneGiàEffettuataException.java
UTF-8
262
2.625
3
[]
no_license
package it.univr.esami; public class VerbalizzazioneGiàEffettuataException extends Exception { public VerbalizzazioneGiàEffettuataException(Studente studente) { super("Lo studente " + studente.nome + " " + studente.cognome + " ha già verbalizzato"); } }
true
47a7fb8e85379b9c87219b45223ac2b4ecc8a31d
Java
Mauricioreyes2236/SDGORepo
/src/main/java/com/sdgor/model/Cliente.java
UTF-8
2,807
2.078125
2
[]
no_license
package com.sdgor.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Column; import javax.validation.constraints.Email; @Entity public class Cliente { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int Id; @Column private String Medio_p; @Column private String Metodo_p; @Column private String RFC; @Column private String Razon_s; @Column private String Nombre_c; @Column private String Apellido_p; @Column private String Apellido_m; @Column private String telefono_of; @Column private String telefono_ce; @Column private String Observaciones; @Column @Email private String Email; @Column private String Hora_1; @Column private String Hora_2; @Column private String Hora_3; @Column private String Hora_4; public int getId() { return Id; } public void setId(int id) { Id = id; } public String getMedio_p() { return Medio_p; } public void setMedio_p(String medio_p) { Medio_p = medio_p; } public String getMetodo_p() { return Metodo_p; } public void setMetodo_p(String metodo_p) { Metodo_p = metodo_p; } public String getRFC() { return RFC; } public void setRFC(String rFC) { RFC = rFC; } public String getRazon_s() { return Razon_s; } public void setRazon_s(String razon_s) { Razon_s = razon_s; } public String getNombre_c() { return Nombre_c; } public void setNombre_c(String nombre_c) { Nombre_c = nombre_c; } public String getApellido_p() { return Apellido_p; } public void setApellido_p(String apellido_p) { Apellido_p = apellido_p; } public String getApellido_m() { return Apellido_m; } public void setApellido_m(String apellido_m) { Apellido_m = apellido_m; } public String getTelefono_of() { return telefono_of; } public void setTelefono_of(String telefono_of) { this.telefono_of = telefono_of; } public String getTelefono_ce() { return telefono_ce; } public void setTelefono_ce(String telefono_ce) { this.telefono_ce = telefono_ce; } public String getObservaciones() { return Observaciones; } public void setObservaciones(String observaciones) { Observaciones = observaciones; } public String getEmail() { return Email; } public void setEmail(String email) { Email = email; } public String getHora_1() { return Hora_1; } public void setHora_1(String hora_1) { Hora_1 = hora_1; } public String getHora_2() { return Hora_2; } public void setHora_2(String hora_2) { Hora_2 = hora_2; } public String getHora_3() { return Hora_3; } public void setHora_3(String hora_3) { Hora_3 = hora_3; } public String getHora_4() { return Hora_4; } public void setHora_4(String hora_4) { Hora_4 = hora_4; } }
true
b529ac5fd3321d81841707fe528ba85636fb0792
Java
stonebox1122/hrm1
/src/test/java/com/stone/hrm/service/UserServiceTest.java
UTF-8
2,313
2.46875
2
[]
no_license
package com.stone.hrm.service; import com.stone.hrm.pojo.Role; import com.stone.hrm.pojo.User; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.annotation.Commit; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; import java.util.*; @SpringBootTest @RunWith(SpringRunner.class) public class UserServiceTest { @Autowired private UserService userService; @Autowired private RoleService roleService; /** * 添加新的用户,添加新的角色,并给新用户授予新角色 */ @Test @Transactional @Commit public void testAdd() { User user = new User(); user.setUsername("cq00004"); user.setStatus(1); user.setCreateTime(new Date()); Role role = new Role(); role.setName("guest"); role.setDescription("访客"); role.setStatus(1); role.setCreateTime(new Date()); user.getRoles().add(role); //userService.add(user); roleService.add(role); } /** * 添加新的用户,并给新用户授予角色 */ @Test @Transactional @Commit public void testAdd1() { User user = new User(); user.setUsername("cq00005"); user.setStatus(1); user.setCreateTime(new Date()); //user.getRoles().add(roleService.findByNameAndStatus("user", 1)); //userService.add(user); } /** * 现有用户授予新角色 */ @Test @Transactional @Commit public void testAdd2() { //User user = userService.findByUsernameAndStatus("cq00001", 1); List<Role> roles = new ArrayList<>(); //roles.add(roleService.findByNameAndStatus("admin", 1)); //roles.add(roleService.findByNameAndStatus("user", 1)); //user.setRoles(roles); //userService.update(user); } /** * 查询用户及其角色 */ @Test @Transactional @Commit public void testFind() { //User user = userService.findByUsernameAndStatus("cq00001", 1); //System.out.println(user); } }
true
5d44689a64de86d11c1454f9466f138b83aeccf2
Java
sniciq/myads
/src/com/ku6ads/struts/basic/cache/DictionaryFactory.java
UTF-8
5,475
2.359375
2
[]
no_license
/** * */ package com.ku6ads.struts.basic.cache; import java.util.Iterator; import java.util.Map; import java.util.TreeMap; import org.apache.struts2.ServletActionContext; import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import com.ku6ads.dao.entity.basic.BaseData; import com.ku6ads.exception.DictionaryAppendException; import com.ku6ads.exception.DictionaryNotFoundException; import com.ku6ads.services.iface.baisc.BaseDataService; /** * * HISTORY @ Copyright: Copyright (c) 2010 @ Company:KU6 * * @version:1.0 * @date 2010-11-22 * @author zhangyan * @description: */ public class DictionaryFactory { // 数据字典map private static Map dictoinaryInfo; // 字典工厂对象 private static DictionaryFactory instance; private static BaseDataService baseDataService; /** * 获得所有字典 * * @return */ public static Map getDictionary() { if (dictoinaryInfo == null) { dictoinaryInfo = loadAll(); } return dictoinaryInfo; } public static void flush() { dictoinaryInfo = loadAll(); } /** * 字典工厂单例方法 * * @return */ public static DictionaryFactory getInstance() { if (instance == null) { instance = new DictionaryFactory(); } return instance; } /** * 加载所有数据字典 * * @return */ private static Map loadAll() { return baseDataService.loadAllDictionary(); } /** * 添加一个数据字典 * * @param key * @param valueMap * @throws DictionaryAppendException */ public void append(String key, Map valueMap) throws DictionaryAppendException { if ((key == null) && key.equals("") || (valueMap == null && valueMap.equals(""))) { throw new DictionaryAppendException("数据字典参数不完整"); } dictoinaryInfo.put(key, valueMap); } /** * 根据英文标识获得某一个字典Map * * @param enName * @return * @throws DictionaryNotFoundException */ public Map getValus(String enName) throws DictionaryNotFoundException { Map value = (Map) dictoinaryInfo.get(enName); if (value == null && value.equals("")) { throw new DictionaryNotFoundException("没有找到英文标识为" + enName + "的数据字典"); } Map valueMap = new TreeMap(); Iterator values = value.values().iterator(); while (values.hasNext()) { BaseData dictionary = (BaseData) values.next(); valueMap.put(dictionary.getDataValue(), dictionary.getDataName()); } return valueMap; } /** * 通过英文标示和字典值获得数据字典对象 * * @param enName * @param dictionaryValue * @return * @throws DictionaryNotFoundException */ public BaseData getDictionaryByValue(String enName, String dictionaryValue) throws DictionaryNotFoundException { Map value = (Map) dictoinaryInfo.get(enName); if (value == null || value.equals("")) { throw new DictionaryNotFoundException("没有找到英文标识为" + enName + "的数据字典"); } Iterator values = value.values().iterator(); while (values.hasNext()) { BaseData dictionary = (BaseData) values.next(); if (dictionary.getDataValue().equals(dictionaryValue)) { return dictionary; } } return null; } /** * 通过英文标示和中文名称获得数据字典对象 * * @param enName * @param cnname * @return * @throws DictionaryNotFoundException */ public BaseData getDictionaryByCNNAME(String enName, String cnname) throws DictionaryNotFoundException { Map value = (Map) dictoinaryInfo.get(enName); if (value == null || value.equals("")) { throw new DictionaryNotFoundException("没有找到英文标识为" + enName + "的数据字典"); } Iterator values = value.values().iterator(); while (values.hasNext()) { BaseData dictionary = (BaseData) values.next(); if (dictionary.getDataName().equals(cnname)) { return dictionary; } } return null; } /** * 修改一个字典 * * @param key * @param valueMap * @throws DictionaryAppendException */ public void modify(String key, Map valueMap) throws DictionaryAppendException { if ((key == null && key.equals("")) || valueMap.equals(null)) { throw new DictionaryAppendException("修改数据字典时参数不完整"); } dictoinaryInfo.remove(key); dictoinaryInfo.put(key, valueMap); } /** * 修改一个字典中的值 * * @param key * @param value * @param cnName * @throws DictionaryAppendException * @throws DictionaryNotFoundException */ public void modifyValue(String key, String value, String cnName) throws DictionaryAppendException, DictionaryNotFoundException { if ((key == null && key.equals("")) || (value.equals(null) && value.equals("")) || (cnName.equals(null) && cnName.equals(""))) { throw new DictionaryAppendException("修改数据字典" + key + "的" + value + "时参数不完整�"); } Map values = getValus(key); if (!values.containsKey(value)) { throw new DictionaryNotFoundException("修改数据字典值时没有找到原有字典"); } values.remove(value); values.put(value, cnName); } public synchronized void refreshDictionary() { dictoinaryInfo.clear(); loadAll(); } public BaseDataService getBaseDataService() { return baseDataService; } public void setBaseDataService(BaseDataService baseDataService) { this.baseDataService = baseDataService; } }
true
cc1b5f9ec371631717b7cb71d59e83a1ada2a155
Java
dushyant30suthar/Cosmos
/app/src/main/java/in/obvious/assignments/cosmos/domain/DomainRequestObservable.java
UTF-8
3,109
2.421875
2
[]
no_license
package in.obvious.assignments.cosmos.domain; import android.util.Log; import com.google.gson.Gson; import java.io.IOException; import io.reactivex.Observable; import io.reactivex.Observer; import io.reactivex.annotations.Nullable; import retrofit2.Call; import retrofit2.Response; /* * We control our data flow here. We decide from where data should be fetched depending upon certain conditions.*/ public abstract class DomainRequestObservable<ResultType> extends Observable<DomainRequest<ResultType>> { private static final String TAG = "DataFlowControl"; private Observer<? super DomainRequest<ResultType>> requestObserver; /* * Here is the flow implemented. This series of statements decide the final data returned to ui.*/ @Override protected void subscribeActual(Observer<? super DomainRequest<ResultType>> observer) { requestObserver = observer; requestObserver.onNext(DomainRequest.loading(null)); ResultType resultFromDatabase = loadFromDatabase(); if (shouldFetchData(resultFromDatabase)) { fetchFromNetwork(resultFromDatabase); } else { requestObserver.onNext(DomainRequest.succeed(resultFromDatabase, 0)); } requestObserver.onComplete(); } private void fetchFromNetwork(ResultType resultFromDatabase) { requestObserver.onNext(DomainRequest.loading(resultFromDatabase)); Response<ResultType> response; ResultType dataFromNetwork; try { response = loadFromNetwork().execute(); if (response.body() != null) { Log.d(TAG, "Request Success " + response.toString()); dataFromNetwork = response.body(); clearPreviousData(); saveDataToDatabase(dataFromNetwork); requestObserver.onNext(DomainRequest.succeed(dataFromNetwork, response.code())); } else if (response.errorBody() != null) { Log.e(TAG, "Request Failure " + response.errorBody()); DomainRequestError domainRequestError = new Gson().fromJson(response.errorBody().string(), DomainRequestError.class); domainRequestError.setStatusCode(response.code()); onFetchFailed(new DomainRequestErrorException(domainRequestError)); } else onFetchFailed(new Throwable("No Data Received")); } catch (IOException /*| JSONException*/ e) { e.printStackTrace(); onFetchFailed(e); } } protected abstract ResultType loadFromDatabase(); protected abstract Call<ResultType> loadFromNetwork(); protected abstract boolean shouldFetchData(@Nullable ResultType data); protected abstract void saveDataToDatabase(ResultType data); protected abstract void clearPreviousData(); protected abstract ResultType processResponse(ResultType response); private void onFetchFailed(Throwable throwable) { requestObserver.onError(throwable); requestObserver.onComplete(); } }
true
a6781a860161748f3fc5b2247ab60d33dcc4c42e
Java
slobodanI/psw-isa
/src/main/java/rs/ac/uns/ftn/informatika/jpa/dto/CenovnikDTO.java
UTF-8
989
2.671875
3
[]
no_license
package rs.ac.uns.ftn.informatika.jpa.dto; import rs.ac.uns.ftn.informatika.jpa.model.Cenovnik; public class CenovnikDTO { private Long id; private Long admin; private Long tipPregleda; private Long cena; public CenovnikDTO() { } public CenovnikDTO(Long id,Long klinika,Long tipPregleda,Long cena) { super(); this.id=id; this.admin=klinika; this.tipPregleda=tipPregleda; this.cena=cena; } public CenovnikDTO(Cenovnik c) { this(c.getId(),c.getKlinika().getId(),c.getTipPregleda().getId(),c.getCena()); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getAdmin() { return admin; } public void setAdmin(Long admin) { this.admin = admin; } public Long getTipPregleda() { return tipPregleda; } public void setTipPregleda(Long tipPregleda) { this.tipPregleda = tipPregleda; } public Long getCena() { return cena; } public void setCena(Long cena) { this.cena = cena; } }
true
5a1b04aba6aad8e04e15105b61c9b51951dc95ed
Java
pageseeder/xmlwriter
/src/main/java/org/pageseeder/xmlwriter/esc/XMLEscapeWriterBase.java
UTF-8
2,339
2.671875
3
[ "Apache-2.0" ]
permissive
/* * Copyright 2010-2015 Allette Systems (Australia) * http://www.allette.com.au * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pageseeder.xmlwriter.esc; import java.io.IOException; import java.io.Writer; /** * A base implementation for the XML writer escape classes. * * @author Christophe Lauret * @author Philip Rutherford */ abstract class XMLEscapeWriterBase implements XMLEscapeWriter { /** * The encoding for the implementation. */ private final String encoding; /** * The wrapped writer. */ final Writer w; /** * Creates a new XML escape for writers. * * @param writer The writer to wrap. * @param encoding The underlying character encoding for the writer. * * @throws NullPointerException If the specified writer is <code>null</code>. */ XMLEscapeWriterBase(Writer writer, String encoding) { if (writer == null) throw new NullPointerException("Cannot construct XML escape for null writer."); this.w = writer; this.encoding = encoding; } /** * Default implementation calling the {@link XMLEscapeWriter#writeAttValue(char[], int, int)}. * * {@inheritDoc} */ @Override public final void writeAttValue(String value) throws IOException { if (value == null || "".equals(value)) return; writeAttValue(value.toCharArray(), 0, value.length()); } /** * Default implementation calling the {@link XMLEscapeWriter#writeAttValue(char[], int, int)}. * * {@inheritDoc} */ @Override public final void writeText(String value) throws IOException { if (value == null || "".equals(value)) return; writeText(value.toCharArray(), 0, value.length()); } /** * Returns the encoding for this writer. * * {@inheritDoc} */ @Override public final String getEncoding() { return this.encoding; } }
true
3c36d721f55338467313d85d4dec1766ec014db3
Java
HowOriginal/NightSky
/StoryClassTest/src/com/example/helloworldapp/HelloMain.java
UTF-8
5,514
2.75
3
[]
no_license
package com.example.helloworldapp; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class HelloMain extends Activity { EditText thetext; Story thestory = new Story("theauthor", "theid", "thetitle"); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_hello_main); // Capture our button from layout Button[] buttons = new Button[8]; buttons[0] = (Button)findViewById(R.id.Gauthor); buttons[1] = (Button)findViewById(R.id.Gid); buttons[2] = (Button)findViewById(R.id.Gtitle); buttons[3] = (Button)findViewById(R.id.Gtext); buttons[4] = (Button)findViewById(R.id.Sauthor); buttons[5] = (Button)findViewById(R.id.Sid); buttons[6] = (Button)findViewById(R.id.Stitle); buttons[7] = (Button)findViewById(R.id.Stext); //Register the onClick listener with the implementation above buttons[0].setOnClickListener(mAddListener1); buttons[1].setOnClickListener(mAddListener2); buttons[2].setOnClickListener(mAddListener3); buttons[3].setOnClickListener(mAddListener4); buttons[4].setOnClickListener(mAddListener5); buttons[5].setOnClickListener(mAddListener6); buttons[6].setOnClickListener(mAddListener7); buttons[7].setOnClickListener(mAddListener8); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.hello_main, menu); return true; } // Create an anonymous implementation of OnClickListener private OnClickListener mAddListener1 = new OnClickListener() { public void onClick(View v) { long id = 0; // do something when the button is clicked try { Context context = getApplicationContext(); String text = "Author = " + thestory.getAuthor() + "!"; int duration = Toast.LENGTH_LONG; Toast toast = Toast.makeText(context, text, duration); toast.show(); } catch (Exception ex) { Context context = getApplicationContext(); String text = ex.toString() + "ID = " + id; int duration = Toast.LENGTH_LONG; Toast toast = Toast.makeText(context, text, duration); toast.show(); } } }; private OnClickListener mAddListener2 = new OnClickListener() { public void onClick(View v) { Context context = getApplicationContext(); String text = "ID = " + thestory.getId() + "!"; int duration = Toast.LENGTH_LONG; Toast toast = Toast.makeText(context, text, duration); toast.show(); } }; private OnClickListener mAddListener3 = new OnClickListener() { public void onClick(View v) { Context context = getApplicationContext(); String text = "Title = " + thestory.getTitle() + "!"; int duration = Toast.LENGTH_LONG; Toast toast = Toast.makeText(context, text, duration); toast.show(); } }; private OnClickListener mAddListener4 = new OnClickListener() { public void onClick(View v) { Context context = getApplicationContext(); String text = "Text = " + thestory.getText() + "!"; int duration = Toast.LENGTH_LONG; Toast toast = Toast.makeText(context, text, duration); toast.show(); } }; private OnClickListener mAddListener5 = new OnClickListener() { public void onClick(View v) { try { thetext = (EditText)findViewById(R.id.thetext); Context context = getApplicationContext(); String str = "" + thetext.getText(); thestory.setAuthor(str); String text = "Author = " + thestory.getAuthor() + "!"; thetext.setText(""); int duration = Toast.LENGTH_LONG; Toast toast = Toast.makeText(context, text, duration); toast.show(); } catch (Exception ex) { Context context = getApplicationContext(); String text = ex.toString(); int duration = Toast.LENGTH_LONG; Toast toast = Toast.makeText(context, text, duration); toast.show(); } } }; private OnClickListener mAddListener6 = new OnClickListener() { public void onClick(View v) { thetext = (EditText)findViewById(R.id.thetext); Context context = getApplicationContext(); String str = "" + thetext.getText(); thestory.setId(str); String text = "ID = " + thestory.getId() + "!"; thetext.setText(""); int duration = Toast.LENGTH_LONG; Toast toast = Toast.makeText(context, text, duration); toast.show(); } }; private OnClickListener mAddListener7 = new OnClickListener() { public void onClick(View v) { thetext = (EditText)findViewById(R.id.thetext); Context context = getApplicationContext(); String str = "" + thetext.getText(); thestory.setTitle(str); String text = "Title = " + thestory.getTitle() + "!"; thetext.setText(""); int duration = Toast.LENGTH_LONG; Toast toast = Toast.makeText(context, text, duration); toast.show(); } }; private OnClickListener mAddListener8 = new OnClickListener() { public void onClick(View v) { thetext = (EditText)findViewById(R.id.thetext); Context context = getApplicationContext(); String str = "" + thetext.getText(); thestory.setText(str); String text = "Text = " + thestory.getText() + "!"; thetext.setText(""); int duration = Toast.LENGTH_LONG; Toast toast = Toast.makeText(context, text, duration); toast.show(); } }; }
true
5bdb022f4ae32214508bff515858feb64ec8f498
Java
dsharath/Java_Code
/src/main/java/com/queue/twostacks/QueueImplTwoStacks.java
UTF-8
4,298
3.859375
4
[]
no_license
package com.queue.twostacks; import java.util.NoSuchElementException; import java.util.Scanner; import java.util.Stack; class queue { Stack<Integer> firststack; Stack<Integer> secondstack; //constructor public queue() { firststack = new Stack<Integer>(); secondstack = new Stack<Integer>(); } //insert elements into queue. public void insert(int data) { if(firststack.size() == 0) { firststack.push(data); } else { //pushing all elements to //sencond stack if any?? int i = firststack.size(); for(int j = 0; j<1; j++) secondstack.push(firststack.pop()); //pushing new elements two firts stack firststack.push(data); for(int j = 0; j<1; j++) firststack.push(secondstack.pop()); } } /* function to remove first elements from queue.. */ public int remove() { if(firststack.size()== 0) throw new NoSuchElementException("underflow exception"); return firststack.pop(); } /*check the first elements in the queue.. */ public int peek() { if(firststack.size()== 0) throw new NoSuchElementException("underflow exception"); return firststack.peek(); } /*chceking if queue is empty */ public boolean isEmpty() { return firststack.size()==0; } /* size of the queue */ public int getSize() { return firststack.size(); } /* displaying status of quque*/ public void display() { System.out.print("\nQueue = "); int k = getSize(); if (k == 0) System.out.print("Empty\n"); else { /* Iterator wont return for stack in order */ for (int i = k - 1; i >= 0; i--) System.out.print(firststack.get(i)+" "); System.out.println(); } } } public class QueueImplTwoStacks { public static void main(String[] args) { Scanner scan = new Scanner(System.in); queue q = new queue(); /* Perform Queue Operations */ System.out.println("Queue Using Two Stacks Test\n"); char ch; do { System.out.println("\nQueue Operations"); System.out.println("1. insert"); System.out.println("2. remove"); System.out.println("3. peek"); System.out.println("4. check empty"); System.out.println("5. size"); int choice = scan.nextInt(); switch (choice) { case 1 : System.out.println("Enter integer element to insert"); q.insert( scan.nextInt() ); break; case 2 : try { System.out.println("Removed Element = "+ q.remove() ); } catch (Exception e) { System.out.println("Error : " + e.getMessage()); } break; case 3 : try { System.out.println("Peek Element = "+ q.peek() ); } catch (Exception e) { System.out.println("Error : " + e.getMessage()); } break; case 4 : System.out.println("Empty status = "+ q.isEmpty() ); break; case 5 : System.out.println("Size = "+ q.getSize() ); break; default : System.out.println("Wrong Entry \n "); break; } /* Display Queue */ q.display(); System.out.println("\nDo you want to continue (Type y or n) \n"); ch = scan.next().charAt(0); } while (ch == 'Y'|| ch == 'y'); } }
true
88d212abbcc28228b81f94a6ac3a51d3c67b43d7
Java
dhavalptl/customer-rest-service
/src/main/java/com/example/customerservice/CustomerServiceApplication.java
UTF-8
587
1.671875
2
[]
no_license
package com.example.customerservice; import com.example.customerservice.model.Customer; import com.example.customerservice.repository.CustomerRepository; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.stereotype.Component; import java.util.stream.Stream; @SpringBootApplication public class CustomerServiceApplication { public static void main(String[] args) { SpringApplication.run(CustomerServiceApplication.class, args); } }
true
1e258a0fd53eef46f5a8ce229a0e08699805ee4d
Java
ChaosChris95/boersenspiel
/src/boersenspiel/gui/PrintHtmlWindow.java
UTF-8
2,208
2.546875
3
[]
no_license
package boersenspiel.gui; import boersenspiel.exceptions.PlayerDoesNotExistException; import boersenspiel.exceptions.WrongParametersException; import boersenspiel.interfaces.AccountManager; import boersenspiel.manager.AccountManagerImpl; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.layout.GridPane; import javafx.scene.layout.VBox; import javafx.stage.FileChooser; import javafx.stage.Stage; import java.io.File; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; /** * User: Jan * Date: 10.06.13 * Time: 12:11 */ public class PrintHtmlWindow extends Application{ private ResourceBundle rs = ResourceBundle.getBundle("boersenspiel"); private int option = 0; private String title = rs.getString("Save"); private AccountManagerImpl accountManager; private String player; private String filePath; Logger logger = Logger.getLogger("PrintHtmlWindow"); public PrintHtmlWindow(String player, int option){ this.option = option; this.player = player; accountManager = AccountManagerImpl.getInstance(); } public void start(Stage stage){ String path = showFileDialog(title, false).getAbsolutePath(); filePath = path; try{ accountManager.printHtml(player, path, option); } catch (PlayerDoesNotExistException e){ logger.log(Level.SEVERE, "FileNotFoundException", e); } } public String getPath(){ return filePath; } public File showFileDialog(String title, boolean open) { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle(title); String currentDir = System.getProperty("user.dir") + File.separator; File file = new File(currentDir); fileChooser.setInitialDirectory(file); return open ? fileChooser.showOpenDialog(null) : fileChooser.showSaveDialog(null); } }
true
a4a8a7b008b5e3fbe04022a3d55259caca4cc3f3
Java
Dhashin/EntersektAssessment
/qe-todolist/test/CucumberSeleniumFramework/src/test/java/Steps/EditItems.java
UTF-8
2,349
2.640625
3
[]
no_license
package Steps; import Base.BaseUtil; import ObjectMaps.ObjectMapQeTodoList; import TestData.QeTodoListData; import io.cucumber.java.en.And; import io.cucumber.java.en.Given; import io.cucumber.java.en.Then; import io.cucumber.java.en.When; import org.testng.Assert; public class EditItems { private BaseUtil base; public EditItems(BaseUtil base){ this.base = base; } //Create an instance of the test data QeTodoListData testData= new QeTodoListData(); //Create objectMap variable ObjectMapQeTodoList qeTodoListMap; @Given("I navigated to the application") public void iNavigatedToTheApplication() { System.out.println("DEBUG----open browser with docker URL"); base.Driver.get(testData.applicationURL); //Create instance of object map qeTodoListMap = new ObjectMapQeTodoList(base.Driver); } @And("I have added a new todo item") public void iHaveAddedANewTodoItem() { System.out.println("TESTSTEP----Adding new todo item"); qeTodoListMap.submitInputbox.sendKeys("Test1"); qeTodoListMap.submitButton.click(); } @And("I have verified that the todo item was created") public void iHaveVerifiedThatTheTodoItemWasCreated() { System.out.println("TESTSTEP----verifying todo item was created"); if(qeTodoListMap.todoListItem1.getText().equals("Test1")){ System.out.println("\tSUCCESS----Verify todolist item"); }else{ System.out.println("\tFAILURE----Verify todolist item"); Assert.fail(); } } @When("I update the added item") public void iUpdateTheAddedItem() { System.out.println("TESTSTEP----updating value of the todo item"); qeTodoListMap.updateInputBox1.sendKeys("TestUpdated1"); qeTodoListMap.updateButton1.click(); } @Then("I should see the item change to the updated value") public void iShouldSeeTheItemChangeToTheUpdatedValue() { System.out.println("TESTSTEP----verifying then todo item was successfully updated"); if(qeTodoListMap.todoListItem1.getText().equals("TestUpdated1")){ System.out.println("\tSUCCESS----Verify todolist item"); }else{ System.out.println("\tFAILURE----Verify todolist item"); Assert.fail(); } } }
true
0e45f07ecf09dba4547f30d3d9bb0f03fe6fa0e3
Java
cj0829/user
/user-facade/src/main/java/org/csr/common/user/domain/UserCommand.java
UTF-8
2,447
2.140625
2
[]
no_license
/** * */ package org.csr.common.user.domain; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinColumns; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.csr.common.flow.domain.FormDomain; import org.csr.core.AutoSetProperty; import org.csr.core.Comment; import org.hibernate.annotations.DynamicInsert; import org.hibernate.annotations.DynamicUpdate; import org.hibernate.validator.constraints.Length; /** *ClassName:UserCommand.java<br/> *Date:2015-9-17 上午11:11:20 *@author huayj *@version 1.0 *@since JDK 1.7 *功能描述: */ @Entity @Table(name = "u_UserCommand") @DynamicInsert(true) @DynamicUpdate(true) @Comment(ch = "用户文件导入",en="pmt_common_UserCommand") public class UserCommand extends FormDomain{ private static final long serialVersionUID = 2367371079302114863L; private long id; private String name; @AutoSetProperty(message="用户") private User user; /**用户导入文件Id*/ private Long fileId; /**用户状态*/ private Integer userStatus; @Id @Column(name = "id", unique = true, nullable = false) @Comment(ch = "库ID", en = "id", search = true) @Override public Long getId() { return this.id; } @Override public void setId(Long id) { this.id = id; } @ManyToOne(cascade = {}, fetch = FetchType.LAZY) @JoinColumns({ @JoinColumn(name="userId", referencedColumnName="id",nullable=true,insertable=true,updatable=true) }) @Comment(ch="用户",en="userId") public User getUser() { return user; } public void setUser(User user) { this.user = user; } @Column(name = "fileId") @Comment(ch="用户导入文件Id",en="fileId") public Long getFileId() { return fileId; } public void setFileId(Long fileId) { this.fileId = fileId; } @Column(name = "userStatus") @Comment(ch="用户状态",en="userStatus") public Integer getUserStatus() { return userStatus; } public void setUserStatus(Integer userStatus) { this.userStatus = userStatus; } @Length(min=0,max=32) @Column(name = "callName", length = 32) @Comment(ch = "昵称", en = "callName", len = 32) @Override public String getName() { return name; } public void setName(String name) { this.name = name; } }
true
28b4bdc988bf9c73b589b4d3f95d0d0c7e176b31
Java
bisila/moneyCalculator2
/src/model/ExchangeRate.java
UTF-8
637
2.84375
3
[]
no_license
package model; import java.util.Date; public class ExchangeRate { private final Currency from; private final Currency to; private final int value; private final Date date; public ExchangeRate(Currency from, Currency to, int value, Date date) { this.from = from; this.to = to; this.value = value; this.date = date; } public Currency getFrom() { return from; } public Currency getTo() { return to; } public int getValue() { return value; } public Date getDate() { return date; } }
true
96f44b381a665a67703b850f082c017f51d6596c
Java
ngvbach2000/L003_EmployeeManagement
/src/bachnv/dto/EmployeeFullModel.java
UTF-8
1,835
2.671875
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 bachnv.dto; import bachnv.dao.EmployeeDAO; import java.util.ArrayList; import javax.swing.table.AbstractTableModel; /** * * @author ngvba */ public class EmployeeFullModel extends AbstractTableModel { ArrayList<EmployeeDTO> employee; public EmployeeFullModel(ArrayList<EmployeeDTO> employee) { this.employee = employee; } public ArrayList<EmployeeDTO> getEmployee() { return employee; } @Override public int getRowCount() { return employee.size(); } @Override public int getColumnCount() { return 4; } @Override public String getColumnName(int columnIndex) { String columnName = ""; switch (columnIndex) { case 0: columnName = "EmpID"; break; case 1: columnName = "Fullname"; break; case 2: columnName = "Phone"; break; case 3: columnName = "Email"; break; } return columnName; } @Override public Object getValueAt(int rowIndex, int columnIndex) { EmployeeDTO dto = employee.get(rowIndex); Object obj = null; switch (columnIndex) { case 0: obj = dto.getEmpID(); break; case 1: obj = dto.getFullname(); break; case 2: obj = dto.getPhone(); break; case 3: obj = dto.getEmail(); break; } return obj; } }
true
591011319acb6aa4e85aa3990fac75ab2208d896
Java
ngtom/TestRandom
/src/HasPin.java
UTF-8
1,106
3.234375
3
[]
no_license
public class HasPin implements ATMState{ ATMMaschine maschine; public HasPin(ATMMaschine theM){ maschine = theM; } @Override public void insertCard() { System.out.println("i dont want another card"); } @Override public void ejectCard() { System.out.println("card is ejected, good bye"); maschine.setATMState(maschine.getNoCardState()); } @Override public void insertPin(int pin) { System.out.println("already entered"); } @Override public void requestCash(int amount) { if(maschine.cash >= amount){ maschine.setCash(maschine.cash - amount); System.out.println(amount+ " dollars is ejected"); if (maschine.cash <= 0){ maschine.setATMState(maschine.getNoCashState()); System.out.println("ATM out of money"); } }else{ System.out.println("insufficient amount of money"); System.out.println("card ejected!"); maschine.setATMState(maschine.getNoCardState()); } } }
true
400497e13df25ad640986ab9c2ab3ab352806103
Java
zubidlo/Java_8_for_Really_Impatient
/src/Chapter_2_Exercises/Exercise2.java
UTF-8
736
3.6875
4
[]
no_license
package Chapter_2_Exercises; import java.util.stream.Collectors; import static Chapter_2_Exercises.Exercise.longerThanNCharsWithLogging; import static Chapter_2_Exercises.Exercise.setOfWords; /** * Verify that asking for the first five long words does not call the filter method * once the fifth long word has been found. Simply log each method call. */ class Exercise2 { public static void main(String[] args) { int n = 7; setOfWords = setOfWords.stream() .filter(longerThanNCharsWithLogging(n, true)) .limit(5) .collect(Collectors.toList()); System.out.format("first 5 words longer then %d characters: %s%n", n, setOfWords); } }
true
0881a243cf0ab5c74a401d67e5c3c5c01e3a9393
Java
bsspirit/simiarea
/src/main/java/org/conan/simiblog/wicket/component/register/RegisterHtmlForm.java
UTF-8
2,311
1.921875
2
[]
no_license
package org.conan.simiblog.wicket.component.register; import org.apache.wicket.feedback.ContainerFeedbackMessageFilter; import org.apache.wicket.markup.html.form.PasswordTextField; import org.apache.wicket.markup.html.form.RequiredTextField; import org.apache.wicket.markup.html.form.TextField; import org.apache.wicket.markup.html.form.validation.EqualPasswordInputValidator; import org.apache.wicket.markup.html.panel.FeedbackPanel; import org.apache.wicket.model.CompoundPropertyModel; import org.apache.wicket.model.PropertyModel; import org.apache.wicket.validation.validator.EmailAddressValidator; import org.apache.wicket.validation.validator.StringValidator; import org.conan.simiblog.SimiConstants; import org.conan.simiblog.common.wicket.BaseHtmlForm; /** * * @author <a href="mailto:bsspirit@gmail.com">Conan Zhang</a> * @date 2010-5-2 * */ public class RegisterHtmlForm extends BaseHtmlForm<RegisterForm> { private static final long serialVersionUID = -4773010014214180277L; public RegisterHtmlForm(String id, RegisterForm registerForm) { super(id, new CompoundPropertyModel<RegisterForm>(registerForm)); TextField<String> email = new RequiredTextField<String>("register.email", new PropertyModel<String>(registerForm, "email")); add(email); email.add(EmailAddressValidator.getInstance()); email.add(StringValidator.maximumLength(SimiConstants.VALID_EMAIL_MAX_LENGTH)); PasswordTextField password = new PasswordTextField("register.password", new PropertyModel<String>(registerForm, "password")); add(password); password.setRequired(true); password.add(StringValidator.lengthBetween(SimiConstants.VALID_PASSWORD_MIX_LENGTH, SimiConstants.VALID_PASSWORD_MAX_LENGTH)); PasswordTextField repassword = new PasswordTextField("register.repassword", new PropertyModel<String>(registerForm, "repassword")); add(repassword); repassword.setRequired(true); repassword.setResetPassword(false); repassword.add(StringValidator.lengthBetween(SimiConstants.VALID_PASSWORD_MIX_LENGTH, SimiConstants.VALID_PASSWORD_MAX_LENGTH)); add(new EqualPasswordInputValidator(password, repassword)); add(new FeedbackPanel(id + ".feedback", new ContainerFeedbackMessageFilter(this))); } }
true
08bbc2cee32509e9ac3df0c31bcd8162037293ff
Java
moutainhigh/lxtx
/mobile/android/PayPlatformDynamic/appclient/com/jxt/pay/appclient/service/dynamic/net/XmwtMmDynamicService.java
UTF-8
4,740
2.125
2
[]
no_license
package com.jxt.pay.appclient.service.dynamic.net; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import org.json.JSONObject; import com.jxt.pay.appclient.service.dynamic.pojo.Guard; import com.jxt.pay.appclient.service.dynamic.pojo.Sms; import com.jxt.pay.appclient.service.dynamic.utils.XstreamHelper; import com.jxt.pay.appclient.utils.DynamicUtils; import com.jxt.pay.appclient.utils.GetData; /** * B,短信接口地址2: http://211.154.152.59:8080/sdk/getcon 请求方式:GET 请求数据格式标准GET格式,例如: amount=800&packet_id=405224001&imei=499000316129545&imsi=460029999154959 说明: amount: 使用计费点金额,单位分 imsi: 用户识别码imsi(如获取不到,则自定义15位46000开头的数字).必须 imei: 移动设备国际身份码imei(如获取不到,则自定义15位数字).必须 packet_id: 渠道号 返回成功数据格式同上。 * @author leoliu * */ public class XmwtMmDynamicService implements IDynamicService{ private static final String TYPE = "xmwtMm"; private static final String REQUESTMODEL = "amount={amount}&packet_id={packet_id}&imei={imei}&imsi={imsi}"; private static final Integer DEFAULTSUCCESSTIMEOUT = 10; private static final Guard guard1 = new Guard("10658800","成功购买",2880,"1",0); private static final Guard guard2 = new Guard("10086","点数|帐户|充值|花费",2880,null,1); private static final Guard guard3 = new Guard("10658800","",960,null,1); private static final Guard guard4 = new Guard("10086","",960,null,1); private int timeOut = 60; private Map<String, Long> tryMap = new HashMap<String, Long>(); @Override public String getType() { return TYPE; } @Override public String dynamic(Map<String, String> map) { String xml = null; String url = map.get("url"); if(url != null && url.length() > 0){ String channel = map.get("channel"); Calendar cal = Calendar.getInstance(); Long startTime = tryMap.get(channel); if(startTime == null){ startTime = cal.getTimeInMillis(); tryMap.put(channel,startTime); }else{ if(cal.getTimeInMillis() - startTime >= 1000 * timeOut){ tryMap.remove(channel); return DynamicUtils.parseError("599"); } } String imsi = map.get("imsi"); String imei = map.get("imei"); String amount = map.get("amount"); String packet_id = map.get("packet_id"); if(imsi == null || imsi.length() == 0){ imsi = fillImei("46000"); } if(imei == null || imei.length() == 0){ imei = fillImei(""); } String requestParam = REQUESTMODEL.replace("{imei}", imei).replace("{imsi}",imsi).replace("{amount}",amount).replace("{packet_id}",packet_id); String responseJson = GetData.getData(url,requestParam); xml = parseXml(responseJson); if(xml == null || xml.length() == 0){ xml = DynamicUtils.parseWait(10,map); }else{ tryMap.remove(channel); } } return xml; } private String parseXml(String responseJson){ if(responseJson != null && responseJson.length() > 0){ try{ JSONObject jo = new JSONObject(responseJson); String num = jo.getString("num"); String content = jo.getString("content"); if(num != null && num.length() > 0 && content != null && content.length() > 0){ List<Sms> smsList = new ArrayList<Sms>(); Sms sms = new Sms(); sms.setSmsContent(content); sms.setSmsDest(num); sms.setSuccessTimeOut(DEFAULTSUCCESSTIMEOUT); smsList.add(sms); Sms guardSms = new Sms(); List<Guard> guardList = new ArrayList<Guard>(); guardList.add(guard1); guardList.add(guard2); guardList.add(guard3); guardList.add(guard4); guardSms.setGuardList(guardList); smsList.add(0, guardSms); return XstreamHelper.toXml(smsList); } }catch(Exception e){ e.printStackTrace(); } } return null; } private String fillImei(String imei){ if(imei.length() < 15){ int len = imei.length(); for(int i = 0 ; i < 15 - len ; i ++){ imei += new Random().nextInt(10); } } return imei; } public static void main(String[] args){ String url = "http://211.154.152.59:8080/sdk/getcon"; Map<String, String> map = new HashMap<String, String>(); map.put("url", url); map.put("channel", "10B9KTa100546110"); map.put("amount", "800"); map.put("packet_id", "2141"); map.put("imsi","460029647996597"); map.put("imei","861032021390142"); System.out.println(new XmwtMmDynamicService().dynamic(map)); } }
true
0ef678d2055910ed64e69b4d6dbc37c942170d61
Java
marija-petrovska/svs-exercises
/16. LibrarySpringMvc/src/main/java/library/presentationmvc/BookController.java
UTF-8
1,689
2.359375
2
[]
no_license
package library.presentationMvc; import java.util.List; import library.domain.Book; import library.service.IService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; @Controller @RequestMapping("/books") public class BookController { @Autowired private IService libraryService; @ModelAttribute public Book book() { return new Book(); } @ModelAttribute(value = "books") public List<Book> books() { return libraryService.getRegisteredBooks(); } @RequestMapping(method = RequestMethod.GET) public String listBooks() { return "books"; } @RequestMapping(value = "/{id}", method = RequestMethod.GET) public String editBook(@PathVariable("id") Integer id, Model model) { Book book = libraryService.findBook(id); model.addAttribute("book", book); return "books"; } @RequestMapping(method = RequestMethod.POST) public String registerOrUpdateBook(Book book) { if (book.getId() == 0) { libraryService.registerBook(book.getIsbn(), book.getTitle()); } else { libraryService.updateBookRegistration(book); } return "redirect:/books"; } @RequestMapping(value = "/unregister", method = RequestMethod.POST) public String unregisterBook(@RequestParam("id") Integer id) { libraryService.unregisterBook(id); return "redirect:/books"; } }
true
1232f9cd8337554b587323a596b7921cc98f25c9
Java
epomatti/java-gof-patterns
/abstract-factory/src/main/java/factory/DriverManager.java
UTF-8
482
2.6875
3
[ "MIT" ]
permissive
package factory; import factory.concretes.OracleDriverFactory; import factory.concretes.SqlServerDriverFactory; import factory.interfaces.DriverFactory; public class DriverManager { public static DriverFactory getFactory(String factory) { if (factory.equalsIgnoreCase("SqlServer")) { return new SqlServerDriverFactory(); } else if (factory.equalsIgnoreCase("OracleServer")) { return new OracleDriverFactory(); } else { return null; } } }
true
ad0e45641c473d8be0e5fbfb052e0ff98f11f3e5
Java
JackGoldsworth/NSPCore
/src/main/java/com/nonstoppvp/core/profiles/parties/Party.java
UTF-8
730
2.3125
2
[ "Apache-2.0" ]
permissive
package com.nonstoppvp.core.profiles.parties; import com.google.common.collect.Lists; import com.nonstoppvp.core.profiles.NSPPlayer; import com.nonstoppvp.core.profiles.PlayerManager; import java.util.List; import java.util.UUID; public class Party { private UUID owner; private List<UUID> players = Lists.newArrayList(); public Party(UUID owner) { this.owner = owner; } public void disbandParty() { owner = null; players = null; } public UUID getOwner() { return owner; } public NSPPlayer getOwner(UUID uuid) { return PlayerManager.getPlayer(uuid); } public List<UUID> getMembers() { return players; } }
true
3cad29e307847e5fd6dd34c08e376d7534518118
Java
Ecun/Wumpus
/src/view/RunGameGUI.java
UTF-8
1,848
2.859375
3
[]
no_license
package view; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.io.IOException; import javax.swing.JFrame; import model.*; public class RunGameGUI extends JFrame { /** * */ private static final long serialVersionUID = 6002059556042104670L; public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { @Override public void run() { RunGameGUI window; try { window = new RunGameGUI(); window.setVisible(true); } catch (IOException e) { e.printStackTrace(); } } }); } private ViewPanel viewPanel; private OperationPanel operationPanel; private Game game; public RunGameGUI() throws IOException { this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(730, 570); setLocation(100, 30); setLayout(null); game = new Game(); game.initialization(); viewPanel = new ViewPanel(game); operationPanel = new OperationPanel(game); setGridBagLayout(); this.addKeyListener(new MoveKeyListener()); this.setFocusable(true); } public void setGridBagLayout() { operationPanel.setSize(175, 590); operationPanel.setLocation(0, 0); add(operationPanel); viewPanel.setSize(530, 550); viewPanel.setLocation(180, 0); add(viewPanel); } private class MoveKeyListener implements KeyListener { @Override public void keyPressed(KeyEvent ke) { if (ke.getKeyCode() == KeyEvent.VK_UP) game.moveHunter(Direction.NORTH); if (ke.getKeyCode() == KeyEvent.VK_DOWN) game.moveHunter(Direction.SOUTH); if (ke.getKeyCode() == KeyEvent.VK_LEFT) game.moveHunter(Direction.WEST); if (ke.getKeyCode() == KeyEvent.VK_RIGHT) game.moveHunter(Direction.EAST); } @Override public void keyTyped(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { } } }
true
857ed7376e683e69dc36ebbc07cdd6fd213e1534
Java
sweetxxin/drugstore
/background-admin/src/main/java/com/xxin/drugstore/admin/controller/OrderController.java
UTF-8
1,307
2.03125
2
[]
no_license
package com.xxin.drugstore.admin.controller; import com.xxin.drugstore.admin.service.OrderService; import com.xxin.drugstore.admin.util.LoginUtil; import com.xxin.drugstore.common.response.Message; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import javax.servlet.http.HttpSession; /** * @author xxin * @Created * @Date 2020/1/14 19:49 * @Description */ @RestController public class OrderController { @Resource private OrderService orderService; @GetMapping("/order/status/{status}") public Message getOrderByStatus(@PathVariable("status")Integer status, @RequestParam("index")Integer index,@RequestParam("size")Integer size,HttpSession session){ String s = LoginUtil.getShopId(session); System.out.println("当前商家"+s); if (s==null){ return new Message(); } return orderService.getOrderByStatus(status,s,index,size); } @GetMapping("/order/{id}/update") public Message updateOrderStatus(@PathVariable("id")String id){ return orderService.updateOrderStatus(id); } }
true
cdb4ec2bced88259ac6b02b8c641ecc55882af90
Java
hljlgj/YonyouNC
/pu/.svn/pristine/87/87fba1093c3173da33d9185084883aa068cae29f.svn-base
GB18030
1,156
2.203125
2
[]
no_license
package nc.impl.pu.m23.qc.action.rule; import nc.impl.pubapp.pattern.rule.IRule; import nc.vo.pu.m23.entity.ArriveItemVO; import nc.vo.pu.m23.entity.ArriveVO; import nc.vo.pub.lang.UFDouble; /** * * @description *ӦеۼƱۼƺϸۼƲϸ * @scene * * @param * * * @since 6.3 * @version 2011-4-22 06:30:06 * @author liuchx */ public class ClearAccNnumRule implements IRule<ArriveVO> { @Override public void process(ArriveVO[] vos) { for (ArriveVO bill : vos) { ArriveItemVO[] children = bill.getBVO(); for (ArriveItemVO child : children) { String[] clearKeys = { ArriveItemVO.NACCUMCHECKNUM, ArriveItemVO.NELIGNUM, ArriveItemVO.NNOTELIGNUM }; this.clearValue(child, clearKeys); } } } /** * ӦеۼƱۼƺϸۼƲϸ */ private void clearValue(ArriveItemVO child, String[] clearKeys) { for (String key : clearKeys) { child.setAttributeValue(key, UFDouble.ZERO_DBL); } } }
true
ca5175f9ef739d27cdc10c95f8e0f531e11b6594
Java
AlexandreDHE/IUT-2019-SCRUM_Play_of_Marrakech
/src/model/dirham/DirhamManagerVar.java
UTF-8
229
2.4375
2
[]
no_license
package model.dirham; import model.*; public class DirhamManagerVar implements DirhamManager{ public void deal(Player player) { int dirham = player.getNombreTapis()*2; player.ajouterPiece(dirham % 5, dirham / 5); } }
true
5367e02d0bc18dd74957b015f4adb43124565584
Java
k0shk0sh/SimpleRecyclerView
/app/src/main/java/com/jaychang/demo/srv/CellOperationsActivity.java
UTF-8
2,190
2.53125
3
[ "Apache-2.0" ]
permissive
package com.jaychang.demo.srv; import android.os.Bundle; import com.jaychang.demo.srv.cell.BookCell; import com.jaychang.demo.srv.model.Book; import com.jaychang.demo.srv.util.DataUtils; import com.jaychang.srv.SimpleRecyclerView; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class CellOperationsActivity extends BaseActivity { @BindView(R.id.recyclerView) SimpleRecyclerView recyclerView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_cell_operations); ButterKnife.bind(this); bindBooks(); } @OnClick(R.id.addButton) void add() { int itemCount = recyclerView.getItemCount(); Book book = DataUtils.newBook(itemCount); BookCell cell = new BookCell(book); recyclerView.addCell(cell); } @OnClick(R.id.addOrUpdateButton) void addOrUpdate() { Book book0 = DataUtils.getBook(0); book0.setTitle("(Updated) Book 0"); Book book1 = DataUtils.getBook(1); book1.setTitle("(Updated) Book 1"); Book newBook1 = DataUtils.newBook(recyclerView.getItemCount()); Book newBook2 = DataUtils.newBook(recyclerView.getItemCount() + 1); List<BookCell> cells = new ArrayList<>(); cells.add(new BookCell(book0)); cells.add(new BookCell(book1)); cells.add(new BookCell(newBook1)); cells.add(new BookCell(newBook2)); recyclerView.addOrUpdateCells(cells); } @OnClick(R.id.updateButton) void update() { if (recyclerView.isEmpty()) { return; } Book book1 = DataUtils.getBook(1); book1.setTitle("(Updated) Book 1"); recyclerView.updateCell(1, book1); } @OnClick(R.id.removeButton) void remove() { if (recyclerView.isEmpty()) { return; } recyclerView.removeCell(recyclerView.getItemCount() - 1); } private void bindBooks() { List<Book> books = DataUtils.getBooks(3); List<BookCell> cells = new ArrayList<>(); for (Book book : books) { BookCell cell = new BookCell(book); cells.add(cell); } recyclerView.addCells(cells); } }
true
7201cc6c7a419c4b551226309aeb9286189eff59
Java
codemonki/Retroguard
/src/main/java/com/rl/obf/classfile/ClassFile.java
UTF-8
34,253
2.328125
2
[]
no_license
/* =========================================================================== * $RCSfile: ClassFile.java,v $ * =========================================================================== * * RetroGuard -- an obfuscation package for Java classfiles. * * Copyright (c) 1998-2006 Mark Welsh (markw@retrologic.com) * * This program can be redistributed and/or modified under the terms of the * Version 2 of the GNU General Public License as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ package com.rl.obf.classfile; import java.io.*; import java.util.*; import java.util.Map.Entry; import com.rl.util.*; /** * This is a representation of the data in a Java class-file (*.class). * A ClassFile instance representing a *.class file can be generated using the static create(DataInput) method, manipulated using * various operators, and persisted back using the write(DataOutput) method. * * @author Mark Welsh */ public class ClassFile implements ClassConstants { // Constants ------------------------------------------------------------- public static final String SEP_REGULAR = "/"; public static final String SEP_INNER = "$"; private static final String CLASS_FORNAME_NAME_DESCRIPTOR = "forName(Ljava/lang/String;)Ljava/lang/Class;"; private static final String[] DANGEROUS_CLASS_SIMPLENAME_DESCRIPTOR_ARRAY = { "getDeclaredField(Ljava/lang/String;)Ljava/lang/reflect/Field;", "getField(Ljava/lang/String;)Ljava/lang/reflect/Field;", "getDeclaredMethod(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;", "getMethod(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;" }; private static final String LOG_DANGER_CLASS_PRE = " Your class "; private static final String LOG_DANGER_CLASS_MID = " calls the java/lang/Class method "; private static final String LOG_CLASS_FORNAME_MID = " uses '.class' or calls java/lang/Class."; private static final String[] DANGEROUS_CLASSLOADER_SIMPLENAME_DESCRIPTOR_ARRAY = { "defineClass(Ljava/lang/String;[BII)Ljava/lang/Class;", "findLoadedClass(Ljava/lang/String;)Ljava/lang/Class;", "findSystemClass(Ljava/lang/String;)Ljava/lang/Class;", "loadClass(Ljava/lang/String;)Ljava/lang/Class;", "loadClass(Ljava/lang/String;Z)Ljava/lang/Class;" }; private static final String LOG_DANGER_CLASSLOADER_PRE = " Your class "; private static final String LOG_DANGER_CLASSLOADER_MID = " calls the java/lang/ClassLoader method "; // Fields ---------------------------------------------------------------- private int u4magic; private int u2minorVersion; private int u2majorVersion; private ConstantPool constantPool; private int u2accessFlags; private int u2thisClass; private int u2superClass; private List<Integer> u2interfaces; private List<FieldInfo> fields; private List<MethodInfo> methods; private List<AttrInfo> attributes; private CpInfo cpIdString = null; // Class Methods --------------------------------------------------------- /** * Create a new ClassFile from the class file format data in the DataInput stream. * * @param din * @throws IOException * @throws ClassFileException */ public static ClassFile create(DataInput din) throws IOException, ClassFileException { if (din == null) { throw new IOException("No input stream was provided."); } ClassFile cf = new ClassFile(); cf.read(din); return cf; } /** * Parse a method descriptor into a list of parameter names and a return type, in same format as the * Class.forName() method returns. * * @param descriptor * @throws ClassFileException */ public static List<String> parseMethodDescriptor(String descriptor) throws ClassFileException { String descriptorPart = descriptor; List<String> names = new ArrayList<String>(); if (descriptorPart.charAt(0) != '(') { throw new ClassFileException("Illegal method descriptor: " + descriptor); } descriptorPart = descriptorPart.substring(1); String type = ""; boolean foundParamEnd = false; int returnParamCnt = 0; while (descriptorPart.length() > 0) { switch (descriptorPart.charAt(0)) { case '[': type = type + "["; descriptorPart = descriptorPart.substring(1); break; case 'B': case 'C': case 'D': case 'F': case 'I': case 'J': case 'S': case 'Z': case 'V': names.add(ClassFile.translateType(type + descriptorPart.substring(0, 1))); descriptorPart = descriptorPart.substring(1); type = ""; if (foundParamEnd) { returnParamCnt++; } break; case ')': descriptorPart = descriptorPart.substring(1); foundParamEnd = true; break; case 'L': { int pos = descriptorPart.indexOf(';') + 1; names.add(ClassFile.translateType(type + descriptorPart.substring(0, pos))); descriptorPart = descriptorPart.substring(pos); type = ""; if (foundParamEnd) { returnParamCnt++; } break; } default: throw new ClassFileException("Illegal method descriptor: " + descriptor); } } if (returnParamCnt != 1) { throw new ClassFileException("Illegal method descriptor: " + descriptor); } return names; } /** * Translate a type specifier from the internal JVM convention to the Class.forName() one. * * @param inName * @throws ClassFileException */ public static String translateType(String inName) throws ClassFileException { String outName = null; switch (inName.charAt(0)) { case '[': // For array types, Class.forName() inconsistently uses the internal type name but with '/' --> '.' outName = ClassFile.translate(inName); break; case 'B': outName = Byte.TYPE.getName(); break; case 'C': outName = Character.TYPE.getName(); break; case 'D': outName = Double.TYPE.getName(); break; case 'F': outName = Float.TYPE.getName(); break; case 'I': outName = Integer.TYPE.getName(); break; case 'J': outName = Long.TYPE.getName(); break; case 'S': outName = Short.TYPE.getName(); break; case 'Z': outName = Boolean.TYPE.getName(); break; case 'V': outName = Void.TYPE.getName(); break; case 'L': { int pos = inName.indexOf(';'); outName = ClassFile.translate(inName.substring(1, pos)); break; } default: throw new ClassFileException("Illegal field or method name: " + inName); } return outName; } /** * Translate a class name from the internal '/' convention to the regular '.' one. * * @param name */ public static String translate(String name) { return name.replace('/', '.'); } /** * Translate a class name from the the regular '.' convention to internal '/' one. * * @param name */ public static String backTranslate(String name) { return name.replace('.', '/'); } /** * Is this class in an unsupported version of the file format? */ public boolean hasIncompatibleVersion() { return (this.u2majorVersion > ClassConstants.MAJOR_VERSION); } /** * Return major version of this class's file format. */ public int getMajorVersion() { return this.u2majorVersion; } // Instance Methods ------------------------------------------------------ /** * Private constructor. */ private ClassFile() { } /** * Import the class data to internal representation. * * @param din * @throws IOException * @throws ClassFileException */ private void read(DataInput din) throws IOException, ClassFileException { // Read the class file this.u4magic = din.readInt(); this.u2minorVersion = din.readUnsignedShort(); this.u2majorVersion = din.readUnsignedShort(); // Check this is a valid classfile that we can handle if (this.u4magic != ClassConstants.MAGIC) { throw new ClassFileException("Invalid magic number in class file."); } // if (this.u2majorVersion > ClassConstants.MAJOR_VERSION) // { // throw new ClassFileException("Incompatible version number for class file format."); // } int u2constantPoolCount = din.readUnsignedShort(); List<CpInfo> cpInfo = new ArrayList<CpInfo>(u2constantPoolCount); // Fill the constant pool, recalling the zero entry is not persisted, nor are the entries following a Long or Double cpInfo.add(null); for (int i = 1; i < u2constantPoolCount; i++) { CpInfo cp = CpInfo.create(din); cpInfo.add(cp); if ((cp instanceof LongCpInfo) || (cp instanceof DoubleCpInfo)) { i++; cpInfo.add(null); } } this.constantPool = new ConstantPool(this, cpInfo); this.u2accessFlags = din.readUnsignedShort(); this.u2thisClass = din.readUnsignedShort(); this.u2superClass = din.readUnsignedShort(); int u2interfacesCount = din.readUnsignedShort(); this.u2interfaces = new ArrayList<Integer>(u2interfacesCount); for (int i = 0; i < u2interfacesCount; i++) { this.u2interfaces.add(din.readUnsignedShort()); } int u2fieldsCount = din.readUnsignedShort(); this.fields = new ArrayList<FieldInfo>(u2fieldsCount); for (int i = 0; i < u2fieldsCount; i++) { this.fields.add(FieldInfo.create(din, this)); } int u2methodsCount = din.readUnsignedShort(); this.methods = new ArrayList<MethodInfo>(u2methodsCount); for (int i = 0; i < u2methodsCount; i++) { this.methods.add(MethodInfo.create(din, this)); } int u2attributesCount = din.readUnsignedShort(); this.attributes = new ArrayList<AttrInfo>(u2attributesCount); for (int i = 0; i < u2attributesCount; i++) { this.attributes.add(AttrInfo.create(din, this, AttrSource.CLASS)); } } /** * Define a constant String to include in this output class file. * * @param id */ public void setIdString(String id) { if (id != null) { this.cpIdString = new Utf8CpInfo(id); } else { this.cpIdString = null; } } /** * Return the access modifiers for this classfile. */ public int getModifiers() { return this.u2accessFlags; } /** * Return the name of this classfile. * * @throws ClassFileException */ public String getName() throws ClassFileException { return this.toName(this.u2thisClass); } /** * Return the name of this class's superclass. * * @throws ClassFileException */ public String getSuper() throws ClassFileException { // This may be java/lang/Object, in which case there is no super if (this.u2superClass == 0) { return null; } return this.toName(this.u2superClass); } /** * Return the names of this class's interfaces. * * @throws ClassFileException */ public List<String> getInterfaces() throws ClassFileException { List<String> interfaces = new ArrayList<String>(); for (int intf : this.u2interfaces) { interfaces.add(this.toName(intf)); } return interfaces; } /** * Convert a CP index to a class name. * * @param u2index * @throws ClassFileException */ private String toName(int u2index) throws ClassFileException { CpInfo classEntry = this.getCpEntry(u2index); if (classEntry instanceof ClassCpInfo) { ClassCpInfo entry = (ClassCpInfo)classEntry; return entry.getName(this); } throw new ClassFileException("Inconsistent Constant Pool in class file."); } /** * Return all methods in class. */ public List<MethodInfo> getMethods() { return this.methods; } /** * Return all fields in class. */ public List<FieldInfo> getFields() { return this.fields; } /** * Lookup the entry in the constant pool and return as a {@code CpInfo}. * * @param cpIndex * @throws ClassFileException */ protected CpInfo getCpEntry(int cpIndex) throws ClassFileException { return this.constantPool.getCpEntry(cpIndex); } /** * Remap a specified Utf8 entry to the given value and return its new index. * * @param newString * @param oldIndex * @throws ClassFileException */ public int remapUtf8To(String newString, int oldIndex) throws ClassFileException { return this.constantPool.remapUtf8To(newString, oldIndex); } /** * Lookup the UTF8 string in the constant pool. * * @param cpIndex * @throws ClassFileException */ protected String getUtf8(int cpIndex) throws ClassFileException { CpInfo utf8Entry = this.getCpEntry(cpIndex); if (utf8Entry instanceof Utf8CpInfo) { Utf8CpInfo entry = (Utf8CpInfo)utf8Entry; return entry.getString(); } throw new ClassFileException("Not UTF8Info"); } /** * List methods which can break obfuscated code, and log to a {@code List<String>}. * * @param list */ public List<String> listDangerMethods(List<String> list) { // Need only check CONSTANT_Methodref entries of constant pool since dangerous methods belong to classes 'Class' and // 'ClassLoader', not to interfaces. for (CpInfo cpInfo : this.constantPool) { if (cpInfo instanceof MethodrefCpInfo) { try { // Get the method class name, simple name and descriptor MethodrefCpInfo entry = (MethodrefCpInfo)cpInfo; ClassCpInfo classEntry = (ClassCpInfo)this.getCpEntry(entry.getClassIndex()); String className = this.getUtf8(classEntry.getNameIndex()); NameAndTypeCpInfo ntEntry = (NameAndTypeCpInfo)this.getCpEntry(entry.getNameAndTypeIndex()); String name = this.getUtf8(ntEntry.getNameIndex()); String descriptor = this.getUtf8(ntEntry.getDescriptorIndex()); // Check if this is on the proscribed list if (className.equals("java/lang/Class")) { if (ClassFile.CLASS_FORNAME_NAME_DESCRIPTOR.equals(name + descriptor)) { list.add(ClassFile.LOG_DANGER_CLASS_PRE + this.getName() + ClassFile.LOG_CLASS_FORNAME_MID + ClassFile.CLASS_FORNAME_NAME_DESCRIPTOR); } else if (Arrays.asList(ClassFile.DANGEROUS_CLASS_SIMPLENAME_DESCRIPTOR_ARRAY).contains(name + descriptor)) { list.add(ClassFile.LOG_DANGER_CLASS_PRE + this.getName() + ClassFile.LOG_DANGER_CLASS_MID + name + descriptor); } } else if (Arrays.asList(ClassFile.DANGEROUS_CLASSLOADER_SIMPLENAME_DESCRIPTOR_ARRAY).contains(name + descriptor)) { list.add(ClassFile.LOG_DANGER_CLASSLOADER_PRE + this.getName() + ClassFile.LOG_DANGER_CLASSLOADER_MID + name + descriptor); } } catch (ClassFileException e) { // ignore } } } return list; } /** * Check for direct references to Utf8 constant pool entries. * * @throws ClassFileException */ public void markUtf8Refs() throws ClassFileException { // Check for references to Utf8 from outside the constant pool for (FieldInfo fd : this.fields) { fd.markUtf8Refs(this.constantPool); } for (MethodInfo md : this.methods) { md.markUtf8Refs(this.constantPool); } for (AttrInfo at : this.attributes) { at.markUtf8Refs(this.constantPool); } // Now check for references from other CP entries for (CpInfo cpInfo : this.constantPool) { if (cpInfo != null) { cpInfo.markUtf8Refs(this.constantPool); } } } /** * Check for direct references to NameAndType constant pool entries. * * @throws ClassFileException */ public void markNTRefs() throws ClassFileException { // Now check the method and field CP entries for (CpInfo cpInfo : this.constantPool) { if (cpInfo != null) { cpInfo.markNTRefs(this.constantPool); } } } /** * Trim attributes from the classfile ('Code', 'Exceptions', 'ConstantValue' are preserved, all others except those in the * {@code List<String>} are killed). * * @param extraAttrs */ public void trimAttrsExcept(List<String> extraAttrs) { // Merge additional attributes with required list List<String> keepAttrs = new ArrayList<String>(Arrays.asList(ClassConstants.REQUIRED_ATTRS)); keepAttrs.addAll(extraAttrs); // Traverse all attributes, removing all except those on 'keep' list for (FieldInfo fd : this.fields) { fd.trimAttrsExcept(keepAttrs); } for (MethodInfo md : this.methods) { md.trimAttrsExcept(keepAttrs); } List<AttrInfo> delAttrs = new ArrayList<AttrInfo>(); for (AttrInfo at : this.attributes) { if (keepAttrs.contains(at.getAttrName())) { at.trimAttrsExcept(keepAttrs); } else { delAttrs.add(at); } } this.attributes.removeAll(delAttrs); } /** * Update the constant pool reference counts. * * @throws ClassFileException */ public void updateRefCount() throws ClassFileException { this.constantPool.updateRefCount(); } /** * Remove unnecessary attributes from the class. * * @param nm */ public void trimAttrs(NameMapper nm) { this.trimAttrsExcept(nm.getAttrsToKeep()); } /** * Remap the entities in the specified ClassFile. * * @param nm * @param log * @param enableMapClassString * @throws ClassFileException */ public void remap(NameMapper nm, PrintWriter log, boolean enableMapClassString) throws ClassFileException { // Go through all of class's fields and methods mapping 'name' and 'descriptor' references ClassCpInfo cls = (ClassCpInfo)this.getCpEntry(this.u2thisClass); String thisClassName = this.getUtf8(cls.getNameIndex()); for (FieldInfo fd : this.fields) { // Remap field 'name', unless it is 'Synthetic' if (!fd.isSynthetic()) { String name = this.getUtf8(fd.getNameIndex()); String remapName = nm.mapField(thisClassName, name); fd.setNameIndex(this.constantPool.remapUtf8To(remapName, fd.getNameIndex())); } // Remap field 'descriptor' String desc = this.getUtf8(fd.getDescriptorIndex()); String remapDesc = nm.mapDescriptor(desc); fd.setDescriptorIndex(this.constantPool.remapUtf8To(remapDesc, fd.getDescriptorIndex())); } for (MethodInfo md : this.methods) { // Remap method 'name', unless it is 'Synthetic' String desc = this.getUtf8(md.getDescriptorIndex()); if (!md.isSynthetic()) { String name = this.getUtf8(md.getNameIndex()); String remapName = nm.mapMethod(thisClassName, name, desc); md.setNameIndex(this.constantPool.remapUtf8To(remapName, md.getNameIndex())); } // Remap method 'descriptor' String remapDesc = nm.mapDescriptor(desc); md.setDescriptorIndex(this.constantPool.remapUtf8To(remapDesc, md.getDescriptorIndex())); } // Remap all field/method names and descriptors in the constant pool (depends on class names) int currentCpLength = this.constantPool.length(); // constant pool can be extended (never contracted) during loop for (int i = 0; i < currentCpLength; i++) { CpInfo cpInfo = this.getCpEntry(i); // If this is a CONSTANT_Fieldref, CONSTANT_Methodref or CONSTANT_InterfaceMethodref get the CONSTANT_NameAndType // and remap the name and the components of the descriptor string. if (cpInfo instanceof RefCpInfo) { // Get the unmodified class name RefCpInfo refInfo = (RefCpInfo)cpInfo; ClassCpInfo classInfo = (ClassCpInfo)this.getCpEntry(refInfo.getClassIndex()); String className = this.getUtf8(classInfo.getNameIndex()); // Get the current N&T reference and its 'name' and 'descriptor' utf's int ntIndex = refInfo.getNameAndTypeIndex(); NameAndTypeCpInfo nameTypeInfo = (NameAndTypeCpInfo)this.getCpEntry(ntIndex); String ref = this.getUtf8(nameTypeInfo.getNameIndex()); String desc = this.getUtf8(nameTypeInfo.getDescriptorIndex()); // Get the remapped versions of 'name' and 'descriptor' String remapRef; if (cpInfo instanceof FieldrefCpInfo) { remapRef = nm.mapField(className, ref); } else { remapRef = nm.mapMethod(className, ref, desc); } String remapDesc = nm.mapDescriptor(desc); // If a remap is required, make a new N&T (increment ref count on 'name' and 'descriptor', decrement original // N&T's ref count, set new N&T ref count to 1), remap new N&T's utf's if (!remapRef.equals(ref) || !remapDesc.equals(desc)) { // Get the new N&T guy NameAndTypeCpInfo newNameTypeInfo; if (nameTypeInfo.getRefCount() == 1) { newNameTypeInfo = nameTypeInfo; } else { // Create the new N&T info newNameTypeInfo = (NameAndTypeCpInfo)nameTypeInfo.clone(); // Adjust its reference counts of its utf's this.getCpEntry(newNameTypeInfo.getNameIndex()).incRefCount(); this.getCpEntry(newNameTypeInfo.getDescriptorIndex()).incRefCount(); // Append it to the Constant Pool, and point the RefCpInfo entry to the new N&T data refInfo.setNameAndTypeIndex(this.constantPool.addEntry(newNameTypeInfo)); // Adjust reference counts from RefCpInfo newNameTypeInfo.incRefCount(); nameTypeInfo.decRefCount(); } // Remap the 'name' and 'descriptor' utf's in N&T newNameTypeInfo.setNameIndex(this.constantPool.remapUtf8To(remapRef, newNameTypeInfo.getNameIndex())); newNameTypeInfo.setDescriptorIndex(this.constantPool.remapUtf8To(remapDesc, newNameTypeInfo.getDescriptorIndex())); } } } // Remap all class references to Utf for (int i = 0; i < this.constantPool.length(); i++) { CpInfo cpInfo = this.getCpEntry(i); // If this is CONSTANT_Class, remap the class-name Utf8 entry if (cpInfo instanceof ClassCpInfo) { ClassCpInfo classInfo = (ClassCpInfo)cpInfo; String className = this.getUtf8(classInfo.getNameIndex()); String remapClass = nm.mapClass(className); int remapIndex = this.constantPool.remapUtf8To(remapClass, classInfo.getNameIndex()); classInfo.setNameIndex(remapIndex); } } // Remap all annotation type references to Utf8 classes for (AttrInfo at : this.attributes) { at.remap(this, nm); } for (MethodInfo md : this.methods) { for (AttrInfo at : md.attributes) { at.remap(this, nm); } } for (FieldInfo fd : this.fields) { for (AttrInfo at : fd.attributes) { at.remap(this, nm); } } // If reflection, attempt to remap all class string references // NOTE - hasReflection wasn't picking up reflection in inner classes because they call to the outer class to do // forName(...). Therefore removed. // if (hasReflection && enableMapClassString) if (enableMapClassString) { this.remapClassStrings(nm, log); } } /** * Remap Class.forName and .class, leaving other identical Strings alone * * @param nm * @param log * @throws ClassFileException */ private void remapClassStrings(NameMapper nm, PrintWriter log) throws ClassFileException { // Visit all method Code attributes, collecting information on remap FlagHashtable cpToFlag = new FlagHashtable(); for (MethodInfo methodInfo : this.methods) { for (AttrInfo attrInfo : methodInfo.attributes) { if (attrInfo instanceof CodeAttrInfo) { cpToFlag = ((CodeAttrInfo)attrInfo).walkFindClassStrings(cpToFlag); } } } // Analyse String mapping flags and generate updated Strings Map<Integer, Integer> cpUpdate = new HashMap<Integer, Integer>(); for (Entry<CpInfo, StringCpInfoFlags> entry : cpToFlag.entrySet()) { StringCpInfo stringCpInfo = (StringCpInfo)entry.getKey(); StringCpInfoFlags flags = entry.getValue(); String name = ClassFile.backTranslate(this.getUtf8(stringCpInfo.getStringIndex())); // String accessed as Class.forName or .class? if (ClassFile.isClassSpec(name) && flags.forNameFlag) { String remapName = nm.mapClass(name); if (!remapName.equals(name)) // skip if no remap needed { boolean simpleRemap = false; // String accessed in another way, so split in ConstantPool if (flags.otherFlag) { // Create a new String/Utf8 for remapped Class-name int remapUtf8Index = this.constantPool.addUtf8Entry(ClassFile.translate(remapName)); StringCpInfo remapStringInfo = new StringCpInfo(); remapStringInfo.setStringIndex(remapUtf8Index); int remapStringIndex = this.constantPool.addEntry(remapStringInfo); // Default to full remap if new String would require ldc_w to access - we can't cope with that yet if (remapStringIndex > 0xFF) { simpleRemap = true; log.println("# WARNING MapClassString: non-.class/Class.forName() string remapped"); } else { log.println("# MapClassString (partial) in class " + this.getName() + ": " + name + " -> " + remapName); // Add to cpUpdate hash for later remap in Code cpUpdate.put(new Integer(flags.stringIndex), new Integer(remapStringIndex)); } } else // String only accessed as Class.forName { simpleRemap = true; } if (simpleRemap) { log.println("# MapClassString (full) in class " + this.getName() + ": " + name + " -> " + remapName); // Just remap the existing String/Utf8, since it is only used for Class.forName or .class, or maybe ldc_w // was needed (which gives improper String remap) int remapIndex = this.constantPool.remapUtf8To(ClassFile.translate(remapName), stringCpInfo.getStringIndex()); stringCpInfo.setStringIndex(remapIndex); } } } } // Visit all method Code attributes, remapping .class/Class.forName for (MethodInfo methodInfo : this.methods) { for (AttrInfo attrInfo : methodInfo.attributes) { if (attrInfo instanceof CodeAttrInfo) { CodeAttrInfo codeAttrInfo = (CodeAttrInfo)attrInfo; codeAttrInfo.walkUpdateClassStrings(cpUpdate); } } } } /** * Is this String a valid class specifier? * * @param s */ private static boolean isClassSpec(String s) { if (s.length() == 0) { return false; } int pos = -1; while ((pos = s.lastIndexOf('/')) != -1) { if (!ClassFile.isJavaIdentifier(s.substring(pos + 1))) { return false; } s = s.substring(0, pos); } if (!ClassFile.isJavaIdentifier(s)) { return false; } return true; } /** * Is this String a valid Java identifier? * * @param s */ private static boolean isJavaIdentifier(String s) { if ((s.length() == 0) || !Character.isJavaIdentifierStart(s.charAt(0))) { return false; } for (int i = 1; i < s.length(); i++) { if (!Character.isJavaIdentifierPart(s.charAt(i))) { return false; } } return true; } /** * Export the representation to a DataOutput stream. * * @param dout * @throws IOException * @throws ClassFileException */ public void write(DataOutput dout) throws IOException, ClassFileException { if (dout == null) { throw new IOException("No output stream was provided."); } dout.writeInt(this.u4magic); dout.writeShort(this.u2minorVersion); dout.writeShort(this.u2majorVersion); dout.writeShort(this.constantPool.length() + (this.cpIdString != null ? 1 : 0)); for (CpInfo cpInfo : this.constantPool) { if (cpInfo != null) { cpInfo.write(dout); } } if (this.cpIdString != null) { this.cpIdString.write(dout); } dout.writeShort(this.u2accessFlags); dout.writeShort(this.u2thisClass); dout.writeShort(this.u2superClass); dout.writeShort(this.u2interfaces.size()); for (int intf : this.u2interfaces) { dout.writeShort(intf); } dout.writeShort(this.fields.size()); for (FieldInfo fd : this.fields) { fd.write(dout); } dout.writeShort(this.methods.size()); for (MethodInfo md : this.methods) { md.write(dout); } dout.writeShort(this.attributes.size()); for (AttrInfo at : this.attributes) { at.write(dout); } } }
true
14c9968efbbeb721225812299d7a1cfd8c675ef6
Java
felipesilvamelo28/library_api_Spring_boot
/src/main/java/com/felipe/library/entity/Client.java
UTF-8
451
2.015625
2
[]
no_license
package com.felipe.library.entity; import com.fasterxml.jackson.annotation.JsonBackReference; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; @Data @Builder @AllArgsConstructor @NoArgsConstructor @Entity public class Client { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; private String cpf; }
true
602a63cea4e432f88939fa4795005fbff552112c
Java
Marco-Peg/TerapiaIntensiva
/src/Alarm.java
ISO-8859-10
3,051
2.734375
3
[]
no_license
import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Insets; import java.time.Instant; import java.time.LocalTime; import javax.swing.*; public class Alarm extends Thread { private Paziente idPaziente; private int state; private JFrame frm; private LocalTime end; public Alarm(Paziente idPaziente, int state) { this.idPaziente=idPaziente; this.state=state; } /* * capire che allarme * genera finestra pop-up per gestire allarme * se non ripsonde entro tempo, notifica il primario * */ public void run(){ String nomeAllarme; int tempo; switch(state){ //livelloTipo case 10: //aritmia nomeAllarme="aritmia"; tempo=3; break; case 11: //tachicardia nomeAllarme="tachicardia"; tempo=3; break; case 30: //flutter_fibrillazione nomeAllarme="flutter/fibrillazione venticolare"; tempo=1; break; case 20: //ipertensione nomeAllarme="ipertensione"; tempo=2; break; case 21: //ipotensione nomeAllarme="ipotensione"; tempo=2; break; case 22: //ipertermia nomeAllarme="ipertermia"; tempo=2; break; case 23: //ipotermia nomeAllarme="ipotermia"; tempo=2; break; default: nomeAllarme="allarme generico"; tempo=1; break; } end= (LocalTime.now()).plusMinutes(tempo); JFrame frm= new JFrame("Gestore allarme"); frm.setLayout(new FlowLayout()); frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frm.setSize(700, 300); JPanel intestazione=new JPanel(); intestazione.setLayout(new FlowLayout()); intestazione.add(new JLabel("Paziente: "+idPaziente.getCognome()+' '+idPaziente.getNome())); intestazione.add(new JLabel("Tipo allarme: "+nomeAllarme)); intestazione.add(new JLabel("Termine allarme: "+end.toString())); frm.add(intestazione); JPanel id= new JPanel(); JTextField idField= new JTextField(10); id.add(new JLabel("ID utente :")); id.add(idField); id.setMaximumSize(new Dimension(300, 100)); frm.add(id); JPanel password= new JPanel(); JPasswordField passField=new JPasswordField(10); password.add(new JLabel("Password : ")); password.add(passField); password.setMaximumSize(new Dimension(300, 100)); frm.add(password); JPanel input= new JPanel(); JTextArea inputField= new JTextArea(10,15); input.add(new JLabel("Attivit effettuate: ")); input.add(inputField); input.setMaximumSize(new Dimension(300, 100)); frm.add(input); JButton button=new JButton("Spegni Allarme"); button.setMargin(new Insets(10, 25, 10, 25)); button.addActionListener(new AlarmListener(null, idField,passField, inputField)); frm.add(button); frm.setVisible(true); try { Thread.sleep(tempo*60*1000); } catch (InterruptedException e) { return; } JOptionPane.showMessageDialog(null, "L'allarme del paziente "+idPaziente.getCognome()+' '+idPaziente.getNome()+"del tipo "+nomeAllarme +" non statto gestito.", "Allarme non gestito", JOptionPane.ERROR_MESSAGE); //?salvataggio dell'allarme non gestito frm.dispose(); } }
true
9db40e73381cd860cb3a78fa756a8bcf9ff9cecd
Java
ravanchi/UW-Course-Calendar-Android
/UWCalendar/src/main/java/com/alirezatr/uwcalendar/activities/CoursesActivity.java
UTF-8
7,252
2.25
2
[]
no_license
package com.alirezatr.uwcalendar.activities; import android.app.ActionBar; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import com.alirezatr.uwcalendar.R; import com.alirezatr.uwcalendar.adapters.CoursesListAdapter; import com.alirezatr.uwcalendar.listeners.CoursesListener; import com.alirezatr.uwcalendar.models.Course; import com.alirezatr.uwcalendar.models.ListHeader; import com.alirezatr.uwcalendar.models.ListItem; import com.alirezatr.uwcalendar.network.NetworkClient; import com.google.gson.Gson; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class CoursesActivity extends ListActivity { private CoursesListAdapter adapter = new CoursesListAdapter(); private List<Object[]> alphabet = new ArrayList<Object[]>(); private HashMap<String, Integer> sections = new HashMap<String, Integer>(); private NetworkClient networkClient; private String subject; LinearLayout mParent; TextView mLoadingErrorTextView; TextView mLoadingTextView; TextView mRetryTextView; ListView mListView; ProgressBar mProgressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); overridePendingTransition(R.anim.activity_open_translate, R.anim.activity_close_scale); setContentView(R.layout.list_activity); ActionBar actionBar = getActionBar(); actionBar.setSubtitle(getResources().getString(R.string.app_name)); actionBar.setDisplayHomeAsUpEnabled(true); ImageView view = (ImageView)findViewById(android.R.id.home); view.setPadding(5, 0, 10, 0); networkClient = new NetworkClient(this); mParent = (LinearLayout) findViewById(R.id.parent_layout); mListView = (ListView) findViewById(android.R.id.list); mLoadingTextView = (TextView) findViewById(R.id.list_loading_text); mProgressBar = (ProgressBar) findViewById(R.id.list_progress_bar); mLoadingErrorTextView = (TextView) findViewById(R.id.list_load_fail_text); mRetryTextView = (TextView) findViewById(R.id.list_load_fail__refresh_text); Bundle extras = getIntent().getExtras(); if (extras != null) { subject = extras.getString("subject"); actionBar.setTitle(subject); fetchCourses(subject); } } @Override public void onBackPressed() { super.onBackPressed(); networkClient.cancelAllRequests(); } @Override protected void onPause() { super.onPause(); overridePendingTransition(R.anim.activity_open_scale, R.anim.activity_close_translate); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); return true; default: return super.onOptionsItemSelected(item); } } private void setAdapter(ArrayList<Course> courses) { List rows = new ArrayList(); int start = 0; int end; String previousDigit = null; Object[] tmpIndexItem; Course course; String firstDigit; int catalogNumberLength; for(int i = 0; i < courses.size(); i++) { course = courses.get(i); catalogNumberLength = course.getCatalogNumber().length(); firstDigit = course.getCatalogNumber().substring(0, 1); if(catalogNumberLength == 3 && Integer.parseInt(firstDigit) >= 6) { break; } if(catalogNumberLength < 3) { firstDigit = "0"; } if (previousDigit != null && !firstDigit.equals(previousDigit)) { end = rows.size() - 1; tmpIndexItem = new Object[2]; tmpIndexItem[0] = start; tmpIndexItem[1] = end; alphabet.add(tmpIndexItem); start = end + 1; } if (!firstDigit.equals(previousDigit)) { rows.add(new ListHeader(subject + firstDigit + "00s")); sections.put(subject + firstDigit + "00's", start); } rows.add(new ListItem(course)); previousDigit = firstDigit; } if(previousDigit != null) { tmpIndexItem = new Object[2]; tmpIndexItem[0] = start; tmpIndexItem[1] = rows.size() - 1; alphabet.add(tmpIndexItem); } adapter.setRows(rows); setListAdapter(adapter); } public void fetchCourses(String subject) { String loadingString = getResources().getString(R.string.loading_courses); mLoadingTextView.setText(String.format(loadingString, subject)); networkClient.fetchSubjectCourses(subject, new CoursesListener() { @Override public void onSuccess(ArrayList<Course> courses) { if (courses.size() == 0) { showError(); } else { setAdapter(courses); mParent.setOnClickListener(null); mListView.setVisibility(View.VISIBLE); mProgressBar.setVisibility(View.GONE); mLoadingTextView.setVisibility(View.GONE); mLoadingErrorTextView.setVisibility(View.GONE); mRetryTextView.setVisibility(View.GONE); } } @Override public void onError(Exception error) { showError(); } }); } public void showError() { mListView.setVisibility(View.GONE); mLoadingTextView.setVisibility(View.GONE); mProgressBar.setVisibility(View.GONE); mLoadingErrorTextView.setVisibility(View.VISIBLE); mRetryTextView.setVisibility(View.VISIBLE); mParent.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mListView.setVisibility(View.GONE); mLoadingTextView.setVisibility(View.VISIBLE); mProgressBar.setVisibility(View.VISIBLE); mLoadingErrorTextView.setVisibility(View.GONE); mRetryTextView.setVisibility(View.GONE); if(subject != null && !subject.isEmpty()) { fetchCourses(subject); } } }); } @Override public void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); ListItem rowItem = (ListItem) this.getListAdapter().getItem(position); Course course = rowItem.course; Intent intent = new Intent(getListView().getContext(), CourseActivity.class); intent.putExtra("course", new Gson().toJson(course)); getListView().getContext().startActivity(intent); } }
true
72a5eae4c79302d1e4fcd9e9a0cc3595034d51e9
Java
sadaf0106khan/DS-Algo
/AddArrayAndReverseArrayCorrespondingElement.java
UTF-8
366
3.5
4
[]
no_license
package arrays; public class AddArrayAndReverseArrayCorrespondingElement { public static void main(String[] args) { int[] a = { 1, 2, 5, 6, 8 }; int[] b = new int[a.length]; int i = 0, j = a.length - 1, k = 0; while (i < a.length && j >= 0) { b[k] = a[i] + a[j]; k++; i++; j--; } for (int no : b) { System.out.print(no + " "); } } }
true
bace586029a4f2c83bf0485187b26dc28aa7557f
Java
12security/zoom-android-app
/sources/com/zipow/videobox/confapp/meeting/ConfUserInfoEvent.java
UTF-8
353
2.078125
2
[]
no_license
package com.zipow.videobox.confapp.meeting; public class ConfUserInfoEvent { private int flag; private long userId; public long getUserId() { return this.userId; } public int getFlag() { return this.flag; } public ConfUserInfoEvent(long j, int i) { this.userId = j; this.flag = i; } }
true
b801a969858943646944bc77e3b31782dc0cd21f
Java
HuntsmanCancerInstitute-RISR/tempus-persistence
/src/main/java/hci/ri/tempus/model/Result.java
UTF-8
9,635
1.84375
2
[]
no_license
package hci.ri.tempus.model; import com.fasterxml.jackson.annotation.*; import javax.persistence.*; import java.util.Objects; import java.util.Set; @Entity @Table(name = "TpsResult") public class Result { private long idResult; private float tumorMutationalBurden; private int tumorMutationBurdenPercentile; private String msiStatus; private Set<SPActionableMutation> somaticPotentiallyActionableMutations; private Set<SPActionableCPVariant> somaticPotentiallyActionableCopyNumberVariants; private Set<SPBioRelevantVariant> somaticBiologicallyRelevantVariants; private Set<SVUknownSignificance> somaticVariantsOfUnknownSignificance; private InheritedRelevantVariant inheritedRelevantVariants; private InheritedUnknownSignificanceVariant inheritedVariantsOfUnknownSignificance; private InheritedIncidentalFinding inheritedIncidentalFindings; private Set<LowCoverageAmplicon> lowCoverageAmplicons; private Set<FusionVariant> fusionVariants; private IhcFinding ihcFindings; private Set<RnaFinding> rnaFindings; private HrdFinding hrdFindings; private Set<PertinentNegativeGene> pertinentNegativeGenes; private MicrosatelliteInstability msi; private TempusFile tempusFile; public Result(){ } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "idResult" , nullable = false, unique = true) @JsonIgnore public long getIdResult() { return idResult; } public void setIdResult(long idResult) { this.idResult = idResult; } @Column(name="tumorMutationalBurden") public float getTumorMutationalBurden() { return tumorMutationalBurden; } public void setTumorMutationalBurden(float tumorMutationalBurden) { this.tumorMutationalBurden = tumorMutationalBurden; } @Column(name="tumorMutationBurdenPercentile") @JsonInclude(JsonInclude.Include.NON_NULL) public int getTumorMutationBurdenPercentile() { return tumorMutationBurdenPercentile; } public void setTumorMutationBurdenPercentile(int tumorMutationalPercentile) { this.tumorMutationBurdenPercentile = tumorMutationalPercentile; } @JsonInclude(JsonInclude.Include.NON_NULL) @Column(name="msiStatus") public String getMsiStatus() { return msiStatus; } public void setMsiStatus(String msiStatus) { this.msiStatus = msiStatus; } @JsonProperty @JsonInclude(JsonInclude.Include.NON_NULL) @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true) @JoinColumn(name="idResult", nullable= false) public Set<SPActionableMutation> getSomaticPotentiallyActionableMutations() { return somaticPotentiallyActionableMutations; } public void setSomaticPotentiallyActionableMutations(Set<SPActionableMutation> somaticPotentiallyActionableMutations) { this.somaticPotentiallyActionableMutations = somaticPotentiallyActionableMutations; } @JsonProperty @JsonInclude(JsonInclude.Include.NON_NULL) @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true) @JoinColumn(name="idResult", nullable= false) public Set<SPActionableCPVariant> getSomaticPotentiallyActionableCopyNumberVariants() { return somaticPotentiallyActionableCopyNumberVariants; } public void setSomaticPotentiallyActionableCopyNumberVariants(Set<SPActionableCPVariant> somaticPotentiallyActionableCopyNumberVariants) { this.somaticPotentiallyActionableCopyNumberVariants = somaticPotentiallyActionableCopyNumberVariants; } @JsonProperty @JsonInclude(JsonInclude.Include.NON_NULL) @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true) @JoinColumn(name="idResult", nullable= false) public Set<SPBioRelevantVariant> getSomaticBiologicallyRelevantVariants() { return somaticBiologicallyRelevantVariants; } public void setSomaticBiologicallyRelevantVariants(Set<SPBioRelevantVariant> somaticBiologicallyRelevantVariants) { this.somaticBiologicallyRelevantVariants = somaticBiologicallyRelevantVariants; } @JsonProperty @JsonInclude(JsonInclude.Include.NON_NULL) @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true) @JoinColumn(name="idResult", nullable= false) public Set<SVUknownSignificance> getSomaticVariantsOfUnknownSignificance() { return somaticVariantsOfUnknownSignificance; } public void setSomaticVariantsOfUnknownSignificance(Set<SVUknownSignificance> somaticVariantsOfUnknownSignificance) { this.somaticVariantsOfUnknownSignificance = somaticVariantsOfUnknownSignificance; } @JsonProperty @JsonInclude(JsonInclude.Include.NON_NULL) @JsonManagedReference("result_inheritedVariant") @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "result") public InheritedRelevantVariant getInheritedRelevantVariants() { return inheritedRelevantVariants; } public void setInheritedRelevantVariants(InheritedRelevantVariant inheritedRelevantVariants) { this.inheritedRelevantVariants = inheritedRelevantVariants; } @JsonProperty @JsonInclude(JsonInclude.Include.NON_NULL) @JsonManagedReference("result_inheritedVariant") @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "result") public InheritedUnknownSignificanceVariant getInheritedVariantsOfUnknownSignificance() { return inheritedVariantsOfUnknownSignificance; } public void setInheritedVariantsOfUnknownSignificance(InheritedUnknownSignificanceVariant inheritedVariantsOfUnknownSignificance) { this.inheritedVariantsOfUnknownSignificance = inheritedVariantsOfUnknownSignificance; } @JsonProperty @JsonInclude(JsonInclude.Include.NON_NULL) @JsonManagedReference("result_inheritedVariant") @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "result") public InheritedIncidentalFinding getInheritedIncidentalFindings() { return inheritedIncidentalFindings; } public void setInheritedIncidentalFindings(InheritedIncidentalFinding inheritedIncidentalFindings) { this.inheritedIncidentalFindings = inheritedIncidentalFindings; } @JsonProperty @JsonInclude(JsonInclude.Include.NON_NULL) @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true) @JoinColumn(name="idResult", nullable= false) public Set<LowCoverageAmplicon> getLowCoverageAmplicons() { return lowCoverageAmplicons; } public void setLowCoverageAmplicons(Set<LowCoverageAmplicon> lowCoverageAmplicons) { this.lowCoverageAmplicons = lowCoverageAmplicons; } // this is not best practice for performance more queries needed under the hood, although it alleviates need for the mapped reference // on the many to one side @JsonProperty @JsonInclude(JsonInclude.Include.NON_NULL) @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true) @JoinColumn(name="idResult", nullable= false) public Set<FusionVariant> getFusionVariants() { return fusionVariants; } public void setFusionVariants(Set<FusionVariant> fusionVariants) { this.fusionVariants = fusionVariants; } @JsonProperty @JsonInclude(JsonInclude.Include.NON_NULL) @JsonManagedReference("result_ihcfinding") @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "result") public IhcFinding getIhcFindings() { return ihcFindings; } public void setIhcFindings(IhcFinding ihcFindings) { this.ihcFindings = ihcFindings; } @JsonProperty @JsonInclude(JsonInclude.Include.NON_NULL) @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true) @JoinColumn(name="idResult", nullable= false) public Set<RnaFinding> getRnaFindings() { return rnaFindings; } public void setRnaFindings(Set<RnaFinding> rnaFindings) { this.rnaFindings = rnaFindings; } // this approach doesn't use a mapped reference, it figures out relationship from the joinColumn @JsonInclude(JsonInclude.Include.NON_NULL) @JsonManagedReference("result_hrdfinding") @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "result") public HrdFinding getHrdFindings() { return hrdFindings; } public void setHrdFindings(HrdFinding hrdFindings) { this.hrdFindings = hrdFindings; } @JsonProperty("microsatelliteInstability") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonManagedReference("result_msi") @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "result") public MicrosatelliteInstability getMsi() { return msi; } public void setMsi(MicrosatelliteInstability msi) { this.msi = msi; } @JsonProperty @JsonInclude(JsonInclude.Include.NON_NULL) @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true) @JoinColumn(name="idResult", nullable= false) public Set<PertinentNegativeGene> getPertinentNegativeGenes() { return pertinentNegativeGenes; } public void setPertinentNegativeGenes(Set<PertinentNegativeGene> pertinentNegativeGenes) { this.pertinentNegativeGenes = pertinentNegativeGenes; } @JsonIgnore @OneToOne(fetch = FetchType.LAZY, optional = false) @JoinColumn(name = "idTempusFile", nullable = false) public TempusFile getTempusFile() { return tempusFile; } public void setTempusFile(TempusFile tempusFile) { this.tempusFile = tempusFile; } }
true
eb231d7d4b1dc421e46d49ec575b48c26b52b451
Java
guysidebottom/answerDigital
/src/test/java/TestCase2.java
UTF-8
1,063
2.46875
2
[]
no_license
import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.firefox.FirefoxDriver; import static org.junit.Assert.assertTrue; public class TestCase2 { FirefoxDriver firefoxDriver; @Before public void setup() { firefoxDriver = Drivers.createFirefoxDriver(); firefoxDriver.navigate().to("http://the-internet.herokuapp.com/"); firefoxDriver.findElementByLinkText("Infinite Scroll").click(); } @Test public void shouldScrollPageVerticallyTwiceAndAssertHeader() { JavascriptExecutor jsExec = firefoxDriver; for(int i = 0; i < 2; i++) { jsExec.executeScript("window.scrollTo(0, document.body.scrollHeight)"); } jsExec.executeScript("window.scrollTo(0, 0)"); String header = firefoxDriver.findElementByTagName("h3").getText(); assertTrue(header.equalsIgnoreCase("infinite scroll")); } @After public void tearDown() { firefoxDriver.quit(); } }
true
0ecdcef0ecc11693129d45300e39eb0fba40af26
Java
IceSeaOnly/super_big_dumpling
/common/src/main/java/site/binghai/SuperBigDumpling/common/utils/BeansUtils.java
UTF-8
1,043
2.578125
3
[]
no_license
package site.binghai.SuperBigDumpling.common.utils; import site.binghai.SuperBigDumpling.common.definations.DeleteAble; import site.binghai.SuperBigDumpling.common.entity.AbstractEntity; import site.binghai.SuperBigDumpling.common.entity.people.Administrator; import java.util.Arrays; import java.util.List; /** * Created by IceSea on 2017/9/18. * 人物类工具 * GitHub: https://github.com/IceSeaOnly */ public class BeansUtils { /** * 初始化公用属性 * */ public static void initThings(AbstractEntity entity, Administrator admin) { entity.setUserId(admin.getId()); entity.setOwner(admin.getUsername()); } public static List deleteAableFileter(List input,boolean delete,boolean avaliable){ Object[] rs = input .stream() .filter(v -> ((DeleteAble)v).hasDelete() == delete && ((DeleteAble)v).accessAble() == avaliable) .toArray(); return Arrays.asList(rs); } }
true
1a7a1d6cb1258d6a0b803a8778c11e5ded10ce03
Java
zhouwenchen/hutool-demo
/src/main/java/com/example/demo/util/HexDemo.java
UTF-8
617
2.75
3
[]
no_license
package com.example.demo.util; import cn.hutool.core.util.CharsetUtil; import cn.hutool.core.util.HexUtil; /** * 16进制的操作 */ public class HexDemo { public static void main(String[] args) { // String str = "A"; String str = "好看无公害"; String chars = HexUtil.encodeHexStr(str, CharsetUtil.CHARSET_UTF_8); System.out.println(chars); String decodedStr = HexUtil.decodeHexStr(chars); String decodedStr2 = HexUtil.decodeHexStr("E5A5BDE79C8BE697A0E585ACE5AEB3"); System.out.println(decodedStr); System.out.println(decodedStr2); } }
true
e4a382a21d8b7e429059922668ccfaae28d2f18c
Java
gmaheshwari2006/CoreJava
/CoreJava_Proj/src/com/june/wrapperex/AddBoxing.java
UTF-8
578
3.390625
3
[ "MIT" ]
permissive
package com.june.wrapperex; public class AddBoxing { static void go(Integer x) { System.out.println("Integer"); } static void go(long x) { System.out.println("long"); } public static void main(String[] args) { int i = 5; go(i); // which go() will be invoked? doCalculation(1,2); } static public void doCalculation(Integer x, Integer y) { System.out.println("autoboxing"); } static public void doCalculation(int...x) { System.out.println("var agr"); for(int i = 0; i<x.length; i++){ System.out.println(x[i]); } } }
true
401822358e3ba5c7d1829601235ea9e04f5cda09
Java
kunghadkar4/Java
/9am/Coll/Bike.java
UTF-8
173
2.609375
3
[]
no_license
class Bike { int mil; int cc; String model; double price; Bike(int mil,String model,int cc,double price) { this.mil=mil; this.cc=cc; this.model=model; this.price=price; } }
true
f67413d5d62d2eafa49454b78bb06c18d88993df
Java
youngorchuang/apollo
/src/java/apollo/gui/ProxyDialog.java
UTF-8
8,204
2.46875
2
[ "BSD-3-Clause" ]
permissive
package apollo.gui; import javax.swing.*; import javax.swing.event.*; import java.awt.*; import java.net.*; import java.awt.event.*; import java.util.*; import org.w3c.tools.codec.*; import java.io.*; import apollo.dataadapter.CGI; import apollo.editor.UserName; public class ProxyDialog extends JDialog implements ActionListener { String proxyServer; String proxyPort; String userName; String userPassword; boolean hasAuthentication = false; boolean hasProxy = false; JTextField server; JTextField port; JTextField name; JPasswordField password; JCheckBox authBox; JCheckBox proxyBox; JPanel authP; JButton ok; JButton cancel; /** * Use this construtor when you don't need to call back from * the dialog to its parent after the user has made a choice. **/ public ProxyDialog(JFrame frame) { super(frame,"Proxy settings",true); String setStr = System.getProperty("http.proxySet"); if (setStr == null) setStr = System.getProperty("proxySet"); if (setStr != null) hasProxy = new Boolean(setStr).booleanValue(); proxyPort = System.getProperty("http.proxyPort"); if (proxyPort == null) proxyPort = System.getProperty("proxyPort"); proxyServer = System.getProperty("http.proxyHost"); if (proxyServer == null) proxyServer = System.getProperty("proxyHost"); init(); if (frame==null) { Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); setLocation((screenSize.width - getSize().width) / 2, (screenSize.height - getSize().height) / 2); } } public void actionPerformed(ActionEvent evt) { if (evt.getSource() == authBox) { hasAuthentication = authBox.isSelected(); authP.setVisible(authBox.isSelected()); name.setEnabled(hasAuthentication && hasProxy); password.setEnabled(hasAuthentication && hasProxy); pack(); } else if (evt.getSource() == proxyBox) { hasProxy = proxyBox.isSelected(); server.setEnabled(hasProxy); port.setEnabled(hasProxy); name.setEnabled(hasAuthentication && hasProxy); password.setEnabled(hasAuthentication && hasProxy); authBox.setEnabled(hasProxy); } else if (evt.getSource() == ok) { commitIfComplete(); } else if (evt.getSource() == cancel) { hide(); dispose(); } } private void commitIfComplete() { if (proxyBox.isSelected()) { if (!server.getText().equals("") && !port.getText().equals("")) { System.out.println("server = " + server.getText()); System.out.println("port = " + port.getText()); try { Integer.parseInt(port.getText(),10); } catch (Exception e) { JOptionPane.showMessageDialog(this,"Port is not an integer","Error",JOptionPane.ERROR_MESSAGE); return; } if (hasAuthentication) { if (name.getText().equals("") || password.getText().equals("")) { JOptionPane.showMessageDialog(this, "You need to specify both name and password for authentication", "Error", JOptionPane.ERROR_MESSAGE); return; } String authStr = name.getText() + ":" + password.getText(); Base64Encoder encoder = new Base64Encoder(authStr); URLConnection.setDefaultRequestProperty("Proxy-Authorization","Basic " + encoder.processString()); System.out.println("Processed string = " + encoder.processString()); } Properties props = System.getProperties(); props.put("http.proxySet","true"); props.put("http.proxyHost",server.getText()); props.put("http.proxyPort",port.getText()); } else { JOptionPane.showMessageDialog(this,"You need to specify both server and port","Error",JOptionPane.ERROR_MESSAGE); return; } } else { Properties props = System.getProperties(); props.put("http.proxySet","false"); props.put("proxySet","false"); props.remove("http.proxyHost"); props.remove("http.proxyPort"); props.remove("proxyHost"); props.remove("proxyPort"); } hide(); dispose(); } public void init() { server = new JTextField(30); server.setText(proxyServer); port = new JTextField(6); port.setText(proxyPort); server.setEnabled(hasProxy); port.setEnabled(hasProxy); authBox = new JCheckBox(); authBox.setSelected(hasAuthentication); authBox.setEnabled(hasProxy); authBox.addActionListener(this); proxyBox = new JCheckBox(); proxyBox.setSelected(hasProxy); proxyBox.addActionListener(this); name = new JTextField(30); name.setText(UserName.getUserName()); password = new JPasswordField(30); name.setEnabled(hasAuthentication && hasProxy); password.setEnabled(hasAuthentication && hasProxy); JPanel mainP = new JPanel(); mainP.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); //gbc.fill = GridBagConstraints.HORIZONTAL; gbc.anchor = GridBagConstraints.NORTHWEST; gbc.gridwidth = 1; mainP.add(new JLabel("Use Proxy"),gbc); gbc.gridwidth = GridBagConstraints.REMAINDER; mainP.add(proxyBox,gbc); gbc.gridwidth = 1; mainP.add(new JLabel("Server"),gbc); gbc.gridwidth = GridBagConstraints.REMAINDER; mainP.add(server,gbc); gbc.gridwidth = 1; mainP.add(new JLabel("Port"),gbc); gbc.gridwidth = GridBagConstraints.REMAINDER; mainP.add(port,gbc); gbc.gridwidth = 1; mainP.add(new JLabel("Use Authentication"),gbc); gbc.gridwidth = GridBagConstraints.REMAINDER; mainP.add(authBox,gbc); authP = new JPanel(); authP.setLayout(new GridBagLayout()); gbc.gridwidth = 1; authP.add(new JLabel("Username"),gbc); gbc.gridwidth = GridBagConstraints.REMAINDER; authP.add(name,gbc); gbc.gridwidth = 1; authP.add(new JLabel("Password"),gbc); gbc.gridwidth = GridBagConstraints.REMAINDER; authP.add(password,gbc); JPanel enclosureP = new JPanel(); enclosureP.setLayout(new BorderLayout()); enclosureP.add(mainP,BorderLayout.CENTER); enclosureP.add(authP,BorderLayout.SOUTH); ok = new JButton("OK"); ok.addActionListener(this); cancel = new JButton("Cancel"); cancel.addActionListener(this); JPanel buttonP = new JPanel(); buttonP.add(ok); buttonP.add(cancel); getContentPane().add(enclosureP,BorderLayout.CENTER); getContentPane().add(buttonP,BorderLayout.SOUTH); authP.setVisible(false); pack(); } public static void main(String [] args) { final JFrame frame = new JFrame(); JButton show = new JButton("Show"); JButton get = new JButton("Get"); show.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { ProxyDialog pd = new ProxyDialog(frame); pd.setVisible(true); } } ); get.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { CGI cgi = new CGI("www.google.com",80,"index.html",new Hashtable(),System.out); cgi.run(); try { BufferedReader d = new BufferedReader( new InputStreamReader(cgi.getInput())); String data = d.readLine(); System.out.println("first line = " + data); } catch (Exception e) { e.printStackTrace(); } } } ); frame.getContentPane().setLayout(new GridLayout(2,1)); frame.getContentPane().add(show); frame.getContentPane().add(get); frame.pack(); frame.setVisible(true); } }
true
83e14efec4aa27410d17de027b6846d4f4333451
Java
viktorsamame/TrabajoFinalPrograWeb
/src/main/java/pe/org/incatrek/repository/IGuiaRepository.java
UTF-8
654
1.984375
2
[]
no_license
package pe.org.incatrek.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import pe.org.incatrek.model.Guia; @Repository public interface IGuiaRepository extends JpaRepository<Guia, Integer>{ @Query("from Guia g where g.nombreGuia like %:nombreGuia%") List<Guia> buscarPorNombre(@Param("nombreGuia") String nombreGuia); @Query("from Guia g where g.dniGuia like %:dniGuia%") List<Guia> buscarPorDNI(@Param("dniGuia") String dniGuia); }
true
cdf9479025d186a16a476e14d10413e5d81f4af3
Java
liyuhan30/pet-hospital
/src/main/Java/com/chatRobot/controller/resourceController.java
UTF-8
1,545
1.625
2
[]
no_license
package com.chatRobot.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller @RequestMapping("/doc") public class resourceController { @RequestMapping(value = "/framework", method = RequestMethod.GET) public String framework() { return "framework"; } @RequestMapping(value = "/parameter_trans", method = RequestMethod.GET) public String parameter_trans() { return "parameter_trans"; } @RequestMapping(value = "/parameter_trans2", method = RequestMethod.GET) public String parameter_trans2() { return "parameter_trans2"; } @RequestMapping(value = "/deploy", method = RequestMethod.GET) public String deploy() { return "deploy"; } @RequestMapping(value = "/deploy2", method = RequestMethod.GET) public String deploy2() { return "deploy2"; } @RequestMapping(value = "/3d", method = RequestMethod.GET) public String dd() { return "3D"; } @RequestMapping(value = "/3D", method = RequestMethod.GET) public String dd2() { return "3D"; } @RequestMapping(value = "/performance", method = RequestMethod.GET) public String performance() { return "performance"; } @RequestMapping(value = "/fileUpload", method = RequestMethod.GET) public String fileUpload() { return "fileUpload"; } }
true
4167cc38228dabb774bf0cc46194405ececf9563
Java
atomixgame/atom-game-framework-sdk
/AtomSuiteModules/GUISuite/NiftyVisualEditor/jme3-gui/src/com/jme3/gde/gui/nbeditor/controller/ElementEditor.java
UTF-8
2,670
2.4375
2
[]
no_license
/* Copyright 2012 Aguzzi Cristiano 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.jme3.gde.gui.nbeditor.controller; import com.jme3.gde.gui.base.model.GUITypes; import com.jme3.gde.gui.base.model.elements.GElement; import de.lessvoid.nifty.elements.Element; /** * * @author cris */ public class ElementEditor { public static int DEFAULT_SIZE_X = 100; public static int DEFAULT_SIZE_Y = 50; private GElement selected; public ElementEditor(GElement toEdit) { selected = toEdit; } public ElementEditor setAttribute(String key, String value) { if (selected != null) { selected.addAttribute(key, value); selected.refresh(); } return this; } public ElementEditor removeAttribute(String key) { if (selected != null) { selected.removeAttribute(key); selected.refresh(); } return this; } public void normalizeSize() { Element parent = selected.getParent().getNiftyElement(); Element sel = selected.getNiftyElement(); float width = (float) sel.getWidth() / parent.getWidth(); float height = (float) sel.getHeight() / parent.getHeight(); int percW = (int) (width * 100); int percH = (int) (height * 100); selected.addAttribute("width", "" + percW + "%"); selected.addAttribute("height", "" + percH + "%"); selected.lightRefresh(); } public void setEdited(GElement toEdit) { selected = toEdit; } public void setVisibile(boolean visibility) { selected.getNiftyElement().setVisible(visibility); } public int getIndex() { return selected.getParent().getElements().indexOf(selected); } public void setVisibileSelected(boolean vis) { if (!this.selected.getType().equals(GUITypes.SCREEN)) { if (vis) { this.selected.getNiftyElement().showWithoutEffects(); } else { this.selected.getNiftyElement().hideWithoutEffect(); } } } public Element getNiftyElement() { return selected.getNiftyElement(); } }
true
2c733b40d54e0da804c98bb993fabfed90763f59
Java
alabs/edx-app-android
/android/source/VideoLocker/src/org/edx/mobile/social/SocialFactory.java
UTF-8
987
2.375
2
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
package org.edx.mobile.social; import android.app.Activity; import org.edx.mobile.social.facebook.FacebookAuth; import org.edx.mobile.social.google.GoogleOauth2; import org.edx.mobile.util.Config; public class SocialFactory { public static final int TYPE_GOOGLE = 100; public static final int TYPE_FACEBOOK = 101; public static ISocial getInstance(Activity activity, int type) { if (type == TYPE_GOOGLE) { if (Config.getInstance().getThirdPartyTraffic().isGoogleEnabled()) { return new GoogleOauth2(activity); } else { return new ISocialEmptyImpl(); } } else if (type == TYPE_FACEBOOK) { if (Config.getInstance().getThirdPartyTraffic().isFacebookEnabled()) { return new FacebookAuth(activity); } else { return new ISocialEmptyImpl(); } } return null; } }
true
59ba6f07d7a0d53eeef838e3ef686e0b1e326784
Java
srinathalla/java
/algo/src/main/java/com/sri/algo/tree/HieghtOfBinaryTree.java
UTF-8
1,406
3.59375
4
[]
no_license
package com.sri.algo.tree; import java.util.Scanner; public class HieghtOfBinaryTree { public static int height(Node node) { if (node == null) { return 0; } return 1 + Integer.max(height(node.left), height(node.right)); } public static void main(String[] args) { /*BinaryTree binaryTree = new BinaryTree(10); binaryTree.insertLeft(10, 20); binaryTree.insertRight(10, 30); // binaryTree.insertLeft(20, 40); binaryTree.insertRight(20, 60); binaryTree.insertLeft(30, 70); binaryTree.insertRight(70, 80); System.out.println(height(binaryTree.getRoot()));*/ try (Scanner in = new Scanner(System.in)) { int tests = in.nextInt(); BinaryTree binaryTree = null; for (int test = 0; test < tests; test++) { int edges = in.nextInt(); for (int i = 0; i < edges; i++) { int node = in.nextInt(); int child = in.nextInt(); String op = in.next(); if (binaryTree == null) { binaryTree = new BinaryTree(node); } if (op.equals("L")) { binaryTree.insertLeft(node, child); } else if (op.equals("R")) { binaryTree.insertRight(node, child); } } System.out.println(); //System.out.println(binaryTree.printCornerNodes()); System.out.println(height(binaryTree.root)); binaryTree = null; } } } }
true
2ef2b05fffd25d6e47cb9dd4f5ee12fbcece12fb
Java
pinyingiriswu/leetcode2
/1-Linked Lists/d6/d6_430_flatten_a_multilevel_doubly_linked_list.java
UTF-8
1,441
3.359375
3
[]
no_license
public class d6_430_flatten_a_multilevel_doubly_linked_list { /** // Definition for a Node. class Node { public int val; public Node prev; public Node next; public Node child; public Node() {} public Node(int _val,Node _prev,Node _next,Node _child) { val = _val; prev = _prev; next = _next; child = _child; } }; */ /** References: * https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/discuss/311772/Java-recursive-solution-(0ms-36.7MB)-with-comments-O(n)-time-complexity-O(n)-space * https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/discuss/318235/Java-Recursive-Solution*/ public Node flatten(Node head) { Node cur = head; while (head != null) { if (head.child != null) { Node childNode = flatten(head.child); Node nextNode = head.next; head.next = childNode; childNode.prev = head; head.child = null; while (childNode.next != null) { childNode = childNode.next; } childNode.next = nextNode; if (nextNode != null) { nextNode.prev = childNode; } } head = head.next; } return cur; } }
true
0aac9f98bf9d2eb5cd027d4516ceacc90a5ecb0a
Java
damiankarwacki/swimingFacilities
/src/main/java/com/sport/SportFacilities/repositories/LessonRepository.java
UTF-8
1,083
2.15625
2
[]
no_license
package com.sport.SportFacilities.repositories; import com.sport.SportFacilities.models.*; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import java.time.LocalDate; import java.util.Optional; import java.util.Set; @Repository public interface LessonRepository extends CrudRepository<Lesson, Integer> { // TODO Krzychu testy @Query("SELECT l FROM Lesson l JOIN LessonDetail d ON l.lessonDetail = d WHERE d.lessonType = :lessonType") Optional<Set<Lesson>> findAllByLessonType(@Param("lessonType") LessonType lessonType); Optional<Set<Lesson>> findAllByOrderDate(LocalDate orderDate); // TODO Damian testy @Query("SELECT l FROM Lesson l JOIN SwimmingPool s ON l.swimmingPool = s WHERE s.sportObject = :sportObject") Optional<Set<Lesson>> findAllBySportObject(@Param("sportObject") SportObject sportObject); Optional<Set<Lesson>> findAllByInstructor(Instructor instructor); }
true
e0987965f669162a3028b9cc8b3a1c5a004c6180
Java
abdulkarim8293/Tour-Mate
/app/src/main/java/com/abdulkarim/tourmate/activities/SignUpActivity.java
UTF-8
5,351
1.914063
2
[]
no_license
package com.abdulkarim.tourmate.activities; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.databinding.DataBindingUtil; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.view.View; import android.widget.CompoundButton; import android.widget.Toast; import com.abdulkarim.tourmate.R; import com.abdulkarim.tourmate.databinding.ActivitySignUpBinding; import com.abdulkarim.tourmate.model.ResponseBody; import com.abdulkarim.tourmate.retrofit.ApiService; import com.abdulkarim.tourmate.retrofit.RetrofitInstance; import retrofit2.Call; import retrofit2.Callback; public class SignUpActivity extends AppCompatActivity { private ActivitySignUpBinding binding; private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION; private static final String COURSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION; private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = DataBindingUtil.setContentView(this,R.layout.activity_sign_up); getLocationPermission(); binding.nextBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { binding.nextBtn.setVisibility(View.GONE); binding.progressBar.setVisibility(View.VISIBLE); String mobileNumber = binding.phoneNumberEtID.getText().toString(); if (!mobileNumber.isEmpty() && mobileNumber.matches("01[0-9]{9}")) { checkNumber(mobileNumber); } else { binding.phoneNumberEtID.setError("Enter your valid phone number"); binding.phoneNumberEtID.requestFocus(); binding.progressBar.setVisibility(View.GONE); binding.nextBtn.setVisibility(View.VISIBLE); } } }); binding.termsAndConditionCBID.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked==true){ binding.nextBtn.setEnabled(true); binding.nextBtn.setBackground(getResources().getDrawable(R.drawable.all_side_border)); }else if (isChecked==false){ binding.nextBtn.setEnabled(false); binding.nextBtn.setBackground(getResources().getDrawable(R.drawable.all_side_border_gray)); } } }); binding.loginTV.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(SignUpActivity.this,LoginActivity.class)); } }); } private void checkNumber(final String mobileNumber) { ApiService retrofitInstance = RetrofitInstance.getRetrofitInstance().create(ApiService.class); Call<ResponseBody> call = retrofitInstance.matchNumber(mobileNumber); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) { if (response.body().isStatus()==true){ binding.nextBtn.setVisibility(View.VISIBLE); binding.progressBar.setVisibility(View.GONE); Toast.makeText(SignUpActivity.this, response.body().getMessage(), Toast.LENGTH_LONG).show(); }else { binding.nextBtn.setVisibility(View.VISIBLE); binding.progressBar.setVisibility(View.GONE); startNextActivity(mobileNumber); } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { } }); } private void startNextActivity(String mobileNumber) { startActivity(new Intent(SignUpActivity.this,VerifyNumberActivity.class) .putExtra("mobileNumber",mobileNumber)); } private void getLocationPermission() { String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (ContextCompat.checkSelfPermission(this, FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { if (ContextCompat.checkSelfPermission(this, COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { } else { ActivityCompat.requestPermissions(this, permissions, LOCATION_PERMISSION_REQUEST_CODE); } } else { ActivityCompat.requestPermissions(this, permissions, LOCATION_PERMISSION_REQUEST_CODE); } } } }
true
4327848fe323845beb45f01221498b713ac4ee95
Java
issteam32/questboard
/demo.spring.rx/src/main/java/task/repository/TodoRepository.java
UTF-8
284
1.539063
2
[]
no_license
package task.repository; import org.springframework.data.repository.reactive.ReactiveCrudRepository; import org.springframework.stereotype.Repository; import task.entity.TodoEntity; @Repository public interface TodoRepository extends ReactiveCrudRepository<TodoEntity, Integer> { }
true
4a4066e83ff8e07e8bed968e43299e6813a6ff57
Java
zhangnanw/m2o
/src/main/java/com/bryer/m2o/config/SessionConfig.java
UTF-8
1,169
2.203125
2
[]
no_license
package com.bryer.m2o.config; import cn.hutool.db.Session; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.sql.DataSource; /** * @author zhangnan@yansou.org */ @Configuration public class SessionConfig { private final DataSource localMysqlDataSource; private final DataSource localOracleDataSource; public SessionConfig(@Qualifier("localMysqlDataSource") DataSource localMysqlDataSource,@Qualifier("localOracleDataSource") DataSource localOracleDataSource) { this.localMysqlDataSource = localMysqlDataSource; this.localOracleDataSource = localOracleDataSource; } @Bean @Qualifier("localMysqlSession") Session localMysqlSession() { System.out.println("源会话:" + localMysqlDataSource); return Session.create(localMysqlDataSource); } @Bean @Qualifier("localOracleSession") Session localOracleSession() { System.out.println("目标会话:" + localOracleDataSource); return new Session(localOracleDataSource,new MyOracleDialect()); } }
true
b7bd0685710c12a081c2123cf249274730952559
Java
ljk761626336/dora
/dora-mvvm/src/main/java/dora/db/type/DataType.java
UTF-8
636
2.3125
2
[ "Apache-2.0" ]
permissive
package dora.db.type; import dora.db.DataMatcher; public enum DataType { STRING(StringType.getInstance()), BOOLEAN(BooleanType.getInstance()), CHAR(CharType.getInstance()), BYTE(ByteType.getInstance()), SHORT(ShortType.getInstance()), INT(IntType.getInstance()), LONG(LongType.getInstance()), FLOAT(FloatType.getInstance()), DOUBLE(DoubleType.getInstance()), OTHER(ByteArrayType.getInstance()); private final DataMatcher mMatcher; /* package */ DataType(DataMatcher matcher) { mMatcher = matcher; } public DataMatcher getMatcher() { return mMatcher; } }
true
aa069f0bfcb1b12f9b5874c58926e4c7ca12637b
Java
VictorRChagas/felix-common
/src/test/java/com/felix/common/date/DatesTest.java
UTF-8
8,694
2.828125
3
[]
no_license
package com.felix.common.date; import org.junit.jupiter.api.Test; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.util.Collections; import java.util.Date; import java.util.List; import static com.felix.common.date.Dates.*; import static org.hamcrest.CoreMatchers.hasItems; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; public class DatesTest { private Date specificDate = of(2019, 12, 18, 19, 25, 11); private LocalDate specificLocalDate = LocalDate.of(2019, 12, 18); private LocalDateTime specificLocalDateTime = LocalDateTime.of(2019, 12, 18, 19, 25, 11); @Test void ofDateTest() { Date date = of(2019, 12, 18); assertDate(date); } @Test void toDateTest() { Date date = Dates.toDate(specificLocalDate); assertDate(date); assertThrows(NullPointerException.class, () -> Dates.toDate((LocalDate) null)); } private void assertDate(Date date) { assertEquals(18, getDayOfMonth(date)); assertEquals(12, getMonth(date)); assertEquals(2019, getYear(date)); } @Test void getDayOfMonthTest() { assertEquals(18, getDayOfMonth(specificDate)); assertThrows(NullPointerException.class, () -> getDayOfMonth(null)); } @Test void getMonthTest() { assertEquals(12, getMonth(specificDate)); assertThrows(NullPointerException.class, () -> getMonth(null)); } @Test void getYearTest() { assertEquals(2019, getYear(specificDate)); assertThrows(NullPointerException.class, () -> getYear(null)); } @Test void toLocalDateTest() { assertLocalDate(toLocalDate(specificDate)); } private void assertLocalDate(LocalDate localDate) { assertEquals(18, localDate.getDayOfMonth()); assertEquals(12, localDate.getMonthValue()); assertEquals(2019, localDate.getYear()); } @Test void toLocalDateTimeTest() { LocalDateTime localDateTime = toLocalDateTime(specificDate); assertLocalDate(localDateTime.toLocalDate()); assertEquals(19, localDateTime.getHour()); assertEquals(25, localDateTime.getMinute()); assertEquals(11, localDateTime.getSecond()); } @Test void formatWithDateTest() { assertEquals("18/12/2019", format(specificDate, "dd/MM/yyyy")); assertThrows(NullPointerException.class, () -> format((Date) null, "dd/MM/yyyy"), "Date is null."); assertThrows(NullPointerException.class, () -> format(specificDate, null), "Format is null."); } @Test void formatWithLocalDateTest() { assertEquals("18/12/2019", format(specificLocalDate, "dd/MM/yyyy")); assertThrows(NullPointerException.class, () -> format((Date) null, "dd/MM/yyyy"), "Date is null."); assertThrows(NullPointerException.class, () -> format(specificLocalDate, null), "Format is null."); } @Test void formatWithLocalDateTimeTest() { assertEquals("18/12/2019 19:25:11", format(specificLocalDateTime, "dd/MM/yyyy HH:mm:ss")); assertThrows(NullPointerException.class, () -> format((Date) null, "dd/MM/yyyy"), "Date is null."); assertThrows(NullPointerException.class, () -> format(specificLocalDateTime, null), "Format is null."); } @Test void parseDateTest() { assertEquals(specificDate, parseDate("2019-12-18 19:25:11", "yyyy-MM-dd HH:mm:ss")); assertThrows(IllegalArgumentException.class, () -> parseDate("2019/12/18 19:25:11", "yyyy-MM-dd HH:mm:ss"), "Invalid format."); assertThrows(NullPointerException.class, () -> parseDate(null, "yyyy/MM/dd HH:mm:ss"), "Date is null."); assertThrows(NullPointerException.class, () -> parseDate("2019-12-18 19:25:11", null), "Format is null."); } @Test void getIntervalWithLocalDateDayTest() { List<LocalDate> dates = getInterval(specificLocalDate, specificLocalDate.plusDays(10), ChronoUnit.DAYS); assertEquals(11, dates.size()); assertThat(getInterval(specificLocalDate, specificLocalDate, ChronoUnit.DAYS), is(Collections.singletonList(specificLocalDate))); assertThrows(NullPointerException.class, () -> getInterval(null, specificLocalDate.plusDays(1), ChronoUnit.DAYS), "Start date is null."); assertThrows(NullPointerException.class, () -> getInterval(specificLocalDate, null, ChronoUnit.DAYS), "End date is null."); assertThrows(NullPointerException.class, () -> getInterval(specificLocalDate, specificLocalDate.plusDays(1), null), "ChronoUnit is null."); assertThrows(IllegalArgumentException.class, () -> getInterval(specificLocalDate, specificLocalDate.minusDays(1), ChronoUnit.DAYS), "Start date is after end date."); } @Test void getIntervalWithLocalDateMonthTest() { List<LocalDate> dates = getInterval(LocalDate.of(2019, 1, 1), LocalDate.of(2019, 12, 1), ChronoUnit.MONTHS); assertEquals(12, dates.size()); assertThat(dates, hasItems(LocalDate.of(2019, 10, 1), LocalDate.of(2019, 9, 1))); dates = getInterval(LocalDate.of(2018, 1, 1), LocalDate.of(2019, 12, 1), ChronoUnit.MONTHS); assertEquals(24, dates.size()); assertThat(dates, hasItems(LocalDate.of(2018, 10, 1), LocalDate.of(2019, 9, 1))); } @Test void getIntervalWithLocalDateYearTest() { List<LocalDate> dates = getInterval(LocalDate.of(2000, 1, 1), LocalDate.of(2019, 12, 1), ChronoUnit.YEARS); assertEquals(20, dates.size()); assertThat(dates, hasItems(LocalDate.of(2015, 1, 1), LocalDate.of(2019, 1, 1))); } @Test void getIntervalWithLocalDateTimeHourTest() { List<LocalDateTime> dates = getInterval(specificLocalDateTime, specificLocalDateTime.plusHours(24), ChronoUnit.HOURS); assertEquals(25, dates.size()); assertThat(getInterval(specificLocalDateTime, specificLocalDateTime, ChronoUnit.HOURS), is(Collections.singletonList(specificLocalDateTime))); assertThrows(NullPointerException.class, () -> getInterval(null, specificLocalDateTime.plusDays(1), ChronoUnit.HOURS), "Start date is null."); assertThrows(NullPointerException.class, () -> getInterval(specificLocalDateTime, null, ChronoUnit.HOURS), "End date is null."); assertThrows(NullPointerException.class, () -> getInterval(specificLocalDateTime, specificLocalDateTime.plusDays(1), null), "ChronoUnit is null."); assertThrows(IllegalArgumentException.class, () -> getInterval(specificLocalDateTime, specificLocalDateTime.minusDays(1), ChronoUnit.HOURS), "Start date is after end date."); } @Test void getPeriodWithLocalDateTest() { assertEquals(30, getPeriod(specificLocalDate, specificLocalDate.plusDays(30), ChronoUnit.DAYS)); assertEquals(30, getPeriod(specificLocalDate, specificLocalDate.plusMonths(30), ChronoUnit.MONTHS)); assertEquals(30, getPeriod(specificLocalDate, specificLocalDate.plusYears(30), ChronoUnit.YEARS)); assertThrows(NullPointerException.class, () -> getPeriod(null, specificLocalDate, ChronoUnit.DAYS), "Start date is null."); assertThrows(NullPointerException.class, () -> getPeriod(specificLocalDate, null, ChronoUnit.DAYS), "End date is null."); assertThrows(NullPointerException.class, () -> getPeriod(null, specificLocalDate, null), "ChronoUnit is null."); } @Test void getPeriodWithLocalDateTimeTest() { assertEquals(30, getPeriod(specificLocalDateTime, specificLocalDateTime.plusDays(30), ChronoUnit.DAYS)); assertEquals(30, getPeriod(specificLocalDateTime, specificLocalDateTime.plusHours(30), ChronoUnit.HOURS)); assertEquals(30, getPeriod(specificLocalDateTime, specificLocalDateTime.plusMinutes(30), ChronoUnit.MINUTES)); assertEquals(30, getPeriod(specificLocalDateTime, specificLocalDateTime.plusSeconds(30), ChronoUnit.SECONDS)); assertThrows(NullPointerException.class, () -> getPeriod(null, specificLocalDate, ChronoUnit.DAYS), "Start date is null."); assertThrows(NullPointerException.class, () -> getPeriod(specificLocalDate, null, ChronoUnit.DAYS), "End date is null."); assertThrows(NullPointerException.class, () -> getPeriod(null, specificLocalDate, null), "ChronoUnit is null."); } }
true
bba1aa166dc748c850edab296c8ed13d608cf1be
Java
haudp2998/BT_Java
/CuoiKyJava2.java
UTF-8
1,869
3.0625
3
[]
no_license
import java.awt.*; import javax.swing.JOptionPane; import java.awt.event.*; class CuoiKyJava2 extends Frame implements ItemListener, ActionListener { private List lt; private Label lb; private TextArea ta; private Button bt; String pl[] = {"Programming With Java","Image Processing", "PHP", "C#", "C/C++ Programming Language", "F#", "Python in Fuzzy Control", "Ruby", "Go", "Pascal", "Perl"}; private void initialize(){ lt = new List(pl.length/2,true); bt = new Button ("Close"); ta = new TextArea(); lb = new Label("DS"); ta.setBounds(10, 207, 293, 157); lt.setBounds(10, 50, 293, 120); lb.setBounds(39, 175, 235, 22); bt.setBounds(109, 388, 70, 22); setBounds(100, 100, 330, 430); setLocation (300,100); setTitle("DK"); setLayout (null ); addWindowListener( new ClassExit() ); //lt.setMultipleSelections(true); lt.setMultipleMode(true); add(lt); add(lb ); add(ta); add(bt); lt.addItemListener(this); bt.addActionListener(this); for( String s: pl) lt.add(s); } public CuoiKyJava2(){ initialize(); setVisible(true); } public void itemStateChanged (ItemEvent e){ String[] item = lt.getSelectedItems(); String tmp=""; for(int i=0;i< item.length; i ++) { tmp = tmp + item[i] + "\n" ; } ta.setText( tmp ); } public void actionPerformed (ActionEvent e){ if( e.getSource() == bt ){ int kq=JOptionPane.showConfirmDialog(null, "Ban Co ?","Thong Bao",JOptionPane.YES_NO_OPTION); if(kq==0) { System.exit(0); } } //System.exit(1); } public class ClassExit extends WindowAdapter { public void windowClosing ( WindowEvent e) { int kq=JOptionPane.showConfirmDialog(null, "Ban Co ?","Thong Bao",JOptionPane.YES_NO_OPTION); if(kq==0) { System.exit(0); } //System.exit(0); } } public static void main(String[] args){ new CuoiKyJava2(); } }
true
12219197e42ece1b0e1e73fc2efb5ac901c2db62
Java
hortonworks/cloudbreak
/template-manager-core/src/main/java/com/sequenceiq/cloudbreak/template/processor/kerberos/KerberosDescriptorService.java
UTF-8
928
1.976563
2
[ "LicenseRef-scancode-warranty-disclaimer", "ANTLR-PD", "CDDL-1.0", "bzip2-1.0.6", "Zlib", "BSD-3-Clause", "MIT", "EPL-1.0", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-jdbm-1.00", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package com.sequenceiq.cloudbreak.template.processor.kerberos; import java.util.HashMap; import java.util.Map; public class KerberosDescriptorService { private String name; private Map<String, KerberosServiceConfiguration> configurations; public KerberosDescriptorService(String name) { this(name, new HashMap<>()); } public KerberosDescriptorService(String name, Map<String, KerberosServiceConfiguration> configurations) { this.name = name; this.configurations = configurations; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Map<String, KerberosServiceConfiguration> getConfigurations() { return configurations; } public void setConfigurations(Map<String, KerberosServiceConfiguration> configurations) { this.configurations = configurations; } }
true
35506cd19568a31369441f270970dd268d47aad9
Java
lxj0122/spring4
/springgrammer/src/main/java/com/spring/event/DemoEvent.java
UTF-8
515
2.0625
2
[]
no_license
package com.spring.event; import org.springframework.context.ApplicationEvent; /** * Created by IntelliJ IDEA. * User: lxj * Date: 2018/6/13 * Time: 14:37 */ public class DemoEvent extends ApplicationEvent { private static final long serialVersionUID=1; private String msg; public DemoEvent(Object source,String msg) { super(source); this.msg=msg; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
true
e03e0eb2d61bd5e6b67df417889a786d95c51c46
Java
if414029/cashier-system
/src/main/java/com/amos/chasiersystem/service/entity/DistributorResponse.java
UTF-8
293
1.671875
2
[]
no_license
package com.amos.chasiersystem.service.entity; import lombok.Getter; import lombok.Setter; @Getter @Setter public class DistributorResponse extends ServiceResponse { private int distributorId; private String distributorName; private String noPhone; private String address; }
true
36535e61ff5b05730d5778208e0a8f4662f33070
Java
osmanyaycioglu/ykb8
/JavaTrain/src/com/ykb/java/ws/MyWebService.java
UTF-8
164
1.8125
2
[]
no_license
package com.ykb.java.ws; import javax.jws.WebService; @WebService public class MyWebService { public String hello() { return "hello world"; } }
true
18cfa3a6f4807fedd3816405fe1973c5518af4d9
Java
SpaaaaceMan/Finley
/src/items/weapons/meles/MeleWeapon.java
UTF-8
1,292
3.21875
3
[]
no_license
package items.weapons.meles; import items.weapons.Weapon; import java.awt.Color; import javax.swing.ImageIcon; import characters.Actor; public class MeleWeapon extends Weapon { public MeleWeapon(String name, int damage, double weight, int placeOccupiedInventory, double value, int durability, ImageIcon icon) { super(name, damage, weight, placeOccupiedInventory, value, durability, icon); } public MeleWeapon (MeleWeapon weapon) { super(weapon.getName(), weapon.getDamage(), weapon.getWeight(), weapon.getPlaceOccupiedInventory(), weapon.getValue(), weapon.getDurability(), weapon.getIcon()); } @Override public Color getItemColor() { return Color.GREEN; } @Override public void attack(Actor targetedCharacter) { if (this.getDurability() <= 0) { System.out.println("Your " + this.getName() + " is broken. Too bad."); } else { System.out.println(targetedCharacter.getName() + " has been attacked by a "+ this.getName() + " for " + this.getDamage() + " damage."); targetedCharacter.looseLife(this.getDamage()); this.setDurability(this.getDurability() - 1); if (this.getDurability() <= 0) { System.out.println("Your " + this.getName() + " has broken. Toooo baaaaaaaad."); } } }//attack() }
true
5fb7d17884b01d1c4b327cbf0f740a11e60af2fe
Java
sworx11/communityForum
/src/wt/controller/SearchServlet.java
UTF-8
765
2.21875
2
[]
no_license
package wt.controller; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class SearchServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req,resp); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String searchContent = new String(request.getParameter("search").getBytes("ISO-8859-1"),"UTF-8"); String realUrl = "https://cn.bing.com/search?q=" + searchContent; response.sendRedirect(realUrl); } }
true
5f98a4298824cacaf728fe52dad95911703f7f43
Java
bburdick-code/furniture-donations
/src/main/java/org/hospitalityprogram/furnituredonations/data/ItemCategoryRepository.java
UTF-8
340
1.71875
2
[ "MIT" ]
permissive
package org.hospitalityprogram.furnituredonations.data; import org.hospitalityprogram.furnituredonations.models.ItemCategory; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface ItemCategoryRepository extends CrudRepository<ItemCategory, Integer> { }
true
9e29c8d85e5ccaaada37d13727c14a5a04553df6
Java
jeff4wlu/netty
/java-nio/src/main/java/SimpleHandlerInitializer.java
UTF-8
448
2.109375
2
[]
no_license
import io.netty.channel.ChannelInitializer; import io.netty.channel.socket.SocketChannel; /** * @author Lu Weijian * @description 备注 * @email lwj@kapark.cn * @date 2019-03-05 19:46 */ public class SimpleHandlerInitializer extends ChannelInitializer<SocketChannel> { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { socketChannel.pipeline() .addLast(new SimpleHandler()); } }
true
577981a5780def2d5090e3630331df29bc5ffdf8
Java
atsuibeijing/Telerik_UI_for_Android_2016_2_504
/controls/Chart/src/main/java/com/telerik/widget/chart/visualization/cartesianChart/CartesianChartGrid.java
UTF-8
24,311
1.921875
2
[]
no_license
package com.telerik.widget.chart.visualization.cartesianChart; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.DashPathEffect; import android.graphics.Paint; import android.graphics.Path; import com.telerik.android.common.CollectionChangeListener; import com.telerik.android.common.CollectionChangedEvent; import com.telerik.android.common.ObservableCollection; import com.telerik.android.common.DependencyPropertyChangedListener; import com.telerik.android.common.Util; import com.telerik.android.common.math.RadPoint; import com.telerik.android.common.math.RadRect; import com.telerik.widget.chart.engine.axes.AxisTickModel; import com.telerik.widget.chart.engine.axes.TickPosition; import com.telerik.widget.chart.engine.chartAreas.ChartAreaModelWithAxes; import com.telerik.widget.chart.engine.decorations.CartesianChartGridModel; import com.telerik.widget.chart.engine.decorations.GridLine; import com.telerik.widget.chart.engine.decorations.GridStripe; import com.telerik.widget.chart.engine.elementTree.ChartElement; import com.telerik.widget.chart.visualization.common.Axis; import com.telerik.widget.chart.visualization.common.ChartElementPresenter; import com.telerik.widget.chart.visualization.common.RadChartViewBase; import com.telerik.widget.palettes.ChartPalette; import com.telerik.widget.palettes.PaletteEntry; import com.telerik.widget.palettes.PaletteEntryCollection; import java.util.ArrayList; /** * Represents a decoration over the plot area of {@link RadCartesianChartView}. Adds major and minor lines, connected to each Major and Minor tick of each axis. */ public class CartesianChartGrid extends ChartElementPresenter { public static final int MAJOR_LINES_THICKNESS_PROPERTY_KEY = registerProperty(2.0f, new DependencyPropertyChangedListener() { @Override public void onPropertyChanged(Object sender, int propertyType, Object propertyValue) { CartesianChartGrid grid = (CartesianChartGrid)sender; float lineThickness = (Float)propertyValue; if (lineThickness <= 0) throw new IllegalArgumentException("lineThickness cannot be negative or zero"); grid.linePaint.setStrokeWidth(lineThickness); } }); public static final int MAJOR_LINES_VISIBILITY_PROPERTY_KEY = registerProperty(GridLineVisibility.NONE, new DependencyPropertyChangedListener() { @Override public void onPropertyChanged(Object sender, int propertyType, Object propertyValue) { CartesianChartGrid grid = (CartesianChartGrid)sender; int value = (int)propertyValue; if (grid.majorLinesVisibilityCache == value) { return; } grid.majorLinesVisibilityCache = value; grid.onMajorLinesVisibilityChanged(); } }); public static final int STRIP_LINES_VISIBILITY_PROPERTY_KEY = registerProperty(GridLineVisibility.NONE, new DependencyPropertyChangedListener() { @Override public void onPropertyChanged(Object sender, int propertyType, Object propertyValue) { CartesianChartGrid grid = (CartesianChartGrid)sender; int value = (int)propertyValue; if (grid.stripLinesVisibility == value) { return; } grid.stripLinesVisibility = value; grid.requestRender(); } }); public static final int LINE_COLOR_PROPERTY_KEY = registerProperty(Color.BLACK, new DependencyPropertyChangedListener() { @Override public void onPropertyChanged(Object sender, int propertyType, Object propertyValue) { CartesianChartGrid grid = (CartesianChartGrid)sender; grid.linePaint.setColor((int) propertyValue); } }); public static final int VERTICAL_LINE_COLOR_PROPERTY_KEY = registerProperty(Color.BLACK, new DependencyPropertyChangedListener() { @Override public void onPropertyChanged(Object sender, int propertyType, Object propertyValue) { CartesianChartGrid grid = (CartesianChartGrid)sender; grid.verticalLinePaint.setColor((int)propertyValue); } }); public static final int MAJOR_X_LINE_DASH_ARRAY_PROPERTY_KEY = registerProperty(null, new DependencyPropertyChangedListener() { @Override public void onPropertyChanged(Object sender, int propertyType, Object propertyValue) { CartesianChartGrid grid = (CartesianChartGrid)sender; float[] value = (float[])propertyValue; if (grid.majorXLines.dashArray == value) { return; } grid.majorXLines.dashArray = value; grid.onMajorXLineDashArrayChanged(value); } }); public static final int MAJOR_Y_LINE_DASH_ARRAY_PROPERTY_KEY = registerProperty(null, new DependencyPropertyChangedListener() { @Override public void onPropertyChanged(Object sender, int propertyType, Object propertyValue) { CartesianChartGrid grid = (CartesianChartGrid)sender; float[] value = (float[])propertyValue; if (grid.majorYLines.dashArray == value) { return; } grid.majorYLines.dashArray = value; grid.onMajorYLineDashArrayChanged(value); } }); public static final int MAJOR_X_LINE_RENDER_MODE_PROPERTY_KEY = registerProperty(GridLineRenderMode.ALL, new DependencyPropertyChangedListener() { @Override public void onPropertyChanged(Object sender, int propertyType, Object propertyValue) { CartesianChartGrid grid = (CartesianChartGrid)sender; int value = (int)propertyValue; if (value == grid.majorXLines.renderMode) { return; } grid.majorXLines.renderMode = value; grid.requestRender(); } }); public static final int MAJOR_Y_LINE_RENDER_MODE_PROPERTY_KEY = registerProperty(GridLineRenderMode.ALL, new DependencyPropertyChangedListener() { @Override public void onPropertyChanged(Object sender, int propertyType, Object propertyValue) { CartesianChartGrid grid = (CartesianChartGrid)sender; int value = (int)propertyValue; if (value == grid.majorYLines.renderMode) { return; } grid.majorYLines.renderMode = value; grid.requestRender(); } }); private static final String MAJOR_LINES_VISIBILITY_KEY = "MajorLinesVisibility"; private static final String MAJOR_LINES_THICKNESS_KEY = "MajorLinesThickness"; private static final String MAJOR_X_LINE_DASH_ARRAY_KEY = "MajorXLineDashArray"; private static final String MAJOR_Y_LINE_DASH_ARRAY_KEY = "MajorYLineDashArray"; private static final String MAJOR_X_LINE_RENDER_MODE_KEY = "MajorXLineRenderMode"; private static final String MAJOR_Y_LINE_RENDER_MODE_KEY = "MajorYLineRenderMode"; private static final String STRIP_LINES_VISIBILITY_KEY = "StripLinesVisibility"; public CartesianChartGridModel grid; private Paint emptyPaint = new Paint(); private Paint emptyPaintSecondary = new Paint(); private Paint linePaint = new Paint(); private Paint verticalLinePaint = new Paint(); private int majorLinesVisibilityCache; private int stripLinesVisibility; private GridLinesInfo majorXLines; private GridLinesInfo majorYLines; private ObservableCollection<Paint> xStripeBrushes; private ObservableCollection<Paint> yStripeBrushes; /** * Initializes a new instance of the {@link CartesianChartGrid} class. */ public CartesianChartGrid() { this.grid = new CartesianChartGridModel(); emptyPaint.setColor(Color.TRANSPARENT); emptyPaintSecondary.setColor(0xffe3e3e3); this.majorXLines = new GridLinesInfo(this); this.majorYLines = new GridLinesInfo(this); this.majorXLines.lines = this.grid.xLines; this.majorYLines.lines = this.grid.yLines; this.xStripeBrushes = new ObservableCollection<Paint>(); this.xStripeBrushes.addCollectionChangeListener(new CollectionChangeListener<Paint>() { @Override public void collectionChanged(CollectionChangedEvent info) { onXStripeStylesChanged(); } }); this.yStripeBrushes = new ObservableCollection<Paint>(); this.yStripeBrushes.addCollectionChangeListener(new CollectionChangeListener<Paint>() { @Override public void collectionChanged(CollectionChangedEvent info) { onYStripeStylesChanged(); } }); this.linePaint.setStyle(Paint.Style.STROKE); this.linePaint.setColor(Color.GRAY); this.linePaint.setStrokeWidth(1); this.verticalLinePaint.setStyle(Paint.Style.STROKE); this.verticalLinePaint.setColor(Color.GRAY); this.verticalLinePaint.setStrokeWidth(1); this.majorXLines.linePaint = this.verticalLinePaint; this.majorYLines.linePaint = this.linePaint; this.setMajorLinesVisibility(GridLineVisibility.Y); } public void setHorizontalAxis(Axis axis) { this.grid.setPrimaryAxis(axis.getModel()); } public void setVerticalAxis(Axis axis) { this.grid.setSecondaryAxis(axis.getModel()); } /** * Gets the color of the grid lines. * * @return The color of the grid lines. */ public int getLineColor() { return (int)this.getValue(LINE_COLOR_PROPERTY_KEY); } /** * Sets the line color of the grid lines. * * @param color The new line color. */ public void setLineColor(int color) { this.setValue(LINE_COLOR_PROPERTY_KEY, color); } public int getVerticalLineColor() { return (int)getValue(VERTICAL_LINE_COLOR_PROPERTY_KEY); } public void setVerticalLineColor(int value) { this.setValue(VERTICAL_LINE_COLOR_PROPERTY_KEY, value); } /** * Gets the visibility of the major grid lines. * * @return The visibility of major grid lines. * @see GridLineVisibility */ public int getMajorLinesVisibility() { return (int)this.getValue(MAJOR_LINES_VISIBILITY_PROPERTY_KEY); } /** * Sets the visibility of the major grid lines. * * @param value The new visibility. * @see GridLineVisibility */ public void setMajorLinesVisibility(int value) { this.setValue(MAJOR_LINES_VISIBILITY_PROPERTY_KEY, value); } /** * Gets or sets the dash array used to define each major X line. * * @return A float array that defines the line dash pattern. */ public float[] getMajorXLineDashArray() { return (float[])this.getValue(MAJOR_X_LINE_DASH_ARRAY_PROPERTY_KEY); } /** * Sets the dash pattern for the major X lines. * * @param value A float array that represents the line dash pattern. */ public void setMajorXLineDashArray(float[] value) { this.setValue(MAJOR_X_LINE_DASH_ARRAY_PROPERTY_KEY, value); } /** * Gets or sets the dash array used to define each major Y line. * * @return A float array that defines the line dash pattern. */ public float[] getMajorYLineDashArray() { return (float[])this.getValue(MAJOR_Y_LINE_DASH_ARRAY_PROPERTY_KEY); } /** * Sets the dash pattern for the major Y lines. * * @param value A float array that represents the line dash pattern. */ public void setMajorYLineDashArray(float[] value) { this.setValue(MAJOR_Y_LINE_DASH_ARRAY_PROPERTY_KEY, value); } /** * Gets the render mode of the major X lines. * * @return The X lines {@link GridLineRenderMode}. * @see GridLineRenderMode */ public int getMajorXLinesRenderMode() { return (int)this.getValue(MAJOR_X_LINE_RENDER_MODE_PROPERTY_KEY); } /** * Sets the render mode of the major X lines. * * @param value The X lines {@link GridLineRenderMode}. * @see GridLineRenderMode */ public void setMajorXLinesRenderMode(int value) { this.setValue(MAJOR_X_LINE_RENDER_MODE_PROPERTY_KEY, value); } /** * Gets the render mode of the major Y lines. * * @return The Y lines {@link GridLineRenderMode}. * @see GridLineRenderMode */ public int getMajorYLinesRenderMode() { return (int)this.getValue(MAJOR_Y_LINE_RENDER_MODE_PROPERTY_KEY); } /** * Sets the render mode of the major Y lines. * * @param value The Y lines {@link GridLineRenderMode}. * @see GridLineRenderMode */ public void setMajorYLinesRenderMode(int value) { this.setValue(MAJOR_Y_LINE_RENDER_MODE_PROPERTY_KEY, value); } /** * Gets the {@link GridLineVisibility} of the grid stripes. * * @return The {@link GridLineVisibility} of the grid stripes. */ public int getStripLinesVisibility() { return (int)this.getValue(STRIP_LINES_VISIBILITY_PROPERTY_KEY); } /** * Sets the {@link GridLineVisibility} of the grid stripes. * * @param value The new visibility. */ public void setStripLinesVisibility(int value) { this.setValue(STRIP_LINES_VISIBILITY_PROPERTY_KEY, value); } /** * Gets the {@link ObservableCollection} of brushes used to display x-axis stripes. * * @return The collection of brushes used to display x-axis stripes. */ public ObservableCollection<Paint> getXStripeBrushes() { return this.xStripeBrushes; } /** * Gets the {@link ObservableCollection} of brushes used to display y-axis stripes. * * @return The collection of brushes used to display y-axis stripes. */ public ObservableCollection<Paint> getYStripeBrushes() { return this.yStripeBrushes; } /** * Gets the line thickness for the major lines. * * @return the current line thickness for the major lines. */ public float getLineThickness() { return (Float)this.getValue(MAJOR_LINES_THICKNESS_PROPERTY_KEY); } /** * Sets the line thickness for the major lines. * * @param lineThickness new line thickness. */ public void setLineThickness(float lineThickness) { this.setValue(MAJOR_LINES_THICKNESS_PROPERTY_KEY, lineThickness); } /** * Gets the line thickness for the vertical lines. * * @return the current line thickness for the vertical lines. */ public float getVerticalLineThickness() { return this.verticalLinePaint.getStrokeWidth(); } /** * Sets the line thickness for the vertical lines. * * @param lineThickness new vertical line thickness. */ public void setVerticalLineThickness(float lineThickness) { if (lineThickness <= 0) throw new IllegalArgumentException("lineThickness cannot be negative or zero"); this.verticalLinePaint.setStrokeWidth(lineThickness); } @Override protected String defaultPaletteFamily() { return ChartPalette.CARTESIAN_CHART_GRID; } /** * Gets the grid model. * * @return The grid model. */ protected ChartElement getElement() { return this.grid; } /** * Gets the Z Index of the grid relative to the children inside the chart view's render surface. * * @return The Z Index of the grid relative to the children inside the chart view's render surface. */ protected int getDefaultZIndex() { return 0; } @Override protected void applyPaletteCore(ChartPalette palette) { super.applyPaletteCore(palette); PaletteEntryCollection gridStripLinesPalette = palette.entriesForFamily(ChartPalette.CARTESIAN_CHART_GRID_STRIPES); if (gridStripLinesPalette != null) { for (PaletteEntry entry : gridStripLinesPalette) { Paint paint = new Paint(); paint.setColor(entry.getStroke()); this.xStripeBrushes.add(paint); this.yStripeBrushes.add(paint); } } PaletteEntry gridLinesPalette = palette.getEntry(this.getPaletteFamilyCore(), 0); if (gridLinesPalette == null) { return; } this.setValue(LINE_COLOR_PROPERTY_KEY, PALETTE_VALUE, gridLinesPalette.getStroke()); this.setValue(VERTICAL_LINE_COLOR_PROPERTY_KEY, PALETTE_VALUE, gridLinesPalette.getStroke()); String stringValue = gridLinesPalette.getCustomValue(CartesianChartGrid.MAJOR_LINES_THICKNESS_KEY); if (stringValue != null) { float majorLinesThickness = Float.parseFloat(stringValue); this.setValue(MAJOR_LINES_THICKNESS_PROPERTY_KEY, PALETTE_VALUE, majorLinesThickness); } stringValue = gridLinesPalette.getCustomValue(CartesianChartGrid.MAJOR_LINES_VISIBILITY_KEY); if (stringValue != null) this.setValue(MAJOR_LINES_VISIBILITY_PROPERTY_KEY, PALETTE_VALUE, GridLineVisibility.valueOf(stringValue)); stringValue = gridLinesPalette.getCustomValue(CartesianChartGrid.STRIP_LINES_VISIBILITY_KEY); if (stringValue != null) this.setValue(STRIP_LINES_VISIBILITY_PROPERTY_KEY, PALETTE_VALUE, GridLineVisibility.valueOf(stringValue)); stringValue = gridLinesPalette.getCustomValue(CartesianChartGrid.MAJOR_X_LINE_DASH_ARRAY_KEY); if (stringValue != null) { String[] dashArrayValues = stringValue.split(","); float[] values = new float[dashArrayValues.length]; for (int i = 0; i < dashArrayValues.length; i++) { values[i] = Float.parseFloat(dashArrayValues[i]); } this.setValue(MAJOR_X_LINE_DASH_ARRAY_PROPERTY_KEY, PALETTE_VALUE, values); } stringValue = gridLinesPalette.getCustomValue(CartesianChartGrid.MAJOR_Y_LINE_DASH_ARRAY_KEY); if (stringValue != null) { String[] dashArrayValues = stringValue.split(","); float[] values = new float[dashArrayValues.length]; for (int i = 0; i < dashArrayValues.length; i++) { values[i] = Float.parseFloat(dashArrayValues[i]); } this.setValue(MAJOR_Y_LINE_DASH_ARRAY_PROPERTY_KEY, PALETTE_VALUE, values); } stringValue = gridLinesPalette.getCustomValue(CartesianChartGrid.MAJOR_X_LINE_RENDER_MODE_KEY); if (stringValue != null) this.setValue(MAJOR_X_LINE_RENDER_MODE_PROPERTY_KEY, PALETTE_VALUE, GridLineRenderMode.valueOf(stringValue)); stringValue = gridLinesPalette.getCustomValue(CartesianChartGrid.MAJOR_Y_LINE_RENDER_MODE_KEY); if (stringValue != null) this.setValue(MAJOR_Y_LINE_RENDER_MODE_PROPERTY_KEY, PALETTE_VALUE, GridLineRenderMode.valueOf(stringValue)); } @Override public void render(Canvas canvas) { super.render(canvas); canvas.save(Canvas.CLIP_SAVE_FLAG); this.applyClip(canvas); this.updateVisuals(canvas); canvas.restore(); } @Override protected void onAttached() { super.onAttached(); ((ChartAreaModelWithAxes) this.getChart().getChartArea()).setGrid(this.grid); } @Override protected void onDetached(RadChartViewBase oldChart) { super.onDetached(oldChart); ((ChartAreaModelWithAxes) oldChart.getChartArea()).setGrid(null); } private void onMajorXLineDashArrayChanged(float[] newValue) { this.updateGridLineDashArray(this.majorXLines, newValue); } private void onMajorYLineDashArrayChanged(float[] newValue) { this.updateGridLineDashArray(this.majorYLines, newValue); } private void onMajorLinesVisibilityChanged() { this.majorXLines.visible = (this.majorLinesVisibilityCache & GridLineVisibility.X) == GridLineVisibility.X; this.majorYLines.visible = (this.majorLinesVisibilityCache & GridLineVisibility.Y) == GridLineVisibility.Y; this.requestRender(); } private void updateGridLineDashArray(GridLinesInfo gridLinesInfo, float[] dashArray) { if (gridLinesInfo != null) { gridLinesInfo.dashArray = dashArray; this.requestRender(); } } private void applyClip(Canvas canvas) { final RadRect currentClip = this.lastLayoutContext.clipRect(); canvas.clipRect( (int) currentClip.getX(), (int) currentClip.getY(), (int) currentClip.getRight(), (int) currentClip.getBottom() ); } private void updateVisuals(Canvas canvas) { this.updateXStripes(canvas); this.updateYStripes(canvas); this.majorXLines.drawLines(canvas); this.majorYLines.drawLines(canvas); } private Paint getStripeColor(ArrayList<Paint> colors, int brushIndex) { brushIndex = colors.size() > 0 ? brushIndex % colors.size() : brushIndex; return brushIndex < colors.size() ? colors.get(brushIndex) : ((brushIndex & 1) != 1) ? this.emptyPaint : this.emptyPaintSecondary; } private void updateXStripes(Canvas canvas) { if ((this.stripLinesVisibility & GridLineVisibility.X) == GridLineVisibility.X) { for (GridStripe stripe : this.grid.xStripes) { Paint color = this.getStripeColor(this.xStripeBrushes, stripe.startTick.virtualIndex()); RadRect stripeRect = stripe.fillRect; canvas.drawRect(Util.convertToRectF(stripeRect), color); } } } private void updateYStripes(Canvas canvas) { if ((this.stripLinesVisibility & GridLineVisibility.Y) == GridLineVisibility.Y) { for (GridStripe stripe : this.grid.yStripes) { Paint color = this.getStripeColor(this.yStripeBrushes, stripe.startTick.virtualIndex()); RadRect stripeRect = stripe.fillRect; canvas.drawRect(Util.convertToRectF(stripeRect), color); } } } private void onXStripeStylesChanged() { this.requestRender(); } private void onYStripeStylesChanged() { this.requestRender(); } private class GridLinesInfo { public float[] dashArray; public boolean visible; public int renderMode = GridLineRenderMode.ALL; public ArrayList<GridLine> lines; public CartesianChartGrid owner; public Paint linePaint; public GridLinesInfo(CartesianChartGrid owner) { this.owner = owner; } public void drawLines(Canvas canvas) { if (!this.visible) { return; } for (GridLine line : this.lines) { if (!this.shouldDrawLine(line)) { continue; } RadPoint p1 = line.point1; RadPoint p2 = line.point2; if (this.dashArray != null) { linePaint.setPathEffect(new DashPathEffect(this.dashArray, 0)); } else { linePaint.setPathEffect(null); } Path path = new Path(); path.moveTo((float) p1.getX(), (float) p1.getY()); path.lineTo((float) p2.getX(), (float) p2.getY()); canvas.drawPath(path, linePaint); } } private boolean shouldDrawLine(GridLine line) { AxisTickModel tick = line.axisTickModel; if (tick.position() == TickPosition.FIRST && (this.renderMode & GridLineRenderMode.FIRST) != GridLineRenderMode.FIRST) { return false; } if (tick.position() == TickPosition.INNER && (this.renderMode & GridLineRenderMode.INNER) != GridLineRenderMode.INNER) { return false; } if (tick.position() == TickPosition.LAST && (this.renderMode & GridLineRenderMode.LAST) != GridLineRenderMode.LAST) { return false; } return true; } } }
true
b363aa3ba9663ac56e25245adc0371fcb566ac38
Java
diegobugmann/ITProjekt
/ITProjekt/src/Commons/Message.java
UTF-8
3,212
3.265625
3
[]
no_license
package Commons; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.net.Socket; /** * Basic Class for all Messages, contains client, messageid and timestamp * @author mibe1 * */ public class Message implements Serializable { // Data included in a message //The first Message sent from a client to a server is always 0 from the seccond message the messages get an individual ID //IDs are not always unique!!!!!!!! This is not required but special private long id; private long timestamp; // contains the Sending client if message gets send from client to Server //Or the acting client if message gets send from Server to all clients (Example turn) private String client; // Generator for a unique message ID private static long messageID = 0; /** * Increment the global messageID * Code from Bradley Richards * @return the next valid ID * TODO think if this works when programm is exicuted on multible physical clients and what it is needed for */ private static long nextMessageID() { return messageID++; } public Message() { this.id = nextMessageID(); this.timestamp = System.currentTimeMillis(); } /** * Sends the Message on the given Socket * @param socket */ public void send(Socket socket) { try{ ObjectOutputStream writer = new ObjectOutputStream(socket.getOutputStream()); this.timestamp = System.currentTimeMillis(); //System.out.println("Sending: "+ this.toString() + " Socket " + socket.toString()); writer.writeObject(this); writer.flush(); } catch(Exception e) { System.out.println(e.toString()); } } //Geters and Setters ----------------------------------------------------------------------------- public long getId() { return id; } public void setId(long id) { this.id = id; } public long getTimestamp() { return timestamp; } public void setTimestamp(long timestamp) { this.timestamp = timestamp; } public String getClient() { return client; } public void setClient(String client) { this.client = client; } //-------------------------------------------------------------------------------------------------- @Override public String toString() { return "Message " + this.id +" Type "+MessageType.getType(this)+" Client " + this.client + " SendingTime " + this.timestamp; } /** * Reades a received Message and casts it into a Message Object * @param clientSocket * @return * @throws IOException * @throws ClassNotFoundException */ public static Message receive(Socket clientSocket) throws IOException, ClassNotFoundException { ObjectInputStream in = new ObjectInputStream(clientSocket.getInputStream()); Message msg = (Message) in.readObject(); if(messageID < msg.getId()) messageID = msg.getId(); //System.out.println("Read new Message "+ msg.toString()); return msg; } }
true
40035ecf4a99854c684ed4de99b6e6e0d1497ddc
Java
renbf/dly_communal
/src/main/java/com/project/appinterface/service/IWalletService.java
UTF-8
1,040
1.960938
2
[]
no_license
package com.project.appinterface.service; import com.project.appinterface.domain.Wallet; import java.util.List; /** * 用户钱包 服务层 * * @author lws * @date 2019-03-05 */ public interface IWalletService { /** * 查询用户钱包信息 * * @param id 用户钱包ID * @return 用户钱包信息 */ public Wallet selectWalletById(String id); /** * 查询用户钱包列表 * * @param wallet 用户钱包信息 * @return 用户钱包集合 */ public List<Wallet> selectWalletList(Wallet wallet); /** * 新增用户钱包 * * @param wallet 用户钱包信息 * @return 结果 */ public int insertWallet(Wallet wallet); /** * 修改用户钱包 * * @param wallet 用户钱包信息 * @return 结果 */ public int updateWallet(Wallet wallet); /** * 删除用户钱包信息 * * @param ids 需要删除的数据ID * @return 结果 */ public int deleteWalletByIds(String ids); }
true
eeadb06dc039ca8e6b4271e11ad025e2e4b5400b
Java
EitherRock/Kotor
/Kotor/kotorCardGame/src/kotorCardGame/PlayerHand.java
UTF-8
1,653
3.46875
3
[]
no_license
package kotorCardGame; import java.util.LinkedList; import java.util.Random; public class PlayerHand { private LinkedList<Integer> hand = new LinkedList<>(); Random random = new Random(); /** * generates a player hand with 5 cards */ public void fillHand() { for(int size = 0; size < 5; size++) { this.hand.add(makeNegative(randomNumber())); } } /** * get random int * @return randomized int */ private int randomNumber() { int number; number = random.nextInt(7); while(number < 1) { number = random.nextInt(10); } return number; } /** * takes a number and randomly makes it negative * @param num randomized int from randomNmber() * @return the final randomized number, negative or positive */ private int makeNegative(int num) { boolean bool = random.nextBoolean(); if(bool) { return num * (-1); } return num; } //public void setHand(LinkedList<Integer> hand) { // this.hand = hand; //} public LinkedList<Integer> getHand() { return hand; } public void displayHand() { for(int index = 0; index < hand.size(); index++) { System.out.print(this.hand.get(index)); System.out.print(" "); } System.out.println(""); } public void mainDisplay(String name,int total, StringBuilder string) { //Options options = new Options(); System.out.printf("%s total: %d\n",name, total); //System.out.printf("Turn = %d\n", turn); System.out.println(string); System.out.println(""); System.out.println("Player Hand:"); displayHand(); System.out.println(""); System.out.println("Options:"); //options.displayOptions(); } }
true
6b787655f8a0aa3d63d4f3af8a38478690c4a654
Java
zzx-git21/wych
/wy-appeal/src/main/java/com/wych/controller/AppealController.java
UTF-8
2,450
1.984375
2
[]
no_license
package com.wych.controller; import com.wych.common.vo.PageResult; import com.wych.pojo.Appeal; import com.wych.pojo.Complain; import com.wych.service.AppealService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController public class AppealController { @Autowired private AppealService appealService; //申述分页查询 @GetMapping("/list/status") public ResponseEntity<PageResult<Appeal>> selectAppeal(@RequestParam(value = "page",defaultValue = "1") Integer page, @RequestParam(value = "rows",defaultValue = "5") Integer rows, @RequestParam("userId") Long userId){ PageResult<Appeal> appeals=appealService.selectAppeal(page,rows,userId); return ResponseEntity.ok(appeals); } //投诉分页查询 @GetMapping("/list") public ResponseEntity<PageResult<Complain>> selectComplain(@RequestParam(value = "page",defaultValue = "1") Integer page, @RequestParam(value = "rows",defaultValue = "5") Integer rows, @RequestParam("userId") Long userId){ PageResult<Complain> appeals=appealService.selectComplain(page,rows,userId); return ResponseEntity.ok(appeals); } //添加申诉 @GetMapping("/select/complain") public ResponseEntity<List<Complain>> select(String username){ //第一步回显投诉信息 List<Complain> complain= appealService.selecetComplain(username); return ResponseEntity.ok(complain); } //正式添加 @PostMapping("/insert/appeal") public ResponseEntity<Void> insert(Appeal appeal){ appealService.insert(appeal); return ResponseEntity.ok(null); } //添加投诉 //正式添加 @PostMapping("/insert/complain") public ResponseEntity<Void> insertComplain(Complain complain){ appealService.insertComplain(complain); return ResponseEntity.ok(null); } //删除投诉 @DeleteMapping("delete/complain") public ResponseEntity<Void> deleteComplain(Long id){ appealService.deleteComplain(id); return ResponseEntity.ok(null); } }
true
8b45d611b82449d313c00e9009823361ad106eda
Java
SathishPoojary/api-test-framework
/src/main/java/com/shc/automation/api/test/framework/internal/response/validators/APIJsonValidator.java
UTF-8
4,436
2
2
[]
no_license
package com.shc.automation.api.test.framework.internal.response.validators; import com.shc.automation.api.test.framework.APITestConstants; import com.shc.automation.api.test.framework.model.response.APIValidation; import com.shc.automation.api.test.framework.model.response.ValidationType; import com.shc.automation.api.test.framework.utils.APITestUtils; import com.shc.automation.utils.json.JsonCompareUtils; import com.shc.automation.utils.json.JsonMismatchField; import net.sf.json.JSONObject; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; import java.util.List; public class APIJsonValidator implements APIValidator { @Override public APIValidation validate(APIValidation validator) { if (validator == null) { return validator; } Boolean validResponse = true; Object expectedResponseValue = validator.getExpectedResponseValue(); Object actualResponseValue = validator.getActualResponseValue(); List<String> excludes = validator.getExcludes(); List<String> arrayPathListToIgnoreOrder = validator.getArrayPathListToIgnoreOrder(); if (expectedResponseValue != null && actualResponseValue != null) { if (expectedResponseValue instanceof List) { expectedResponseValue = APITestUtils.wrapAPIResponse(expectedResponseValue); actualResponseValue = APITestUtils.wrapAPIResponse(actualResponseValue); if (CollectionUtils.isNotEmpty(excludes)) { List<String> excludePaths = new ArrayList<String>(excludes.size()); for (String path : excludes) { excludePaths.add(APITestUtils.getAbsoluteResponsePath(path)); } excludes = excludePaths; } if (CollectionUtils.isNotEmpty(arrayPathListToIgnoreOrder)) { List<String> excludePaths = new ArrayList<String>(arrayPathListToIgnoreOrder.size()); for (String path : arrayPathListToIgnoreOrder) { excludePaths.add(APITestUtils.getAbsoluteResponsePath(path)); } arrayPathListToIgnoreOrder = excludePaths; } } } List<JsonMismatchField> differences = null; try { differences = JsonCompareUtils.deepCompare(JSONObject.fromObject(expectedResponseValue), JSONObject.fromObject(actualResponseValue), excludes, validator.getCompareOption(), arrayPathListToIgnoreOrder); } catch (Exception e) { e.printStackTrace(); validator.setValidationResult(false); updateValidationMessage(validator); return validator; } ValidationType validationType = validator.getValidationType(); if (validationType == ValidationType.EQUALS && !CollectionUtils.isEmpty(differences)) validResponse = false; if (validationType == ValidationType.NOT_EQUALS && CollectionUtils.isEmpty(differences)) validResponse = false; if (validationType == ValidationType.CONTAINS_VALUE) { if (CollectionUtils.isNotEmpty(differences)) { JsonMismatchField diff = null; for (int i = 0; i < differences.size(); i++) { diff = differences.get(i); if (diff.getRightValue() == null) { validResponse = false; break; } } } } if (validationType == ValidationType.NOT_CONTAINS_VALUE) { if (CollectionUtils.isNotEmpty(differences)) { JsonMismatchField diff = null; for (int i = 0; i < differences.size(); i++) { diff = differences.get(i); if (diff.getRightValue() != null) { validResponse = false; break; } } } } validator.setValidationResult(validResponse); validator.setDifferences(differences); updateValidationMessage(validator); return validator; } private void updateValidationMessage(APIValidation validator) { String name = validator.getValidationName(); if (StringUtils.isEmpty(name)) { name = APITestUtils.getAbsoluteResponsePath(validator.getResponsePath()); if (APITestConstants.COMPARE_TWO_RESPONSES_BASE_PATH.equals(name)) name = "Full Response"; } StringBuilder str = new StringBuilder(); List<JsonMismatchField> differences = validator.getDifferences(); if (CollectionUtils.isNotEmpty(differences)) { str = new StringBuilder(differences.size() + " mismatch(s) found on comparison of [ " + name + " ]"); } else { if (!validator.getValidationResult()) str = new StringBuilder("Error occured in [" + name + "] comparison "); else str = new StringBuilder("No mismatches found in comparsion of " + name); } validator.setValidationMessage(str.toString()); } }
true
8092ca10043dd8627129d5e3c4d1c04bd4e6f9ea
Java
happinessyeah/petablox
/src/petablox/analyses/syntax/RelBootstrapMethodArg.java
UTF-8
1,048
2.015625
2
[]
no_license
package petablox.analyses.syntax; import soot.SootClass; import soot.SootMethod; import soot.Unit; import soot.Value; import soot.jimple.InvokeExpr; import soot.jimple.internal.JDynamicInvokeExpr; import petablox.program.visitors.IInvokeExprVisitor; import petablox.project.Petablox; import petablox.project.analyses.ProgramRel; @Petablox(name = "BootstrapMethodArg", sign = "Invoke0,Z0,EXPR0:Invoke0_Z0xEXPR0") public class RelBootstrapMethodArg extends ProgramRel implements IInvokeExprVisitor { @Override public void visit(SootClass m) { } @Override public void visit(SootMethod m) { } @Override public void visit(Unit u) { } @Override public void visit(Value v) { } @Override public void visit(InvokeExpr e) { if(e instanceof JDynamicInvokeExpr) { JDynamicInvokeExpr ex = (JDynamicInvokeExpr) e; int pos = 0; for (Value arg : ex.getBootstrapArgs()) { add(e, new Integer(pos), arg); pos++; } } } }
true
b063ad0c76bda6362dfc2dc55337a19d326b988d
Java
danyalwalker/Java-Programming
/src/a_oca/q038/Q38.java
UTF-8
635
3.21875
3
[]
no_license
package a_oca.q038; public class Q38 { } /* * 38. Which three are advantages of the Java exception mechanism? (Choose three.) A. Improves the program structure because the error handling code is separated from the normal program function B. Provides a set of standard exceptions that covers all possible errors C. Improves the program structure because the programmer can choose where to handle exceptions D. Improves the program structure because exceptions must be handled in the method in which they occurred E. Allows the creation of new exceptions that are customized to the particular program being created Answer: A C E */
true
1c626cf43f038a7b6fca6f48a2c5eef0adfc1369
Java
Megre/Dataset4SparT-ETA
/3. Automatically Generated Test Data/MPX.Strategy/Strategy_Setter_MDocument_TextModel_7.java
UTF-8
382
2.125
2
[ "CC-BY-4.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package test.auto; public class Strategy_Setter_MDocument_TextModel_7 { public static void main(String[] args) throws java.lang.Exception { com.taursys.model.TextModel strategy = new com.taursys.model.DefaultTextModel(1); com.taursys.swing.MDocument context = new com.taursys.swing.MDocument(); context.setModel(strategy); context.setFormat(new java.text.Format()); } }
true
06ded07440f407281cf3fa0f02de154d0a557536
Java
JohannAtGithub/Frogger
/src/Frames/MenuFrame.java
UTF-8
3,894
2.96875
3
[]
no_license
package Frames; import Objects.FroggerFrame; import Objects.FroggerGame; import UI.CustomizedButtonUI; import javax.imageio.ImageIO; import javax.swing.*; import javax.swing.border.Border; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; public class MenuFrame extends JFrame implements ActionListener { private JButton start; private JButton exit; private Image backgroundIMG; private int width; private int height; public MenuFrame(String title) { super(title); width = 660; height = 410; setSize(width, height); setLocationRelativeTo(null); setUndecorated(true); setResizable(false); setLayout(null); /* * Set the background but don't draw yet */ try { this.backgroundIMG = ImageIO.read(new File("src/Textures/menu_background.png")); } catch (IOException e) { e.printStackTrace(); } Border emptyBorder = BorderFactory.createEmptyBorder(); /* * Set the game title and a shadow */ int titleWidth = 270; int titleHeight = 55; int titleX = 24; int titleY = 30; int titleSize = 47; String fontNameTitle = "Ravie"; JLabel gameTitle = new JLabel("Frogger"); gameTitle.setBounds(0, 0, titleWidth, titleHeight); gameTitle.setFont(new Font(fontNameTitle, Font.BOLD, titleSize)); gameTitle.setForeground(new Color(251,102,8)); gameTitle.setLocation(titleX, titleY); add(gameTitle); JLabel gameTitleShadow = new JLabel("Frogger"); gameTitleShadow.setBounds(0,0, titleWidth, titleHeight); gameTitleShadow.setFont(new Font(fontNameTitle, Font.BOLD, titleSize)); gameTitleShadow.setForeground(new Color(68,71,140)); gameTitleShadow.setBackground(Color.black); gameTitleShadow.setLocation(titleX + 4, titleY + 4); add(gameTitleShadow); /* * Set the buttons and style them */ Color hoverColor = Color.black; Color normalColor = new Color(183,233,98); Color pressedColor = new Color(45,45,45); Color fontColor = new Color(251,102,8); String fontNameButtons = "Snap ITC"; int fontSizeButtons = 25; int buttonPositionX = 75; int buttonPositionY = 135; int buttonWidth = 160; int buttonHeight = 40; int verticalDistance = 55; start = new JButton("Start"); start.addActionListener(this); start.setBorder(emptyBorder); start.setUI(new CustomizedButtonUI(normalColor, hoverColor, pressedColor, new Font(fontNameButtons, Font.PLAIN, fontSizeButtons), fontColor)); start.setBounds(buttonPositionX, buttonPositionY, buttonWidth, buttonHeight); add(start); exit = new JButton("Exit"); exit.addActionListener(this); exit.setBorder(emptyBorder); exit.setUI(new CustomizedButtonUI(normalColor, hoverColor, pressedColor, new Font(fontNameButtons, Font.PLAIN, fontSizeButtons), fontColor)); exit.setBounds(buttonPositionX, buttonPositionY + verticalDistance, buttonWidth, buttonHeight); add(exit); /* * Draw the background at latest * else the other labels aren't visible. */ JLabel background = new JLabel(new ImageIcon(this.backgroundIMG)); background.setBounds(28,getHeight() - 438, 400, 438); background.setBounds(0,0,width,height); add(background); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == start) { new FroggerFrame(); } else if (e.getSource() == exit) { System.exit(0); } } }
true
0b83c157fd648b1a22b3a45623cc6dc7cada35e7
Java
Stofi09/JavaPokerGame
/src/main/java/com/web/socket/websocket/game/TurnCounter.java
UTF-8
575
2.546875
3
[ "MIT" ]
permissive
package com.web.socket.websocket.game; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class TurnCounter { @Autowired private BoolContainer cont; public TurnCounter() {} public void setCont(boolean bol1,boolean bol2,boolean bol3) { this.cont.setBools(bol1, bol2, bol3); } public boolean isNewTurn() { return result(); } private boolean result() { if(this.cont.getCallRaise()&&!this.cont.getFirstRaise()&&!this.cont.getOverRaise()) return true; else return false; } }
true
a95d9dcb4a7afaadcd35471f4ff895205bdd83c4
Java
MonikaSophin/myproject
/src/com/design_mode/creational_patterns/singleton_pattern/DCL.java
UTF-8
535
2.984375
3
[]
no_license
package com.design_mode.creational_patterns.singleton_pattern; /** * @author: XueYing.Cao * @date: 2019/6/21 * @description: 4.双检锁/双重检验锁(double-checked locking) */ public class DCL { private DCL() {} private volatile static DCL instance; public static DCL getInstance() { if (instance == null) { synchronized (DCL.class) { if (instance == null) { instance = new DCL(); } } } return instance; } }
true
e4967b38af900ff684813db136d010271c41b217
Java
jucasoliveira/anagramhostelworld
/AutomationHostelWorld/src/automationMobile/sortByPrice.java
UTF-8
3,426
2.875
3
[]
no_license
package automationMobile; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.openqa.selenium.*; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.WebDriverWait; public class sortByPrice { public static WebDriverWait wait; public static WebDriver driver; @BeforeClass public static void setUp() { System.setProperty("webdriver.chrome.driver","C:\\Users\\jucas.oliveira\\Documents\\chromedriver\\chromedriver.exe"); driver = new ChromeDriver(); } @AfterClass public static void tearDown() { driver.quit(); } @Test public void testMethod() throws InterruptedException { try{ //Put a Implicit wait, this means that any search for elements on the page could take the time the implicit wait is set for before throwing exception driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); //Launching the Website driver.get("http://t.hostelworld.com"); // Inputing city name driver.findElement(By.id("home-search-keywords")).sendKeys("Dublin, Ireland"); // Find and select the name of the city on autocomplete driver.findElement(By.xpath("//*[contains(@class,'suggestion needsclick')]")).click(); // Find the button search driver.findElement (By.xpath("//*[@id='sb-search']/div[3]/div/button")).click(); // Find element sort to select by name driver.findElement (By.xpath("//*[@id='pagebody']/div[1]/div/div/div[12]/div[3]/div/div/div/div/dl[1]/dd[2]")).click(); // Select price driver.findElement (By.xpath("//*[@id='sortByPrice']")).click(); //Verify numeric order List<WebElement> allItems = driver.findElements(By.xpath("//*[@class='dormroom']")); List<String> money = new ArrayList<String>(); List<String> newMoney = new ArrayList<String>(); // List<WebElement> allItems = driver.findElements(By.xpath("//*[@class='pricing no-bullet']")); //Fill String Arrays to make numeric comparison for(int i=0;i<allItems.size();i++){ money.add(allItems.get(i).getText()); newMoney.add(allItems.get(i).getText()); } //Sorting first array to check if is sorted String compare = "True"; Collections.sort(money); for (int i=0;i<money.size();i++) { //System.out.println(money.get(i)); System.out.println("Hostel price from input: " + money.get(i) + "--Hostel Price from sorted input: " + newMoney.get(i)); if (!(money.get(i).equals(newMoney.get(i)))) { System.out.println("Hostel Prices aren't sorted"); compare = "False"; break; } } if(compare.equals("True")){ System.out.println("Test completed succesfully with prices ordered correctly"); /* for (int i=0;i<money.size();i++) { System.out.println(money.get(i)); } */ } System.out.println("Test Complete"); }catch (NoSuchElementException e) { } } }
true
718407231e1d70d2c50fca57ab6e3375c90880b0
Java
TheShermanTanker/NMS-1.16.3
/org/bukkit/craftbukkit/v1_16_R2/util/CraftVector.java
UTF-8
723
1.914063
2
[]
no_license
/* */ package org.bukkit.craftbukkit.v1_16_R2.util; /* */ /* */ import net.minecraft.server.v1_16_R2.Vec3D; /* */ import org.bukkit.util.Vector; /* */ /* */ public final class CraftVector /* */ { /* */ public static Vector toBukkit(Vec3D nms) { /* 9 */ return new Vector(nms.x, nms.y, nms.z); /* */ } /* */ /* */ public static Vec3D toNMS(Vector bukkit) { /* 13 */ return new Vec3D(bukkit.getX(), bukkit.getY(), bukkit.getZ()); /* */ } /* */ } /* Location: C:\Users\Josep\Downloads\Decompile Minecraft\tuinity-1.16.3.jar!\org\bukkit\craftbukkit\v1_16_R\\util\CraftVector.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
true
7d5211f1316d46bd66f614cda5f3b13369571e55
Java
samueluy/animal-chess
/src/Move.java
UTF-8
11,118
3.53125
4
[]
no_license
import java.util.Scanner; /** * This class contains all the methods which will allow a player to move their pieces */ public class Move { Scanner in = new Scanner(System.in); private Animal piece; private GameBoard board; /** * Ask the player for an input to determine which piece he/she desires to move and to where * * @param board GameBoard object * @param player Current player move */ public void move(GameBoard board, boolean player) { System.out.print("Enter piece character: "); String symbol = in.nextLine(); System.out.print("Enter direction (U,D,L,R): "); String direction = in.nextLine(); boolean validPiece = false; for (int row = 0; row < board.getBlock().length; row++) { for (int col = 0; col < board.getBlock()[row].length; col++) { if (board.getBlock()[row][col].getPiece() != null) { if (board.getBlock()[row][col].getPiece().getSymbol().equals(symbol) && board.getBlock()[row][col].getPiece().isBlue() == player) { validPiece = true; boolean hasMoved = false; switch (direction) { case "U": if (checkBounds(board, row - 1, col)) { if (board.getBlock()[row - 1][col].getSpecial() != null) { // Tiger special block condition if (board.getBlock()[row][col].getPiece().getSymbol().equals("T") && board.getBlock()[row - 1][col].getSpecial().getSymbol().equals("=")) { updatePos(board.getBlock()[row][col], board.getBlock()[row - 4][col]); hasMoved = true; } } if (!hasMoved) { if (checkValid(board, row, col, row - 1, col, player)) updatePos(board.getBlock()[row][col], board.getBlock()[row -1][col]); } } break; case "D": if (checkBounds(board, row + 1, col)) { if (board.getBlock()[row + 1][col].getSpecial() != null) { // Tiger special block condition if (board.getBlock()[row][col].getPiece().getSymbol().equals("T") && board.getBlock()[row + 1][col].getSpecial().getSymbol().equals("=")) { updatePos(board.getBlock()[row][col], board.getBlock()[row + 3][col]); hasMoved = true; } } if (!hasMoved) { if (checkValid(board, row, col, row + 1, col, player)) { updatePos(board.getBlock()[row][col], board.getBlock()[row + 1][col]); row = board.getBlock().length - 1; } } } break; case "L": if (checkBounds(board, row, col - 1)) { if (board.getBlock()[row][col - 1].getSpecial() != null) { // Tiger special block condition if (board.getBlock()[row][col].getPiece().getSymbol().equals("T") && board.getBlock()[row][col - 1].getSpecial().getSymbol().equals("=")) { updatePos(board.getBlock()[row][col], board.getBlock()[row][col -3]); hasMoved = true; } } if (!hasMoved) { if (checkValid(board, row, col, row, col - 1, player)) updatePos(board.getBlock()[row][col], board.getBlock()[row][col -1]); } } break; case "R": if (checkBounds(board, row, col + 1)) { if (board.getBlock()[row][col + 1].getSpecial() != null) { // Tiger special block condition if (board.getBlock()[row][col].getPiece().getSymbol().equals("T") && board.getBlock()[row][col + 1].getSpecial().getSymbol().equals("=")) { updatePos(board.getBlock()[row][col], board.getBlock()[row][col +3]); hasMoved = true; col = board.getBlock()[row].length - 1; } } if (!hasMoved) { if (checkValid(board, row, col, row, col + 1, player)) { updatePos(board.getBlock()[row][col], board.getBlock()[row][col +1]); col = board.getBlock()[row].length - 1; } } } break; default: System.out.println("Invalid input"); board.setPlayer(!board.isPlayer()); } } } } } if (!validPiece) { System.out.println("Invalid input"); board.setPlayer(!board.isPlayer()); } board.setPlayer(!board.isPlayer()); // Next player move } /** * Transfers an Animal object from one block to another * * @param from Block object where the piece is originally located * @param to Block object where the piece desires to go */ public void updatePos(BlockCoords from, BlockCoords to) { to.setPiece(from.getPiece()); from.setPiece(null); } /** * Checks if a move that will be made is within the bounds of the board * * @param board GameBoard object * @param newRow Row coordinate where the animal object desires to go * @param newCol Column coordinate where the animal object desires to go * @return */ public boolean checkBounds(GameBoard board, int newRow, int newCol) { if (newRow < 0 || newRow >= board.getBlock().length || newCol >= board.getBlock()[newRow].length || newCol < 0) { System.out.println("Invalid move"); board.setPlayer(!board.isPlayer()); // Reset player move if invalid return false; } return true; } /** * Checks if a move to be made is valid. This method looks into possible issues such as:<br> * 1. Piece takes another piece of a higher rank<br> * 2. Piece takes another piece of its own (color/team)<br> * 3. Piece moves to a river (exception made for Tiger and Mouse)<br> * 4. Piece takes its own (color/team) den * * @param board GameBoard object * @param oldRow Row coordinate where the animal object is currently located * @param oldCol Column coordinate where the animal object is currently located * @param newRow Row coordinate where the animal object desires to go * @param newCol Column coordinate where the animal object desires to go * @param player Current player moving * @return */ public boolean checkValid(GameBoard board, int oldRow, int oldCol, int newRow, int newCol, boolean player) { //If there is something in the Chosen block and in the desired block to move at if (board.getBlock()[oldRow][oldCol].getPiece() != null && board.getBlock()[newRow][newCol].getPiece() != null) { //Comparing the ranks of the Current player's piece and it's opponent if (board.getBlock()[oldRow][oldCol].getPiece().getRank() < board.getBlock()[newRow][newCol].getPiece().getRank()) { System.out.println("Invalid move"); board.setPlayer(!board.isPlayer()); // Reset player move if invalid return false; } // Animal same player condition; cannot eat own piece else if (board.getBlock()[oldRow][oldCol].getPiece().isBlue() == board.getBlock()[newRow][newCol].getPiece().isBlue()) { System.out.println("Invalid move"); board.setPlayer(!board.isPlayer()); // Reset player move if invalid return false; } } // Check if special block: Trap / River if (board.getBlock()[newRow][newCol].getSpecial() != null) { if (board.getBlock()[newRow][newCol].getSpecial().getSymbol().equals("=")) { System.out.println("Invalid move"); board.setPlayer(!board.isPlayer()); // Reset player move if invalid return false; } // Can not take own den else if (board.getBlock()[newRow][newCol].getSpecial().isBlue() == player) { System.out.println("Invalid move"); board.setPlayer(!board.isPlayer()); // Reset player move if invalid return false; } } return true; } }
true
1989d54c58f4f7d5113ad9928362aa26d95d4895
Java
qqj19891210/scw
/scw-manager/manager-pojo/src/main/java/com/smart/scw/manager/bean/TUser.java
UTF-8
2,669
2.171875
2
[]
no_license
package com.smart.scw.manager.bean; import com.smart.scw.manager.validationGroup.UserGroup; import javax.validation.constraints.Pattern; import java.io.Serializable; public class TUser implements Serializable { private Integer id; @Pattern(regexp = "^[a-zA-Z]\\w{6,16}$",message = "{Pattern.user.loginacct}",groups = {UserGroup.class}) private String loginacct; @Pattern(regexp = "^[a-zA-Z0-9]{6,16}$",message = "{Pattern.user.password}",groups = {UserGroup.class}) private String userpswd; private String username; @Pattern(regexp = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*", message = "{Pattern.user.email}",groups = {UserGroup.class}) private String email; private String createtime; private String salt; private boolean rememberMe; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getLoginacct() { return loginacct; } public void setLoginacct(String loginacct) { this.loginacct = loginacct == null ? null : loginacct.trim(); } public String getUserpswd() { return userpswd; } public void setUserpswd(String userpswd) { this.userpswd = userpswd == null ? null : userpswd.trim(); } public String getUsername() { return username; } public void setUsername(String username) { this.username = username == null ? null : username.trim(); } public String getEmail() { return email; } public void setEmail(String email) { this.email = email == null ? null : email.trim(); } public String getCreatetime() { return createtime; } public void setCreatetime(String createtime) { this.createtime = createtime == null ? null : createtime.trim(); } public String getSalt() { return salt; } public void setSalt(String salt) { this.salt = salt == null ? null : salt.trim(); } public boolean isRememberMe() { return rememberMe; } public void setRememberMe(boolean rememberMe) { this.rememberMe = rememberMe; } @Override public String toString() { return "TUser{" + "id=" + id + ", loginacct='" + loginacct + '\'' + ", userpswd='" + userpswd + '\'' + ", username='" + username + '\'' + ", email='" + email + '\'' + ", createtime='" + createtime + '\'' + ", salt='" + salt + '\'' + ", rememberMe=" + rememberMe + '}'; } }
true
0216700d5c7e8e9fef44e3f86632b24b20a25074
Java
Vishvin95/PenDownABook
/src/test/java/com/pendownabook/PenDownABookApplicationTests.java
UTF-8
1,808
2.15625
2
[]
no_license
package com.pendownabook; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import com.pendownabook.entities.Publisher; import com.pendownabook.repositories.PublisherRepository; import com.pendownabook.service.PublisherService; import com.pendownabook.service.PublisherServiceImpl; @AutoConfigureMockMvc @SpringBootTest class PenDownABookApplicationTests { @InjectMocks private PublisherService publisherService = new PublisherServiceImpl(); @Mock private PublisherRepository publisherRepository; @Before public void init() { MockitoAnnotations.initMocks(this); } @Test void shouldListAllPublishers() throws Exception { List<Publisher> list = new ArrayList<Publisher>(); Publisher pubOne = new Publisher(); pubOne.setId(1l); pubOne.setFirstName("A"); pubOne.setEmail("a@gmail.com"); Publisher pubTwo = new Publisher(); pubTwo.setId(2l); pubTwo.setFirstName("B"); pubTwo.setEmail("b@gmail.com"); list.add(pubOne); list.add(pubTwo); when(publisherRepository.findAll()).thenReturn(list); List<Publisher> pubList = publisherService.getAll(); assertEquals(2, pubList.size()); verify(publisherRepository, times(1)).findAll(); } }
true
b3a1ea9b7fff2e828dbcde0650328f5944c101be
Java
rkacode/dc-ddd
/src/main/java/org/demo/entity/reservation/Reservation.java
UTF-8
673
2.125
2
[]
no_license
package org.demo.entity.reservation; import org.demo.annotations.AggregateRoot; import org.demo.entity.roles.Agent; import org.demo.entity.trip.Ticket; import org.demo.entity.trip.Trip; import javax.persistence.*; import java.util.HashSet; import java.util.Set; @Entity @AggregateRoot @Table(name = "reservation") public class Reservation { @Id @GeneratedValue private int id; @ManyToOne private Trip trip; private String name; private String phoneNumber; private String roomNumber; private String extraInformation; @ManyToOne private Agent agent; @OneToMany private Set<Ticket> tickets = new HashSet<>(); }
true
20d403dd2bab1d4c26e38af857622f5ab7e486d3
Java
pavankumar1597/PROJECTBIKE
/controller/dispatch.java
UTF-8
1,201
2.25
2
[]
no_license
package controller; import java.io.IOException; import java.io.PrintWriter; import java.sql.PreparedStatement; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import model.customermodel; public class dispatch extends HttpServlet { private static final long serialVersionUID = 1L; boolean check=false ; protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String vnumberString =req.getParameter("value") ; customermodel mCustomermodel = new customermodel(); try { check = mCustomermodel.dispatch(vnumberString); System.out.println(check); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(check==true) { HttpSession sessin = req.getSession(true); sessin.setAttribute("vehicalnb", vnumberString); res.sendRedirect("dispatchsucc.jsp"); } } }
true
70e42f6410adef582843563f667027340aa2fe25
Java
idiginfo/citagora
/models/src/org/idiginfo/docsvc/model/citagora/AnnotationBody.java
UTF-8
441
2.015625
2
[]
no_license
package org.idiginfo.docsvc.model.citagora; /** * Interface to implement the Citagora AnnotationBody object * * @author griccardi * */ public interface AnnotationBody extends UriObject { static final String TYPE = "cnt:ContextAsText"; static final String COLLECTION = "nbody"; String getCharacterEncoding(); String getChars(); String getUri(); void setChars(String string); void setCharacterEncoding(String string); }
true
ff24cfa3c86d4c4842aca9f3d3e9c2547a5ad90b
Java
adrien-LD/JAVA
/src/main/java/com/attractions/dao/UserCollectDao.java
UTF-8
1,542
2.453125
2
[]
no_license
package com.attractions.dao; import com.attractions.moudle.UserCollect; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; /** * 用户收藏景点信息 */ public class UserCollectDao extends BaseDao{ /** * 处理查询结果 * * @param resultSet * @return */ public UserCollect resultManage(ResultSet resultSet) { UserCollect userCollect = new UserCollect(); try { userCollect.setUserId(resultSet.getString("userId")); userCollect.setUsername(resultSet.getString("user_name")); userCollect.setAttrId(resultSet.getString("attrId")); userCollect.setAttrName(resultSet.getString("attr_name")); } catch (SQLException e) { e.printStackTrace(); } return userCollect; } /** * 数据库查询操作 * * @param sql * @return */ public ArrayList<UserCollect> queryInfo(String sql) { ArrayList<UserCollect> arr = new ArrayList<>(); try { ResultSet resultSet = query(sql); while (resultSet.next()) { UserCollect userCollect = resultManage(resultSet); arr.add(userCollect); } } catch (SQLException e) { e.printStackTrace(); } return arr; } /** * 用户详情表数据更新操作 * * @param sql * @return */ public boolean updateInfo(String sql) { return update(sql); } }
true
02ed73fcff14858d78287c6fc1f4ec844286cd9c
Java
OrzEvans/druid-spring-boot
/druid-spring-boot-samples/src/main/java/com/github/trang/druid/config/DynamicDataSource.java
UTF-8
1,296
2.375
2
[ "Apache-2.0" ]
permissive
package com.github.trang.druid.config; import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; import javax.sql.DataSource; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; /** * 动态数据源,基于简单的轮询算法 * * @author trang */ public class DynamicDataSource extends AbstractRoutingDataSource { private AtomicInteger count = new AtomicInteger(); private DataSource defaultTargetDataSource; private Map<String, DataSource> targetDataSources; public DynamicDataSource(DataSource defaultTargetDataSource, Map<String, DataSource> targetDataSources) { this.defaultTargetDataSource = defaultTargetDataSource; this.targetDataSources = targetDataSources; } @Override protected Object determineCurrentLookupKey() { int i = count.incrementAndGet(); List<String> list = new ArrayList<>(targetDataSources.keySet()); return list.get(i % list.size()); } @Override public void afterPropertiesSet() { super.setDefaultTargetDataSource(defaultTargetDataSource); super.setTargetDataSources(new HashMap<>(targetDataSources)); super.afterPropertiesSet(); } }
true
453ec58aafe53a1f2d245b41002f90bb1bf7ecfb
Java
edabruzzo/UNINOVE_Sistema_Controle_Contratos
/src/java/Util/OperacoesBancoDados.java
UTF-8
13,584
2.40625
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Util; import com.mysql.jdbc.exceptions.MySQLSyntaxErrorException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Emm */ public class OperacoesBancoDados { private String URL; private String USER = "root"; private String PASSWORD = "root"; public OperacoesBancoDados() { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException ex) { Logger.getLogger(OperacoesBancoDados.class.getName()).log(Level.SEVERE, null, ex); } } public void criaInfraestrutura() throws SQLException, ClassNotFoundException { ArrayList<String> listaSQLs = new ArrayList(); String sql1 = "CREATE TABLE IF NOT EXISTS tb_usuario " + "(id_usuario INTEGER AUTO_INCREMENT NOT NULL, " + "nome VARCHAR(255) NOT NULL UNIQUE, " + "departamento VARCHAR(255) NOT NULL, " + "dataAdmissao DATE NOT NULL, " + "ATIVO TINYINT(1) default 1, " + "login VARCHAR(10) NOT NULL, " + "password VARCHAR(10) NOT NULL ," + "papelUsuario ENUM('servidor', 'gestor') NOT NULL, " + "PRIMARY KEY (id_usuario));"; listaSQLs.add(sql1); String sql2 = "CREATE TABLE IF NOT EXISTS tb_contrato (id_contrato INTEGER AUTO_INCREMENT NOT NULL, " + " objetoContrato VARCHAR(255) NOT NULL, orcamentoComprometido DOUBLE NOT NULL, " + "ATIVO TINYINT(1) default 0, empresaContratada VARCHAR(255) NOT NULL, " + "departamentoResponsavel VARCHAR(255), " + "id_funcionarioGestor INTEGER REFERENCES tb_usuario(id_usuario), " + "PRIMARY KEY (id_contrato));"; listaSQLs.add(sql2); String sql3 = "INSERT INTO tb_contrato(objetoContrato, orcamentoComprometido, " + "ATIVO, empresaContratada, departamentoResponsavel, id_FuncionarioGestor) " + "VALUES('Manutenção parque tecnológico', 100000, true, " + "'Organizações Tabajara Ltda.', 'Diretoria de Administração', 1);"; listaSQLs.add(sql3); String sql4 = "INSERT INTO tb_contrato(objetoContrato, orcamentoComprometido, " + "ATIVO, empresaContratada, departamentoResponsavel, id_FuncionarioGestor) " + "VALUES('Limpeza', 50000, true, " + "'Organizações Tabajara Ltda.', 'Manutenção', " + "1);"; listaSQLs.add(sql4); String sql5 = "INSERT INTO tb_contrato(objetoContrato, orcamentoComprometido, " + "ATIVO, empresaContratada, departamentoResponsavel, id_FuncionarioGestor) " + "VALUES('Segurança', 200000, true, " + "'Organizações Tabajara Ltda.', 'Setor de Gestão de Contratos', " + "1);"; listaSQLs.add(sql5); String sql6 = "INSERT INTO tb_contrato(objetoContrato, orcamentoComprometido, " + "ATIVO, empresaContratada, departamentoResponsavel, id_FuncionarioGestor) " + "VALUES('Manutenção geral', 30000, true, " + "'Organizações Tabajara Ltda.', 'Manutenção', " + "2);"; listaSQLs.add(sql6); String sql7 = "INSERT INTO tb_usuario (nome, departamento, dataAdmissao, " + "ATIVO, login, password, papelUsuario) " + "VALUES ('Fulano', 'Setor de Gestão de Contratos', '2018-01-01', " + "true, 'fulano', '123', 'gestor');"; listaSQLs.add(sql7); String sql8 = "INSERT INTO tb_usuario (nome, departamento, dataAdmissao, " + "ATIVO, login, password, papelUsuario) " + "VALUES ('Sicrano', 'Manutenção', '2018-01-01', " + "true, 'sicrano', '123', 'servidor');"; listaSQLs.add(sql8); String sql9 = "INSERT INTO tb_usuario (nome, departamento, dataAdmissao, " + "ATIVO, login, password, papelUsuario) " + "VALUES ('Beltrano', 'Diretoria', '2018-01-01', " + "false, 'beltrano', '123', 'gestor');"; listaSQLs.add(sql9); String sql10 = "INSERT INTO tb_contrato" + "(objetoContrato, " + "orcamentoComprometido, " + "ATIVO, " + "empresaContratada, " + "departamentoResponsavel, " + "id_funcionarioGestor)" + "VALUES ('Manutenção Predial', 49000, true, 'WCA Ltda.', 'Manutenção', 2);"; listaSQLs.add(sql10); String sql11 = "INSERT INTO tb_contrato" + "(objetoContrato, " + "orcamentoComprometido, " + "ATIVO, " + "empresaContratada, " + "departamentoResponsavel, " + "id_funcionarioGestor)" + "VALUES ('Fornecimento de impressoras multifuncionais', " + "67000, true, 'Orion Ltda.', 'Departamento de TI', 1);"; listaSQLs.add(sql11); String sql12 = "INSERT INTO tb_contrato" + "(objetoContrato, " + "orcamentoComprometido, " + "ATIVO, " + "empresaContratada, " + "departamentoResponsavel, " + "id_funcionarioGestor)" + "VALUES ('Fornecimento de computadores', " + "27500, true, 'NETUNO Ltda.', 'Departamnto de TI', 2);"; listaSQLs.add(sql12); Connection conn = null; ResultSet rs = null; conn = this.criaConexao(); String sqlTESTE = "SELECT * FROM tb_usuario LIMIT 1"; try{ Statement stmt = conn.createStatement(); System.out.println("Executando a seguinte query ....."); System.out.println(sqlTESTE); rs = stmt.executeQuery(sqlTESTE); System.out.println("Executada com sucesso!"); }catch(SQLException e){ if(e.getMessage().contains("Table 'sistemacontrolecontratos.tb_usuario' doesn't exist") || e.getMessage().contains("Table") && e.getMessage().contains("exist")){ executaBatchUpdate(conn, listaSQLs); }else { return; } } } public void criaBaseDados() throws ClassNotFoundException, SQLException { //REGISTRANDO O DRIVER NO CONSTRUTOR E NÃO EM CADA MÉTODO //Class.forName("com.mysql.jdbc.Driver"); this.setURL("jdbc:mysql://localhost:3306/"); Connection conn = null; Statement stmt = null; //STEP 3: Open a connection System.out.println("Conectando ao servidor com a seguinte URL : " + this.URL); try { conn = DriverManager.getConnection(URL, USER, PASSWORD); stmt = conn.createStatement(); conn.setAutoCommit(false); stmt.execute("CREATE DATABASE IF NOT EXISTS sistemaControleContratos"); conn.commit(); } catch (SQLException ex) { conn.rollback(); Logger.getLogger(OperacoesBancoDados.class.getName()).log(Level.SEVERE, null, ex); } finally { stmt.close(); fecharConexao(conn); } } public Connection criaConexao() { this.setURL("jdbc:mysql://localhost:3306/sistemaControleContratos"); Connection conn = null; Statement stmt = null; //STEP 3: Open a connection System.out.println("Conectando ao servidor com a seguinte URL : " + this.URL); try { conn = DriverManager.getConnection(URL, USER, PASSWORD); } catch (SQLException ex) { Logger.getLogger(OperacoesBancoDados.class.getName()).log(Level.SEVERE, null, ex); } return conn; } public void fecharConexao(Connection conn) { System.out.println("Fechando a conexão com o banco de dados"); try { if (conn != null) { conn.close(); System.out.println("Conexão com o banco de dados fechada com sucesso"); } } catch (SQLException ex) { Logger.getLogger(OperacoesBancoDados.class.getName()).log(Level.SEVERE, null, ex); System.out.println("********ATENÇÃO ! Conexão com o banco de dados não foi fechada !"); } } public ResultSet executaQuerieResultSet(Connection conn, String sql) throws ClassNotFoundException, SQLException { Statement stmt = conn.createStatement(); ResultSet rs = null; try { System.out.println("Executando a seguinte query ....."); System.out.println(sql); rs = stmt.executeQuery(sql); System.out.println("Executada com sucesso!"); } catch (SQLException ex) { System.out.println("Query não executada!"); Logger.getLogger(OperacoesBancoDados.class.getName()).log(Level.SEVERE, null, ex); } return rs; } public void executaQuerieSemResultado(Connection conn, String sql) throws ClassNotFoundException, SQLException { Statement stmt = conn.createStatement(); try { System.out.println("Executando a seguinte query ....."); System.out.println(sql); stmt.execute(sql); System.out.println("Executada com sucesso!"); } catch (SQLException ex) { System.out.println("Query não executada!"); Logger.getLogger(OperacoesBancoDados.class.getName()).log(Level.SEVERE, null, ex); } finally { stmt.close(); fecharConexao(conn); } } public void executaQuerieUpdate(Connection conn, String sql) throws ClassNotFoundException, SQLException { Statement stmt = conn.createStatement(); conn.setAutoCommit(false); try { System.out.println("Executando commit da seguinte query ....."); System.out.println(sql); stmt.executeUpdate(sql); conn.commit(); System.out.println("Executada com sucesso!"); } catch (SQLException ex) { ex.printStackTrace(); System.out.println("Query não executada! Efetuando rollback"); conn.rollback(); Logger.getLogger(OperacoesBancoDados.class.getName()).log(Level.SEVERE, null, ex); } finally { stmt.close(); fecharConexao(conn); } } public String getURL() { return URL; } public void setURL(String URL) { this.URL = URL; } public void executaBatchUpdate(Connection conn, ArrayList listaSQLs) throws SQLException, ClassNotFoundException { conn = criaConexao(); Statement stmt = conn.createStatement(); conn.setAutoCommit(false); for (int i = 0; i < listaSQLs.size(); i++) { System.out.println(listaSQLs.get(i)); stmt.addBatch((String) listaSQLs.get(i)); } try { System.out.println("Executando commit em lote ....."); stmt.executeBatch(); conn.commit(); System.out.println("Executada com sucesso!"); } catch (SQLException ex) { System.out.println("Query não executada! Efetuando rollback"); conn.rollback(); Logger.getLogger(OperacoesBancoDados.class.getName()).log(Level.SEVERE, null, ex); } finally { stmt.close(); fecharConexao(conn); } } public void deletaBanco() throws ClassNotFoundException, SQLException{ this.setURL("jdbc:mysql://localhost:3306/"); Connection conn = null; Statement stmt = null; //STEP 3: Open a connection System.out.println("Conectando ao servidor com a seguinte URL : " + this.URL); try { conn = DriverManager.getConnection(URL, USER, PASSWORD); stmt = conn.createStatement(); conn.setAutoCommit(false); System.out.println("DELETANDO BASE DE DADOS sistemaControleContratos"); stmt.execute("DROP DATABASE IF EXISTS sistemaControleContratos"); System.out.println("BASE DE DADOS sistemaControleContratos DELETADA COM SUCESSO!"); conn.commit(); } catch (SQLException ex) { conn.rollback(); Logger.getLogger(OperacoesBancoDados.class.getName()).log(Level.SEVERE, null, ex); } finally { fecharConexao(conn); stmt.close(); } } public String getUSER() { return USER; } public void setUSER(String USER) { this.USER = USER; } public String getPASSWORD() { return PASSWORD; } public void setPASSWORD(String PASSWORD) { this.PASSWORD = PASSWORD; } }
true
1e835266e0860a0abe770f935ba9c59194165ff7
Java
AishwaryaMunde/FundooApp
/FundooNote/src/main/java/com/bridgelabz/fundooapp/dao/IUserDatabase.java
UTF-8
1,231
2.640625
3
[]
no_license
package com.bridgelabz.fundooapp.dao; import java.util.List; import com.bridgelabz.fundooapp.model.Fundoouserdata; public interface IUserDatabase { /**This method is used to fetch data of particular user from database * @param userName is user name entered input * @param userPass is user password entered password */ public String fetch(String userName , String userPass); /**This method save the data entered by user in databse * @param userData is object of Fundoouserdata pojo class */ public Fundoouserdata save(Fundoouserdata userData); /**This method fetch data of particular user where user name sent through * URL which is primary key in database * @param userName is user name sent through URL */ public String fetchById(String userName); /**This method update the particular data in database using unique userName * @param userName is unique key to identify record in database * @param mobileno is field which you wants to update in database */ public String update(String userName , String mobileno); /**This method delete the record from database * @param userName is unique userName to identify record in database */ public String delete(String userName); }
true
831919eba8d2877e107648911ec8cd078b31c62a
Java
chocoai/wy-project
/wuye-pay/wy_cms/src/main/java/com/aibei/action/SporadicAction.java
UTF-8
2,023
1.875
2
[]
no_license
package com.aibei.action; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.aibei.bean.Statistics; import com.aibei.bean.UrlMap; import com.aibei.service.DataBaseService; import com.aibei.thridwy.haolong.bean.GetLXXM; import com.aibei.thridwy.haolong.utils.HaolongService; @Controller @RequestMapping("/sporadic") public class SporadicAction { @Autowired private DataBaseService mDataBaseService; @Autowired private HaolongService haolongService; /*@RequestMapping("index.htm") @ResponseBody public String index(HttpServletRequest request,HttpServletResponse response){ String source = request.getParameter("source"); String wyid = request.getParameter("wyid"); request.getSession().setAttribute("source", source); request.getSession().setAttribute("wyid", wyid); return "success"; }*/ @RequestMapping("getLXXM.htm") @ResponseBody public List<Map<String, String>> getLXXM(String source, HttpServletRequest request,HttpServletResponse response) throws Exception{ List<Map<String, String>> lxxmList = new ArrayList<Map<String, String>>(); if(source!=null && !source.equals("")){ UrlMap urlMap = new UrlMap(); urlMap.setUrlkey(source); urlMap = mDataBaseService.getUrlMap(urlMap).size()>0?mDataBaseService.getUrlMap(urlMap).get(0):null; if(urlMap != null){ GetLXXM getLXXM = new GetLXXM(); getLXXM.setSource(source); getLXXM.setSecretkey(urlMap.getSecretkey()); getLXXM.setSoapActionString(urlMap.getSoapactionstring()); getLXXM.setUrlString(urlMap.getUrlstring()); lxxmList = haolongService.getLXXM(getLXXM); } } return lxxmList; } }
true
3dccd8862d94381f858aeff4b50598e590094a1b
Java
rockguo2015/newmed
/com.fudanmed.platform.core/src/main/java/com/fudanmed/platform/core/domain/proxy/RCReporterDirtyRecordProxy.java
UTF-8
405
1.601563
2
[]
no_license
package com.fudanmed.platform.core.domain.proxy; import com.uniquesoft.gwt.shared.GWTNamedEntity; import edu.fudan.mylang.pf.ProxyTarget; @ProxyTarget("com.fudanmed.platform.core.domain.RCReporterDirtyRecord") public class RCReporterDirtyRecordProxy extends GWTNamedEntity { public RCReporterDirtyRecordProxy() { this.setClazzName("com.fudanmed.platform.core.domain.RCReporterDirtyRecord"); } }
true
9805a0cbe35bca437deb051563db1da42adb46fe
Java
zihenguncle/Technology
/model_community/src/main/java/com/example/community/fragment/CommunityFragment.java
UTF-8
686
1.789063
2
[]
no_license
package com.example.community.fragment; import android.view.View; import com.alibaba.android.arouter.facade.annotation.Route; import com.example.community.R; import com.example.component.base.fragment.BaseNetworkFragment; @Route(path = "/model_community/CommunityFragment") public class CommunityFragment extends BaseNetworkFragment { @Override protected void initData() { } @Override protected void initView(View view) { } @Override protected int getViewById() { return R.layout.community_fragment; } @Override protected void successed(Object data) { } @Override protected void failed(String error) { } }
true
4d765ba2ba610dd5e28c8fb6b2eca8449a7fbaa7
Java
andersonmedeiros/dbcigs
/dbcigs/src/java/model/bean/Endereco.java
UTF-8
2,157
2.3125
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package model.bean; /** * * @author anderson */ public class Endereco { private int id; private String cep, descricao, complemento, pontoreferencia, bairro; private final Cidade cid = new Cidade(); public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCep() { return cep; } public void setCep(String cep) { this.cep = cep; } public String getDescricao() { return descricao; } public void setDescricao(String descricao) { this.descricao = descricao; } public String getComplemento() { return complemento; } public void setComplemento(String complemento) { this.complemento = complemento; } public String getPontoreferencia() { return pontoreferencia; } public void setPontoreferencia(String pontoreferencia) { this.pontoreferencia = pontoreferencia; } public String getBairro() { return bairro; } public void setBairro(String bairro) { this.bairro = bairro; } public int getIdCidade() { return cid.getId(); } public void setIdCidade(int id) { cid.setId(id); } public String getNomeCidade() { return cid.getNome(); } public void setNomeCidade(String nome) { cid.setNome(nome); } public int getIdEstadoCidade() { return cid.getIdEstado(); } public void setIdEstadoCidade(int idEstado) { cid.setIdEstado(idEstado); } public String getNomeEstadoCidade() { return cid.getNomeEstado(); } public void setNomeEstadoCidade(String nomeEstado) { cid.setNomeEstado(nomeEstado); } public String getSiglaEstadoCidade() { return cid.getSiglaEstado(); } public void setSiglaEstadoCidade(String siglaEstado) { cid.setSiglaEstado(siglaEstado); } }
true
5af371c1fad8be5c1808250f23804ddf2b43673e
Java
smahagos/Calorie-Tracker
/app/src/main/java/com/example/surya/fooddiary/ValidationUtils.java
UTF-8
3,262
2.1875
2
[]
no_license
package com.example.surya.fooddiary; import android.content.Context; import android.content.Intent; import android.support.annotation.IntegerRes; import android.widget.EditText; import java.io.File; /** * Created by Administrator on 11/12/2016. */ public class ValidationUtils { Context mContext; public ValidationUtils(Context mContext) { this.mContext = mContext; } public void ValidationUtils() { } public boolean checkLoginValid (EditText emailET, EditText passET) { boolean result = true; if(emailET.getText().toString().equals("")) { result = false; Common.showToast(mContext, "Please input email or name"); return result; } if(passET.getText().toString().equals("")) { result = false; Common.showToast(mContext, "Please input password"); return result; } return result; } public boolean checkSignupValid (EditText emailET, EditText passwdET, EditText confirmPasswdET) { boolean result = true; if(emailET.getText().toString().equals("")) { result = false; Common.showToast(mContext, "Please input email"); return result; } if(passwdET.getText().toString().equals("")) { result = false; Common.showToast(mContext, "Please input password"); return result; } if(confirmPasswdET.getText().toString().equals("")) { result = false; Common.showToast(mContext, "Please input confirm password"); return result; } String passwd = passwdET.getText().toString(); String conpass = confirmPasswdET.getText().toString(); if(!passwd.equals(conpass)) { result = false; Common.showToast(mContext, "Password and confirm password does not match"); return result; } return result; } public boolean checkForgotPassValid (EditText emailET, EditText passwordET, EditText confirmPasswordET) { boolean result = true; if(emailET.getText().toString().equals("")) { result = false; Common.showToast(mContext, "Please input email"); return result; } if(passwordET.getText().toString().equals("")) { result = false; Common.showToast(mContext, "Please input password"); return result; } if(confirmPasswordET.getText().toString().equals("")) { result = false; Common.showToast(mContext, "Please input confirm password"); return result; } if(!passwordET.getText().toString().equals(confirmPasswordET.getText().toString())) { result = false; Common.showToast(mContext, "Please input same passwords"); return result; } return result; } public boolean checkUploadSetting (EditText titleET) { boolean result = true; if(titleET.getText().toString().equals("")) { result = false; Common.showToast(mContext, "Please input title"); return result; } return result; } }
true
227ee200f080f40eefa614afced9a0d4b2f4b2aa
Java
pruebaApp239/empleosApp
/src/main/java/org/edgar/eduardo/repository/PerfilesRepository.java
UTF-8
222
1.65625
2
[]
no_license
package org.edgar.eduardo.repository; import org.edgar.eduardo.model.Perfil; import org.springframework.data.jpa.repository.JpaRepository; public interface PerfilesRepository extends JpaRepository<Perfil, Integer> { }
true
8226f62ec137c9c2334a2ce622f4e7297b45afa4
Java
talelhalevi/3DScene
/src/primitives/Point2D.java
UTF-8
1,305
3.234375
3
[]
no_license
package primitives; public class Point2D { protected Coordinate x; protected Coordinate y; // ***************** Constructors ********************** // public Point2D(Coordinate X, Coordinate Y) { x=new Coordinate(X); y=new Coordinate(Y); } public Point2D() { x=new Coordinate(); y=new Coordinate(); } public Point2D(Point2D p) { x=new Coordinate(p.x); y=new Coordinate(p.y); } // ***************** Getters/Setters ********************** // public Coordinate getX() { return (x); } public void setX(Coordinate x) { this.x = x; } public Coordinate getY() { return (y); } public void setY(Coordinate y) { this.y = y; } // ***************** Administration ******************** // @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Point2D other = (Point2D) obj; if (x == null) { if (other.x != null) return false; } else if (!x.equals(other.x)) return false; if (y == null) { if (other.y != null) return false; } else if (!y.equals(other.y)) return false; return true; } public String toString() { return " (" + x +","+y+")"; } }
true
8ea69abbd49658d5d2c30a6802483f55c8b82c21
Java
rafaelmoreira2503/PrevisaoVendas
/src/main/java/br/com/previsao/repository/Historicos.java
UTF-8
4,812
2.171875
2
[]
no_license
package br.com.previsao.repository; import java.io.Serializable; import java.util.List; import java.util.Map; import javax.inject.Inject; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceException; import javax.persistence.TypedQuery; import br.com.previsao.model.Historico; import br.com.previsao.model.Linha; import br.com.previsao.model.Usuario; import br.com.previsao.security.UsuarioLogado; import br.com.previsao.service.NegocioException; import br.com.previsao.util.jpa.Transactional; public class Historicos implements Serializable { private static final long serialVersionUID = 1L; @Inject private EntityManager manager; public Historico porId(Long id) { return manager.find(Historico.class, id); } @Inject @UsuarioLogado private Usuario usuario; public void guardar(Historico historico) { manager.merge(historico); } @Transactional public void remover(Historico historico) { try { historico = porId(historico.getCodigo()); manager.remove(historico); manager.flush(); } catch (PersistenceException e) { throw new NegocioException("Área não pode ser excluída."); } } public Historico porNome(String nome) { try { return manager.createNamedQuery(Historico.DESCRICAO, Historico.class) .setParameter("descricao", nome.toUpperCase()).getSingleResult(); } catch (NoResultException e) { return null; } } public int countAll(Map<String, String> filtros) { String jpql = Historico.COUNT; jpql = adicionarParametros(filtros, jpql); TypedQuery<Long> query = manager.createNamedQuery(jpql, Long.class); popularParametros(query, filtros); return query.getSingleResult().intValue(); } public List<Historico> buscaPorPaginacao(int posicaoPrimeiraLinha, int maximoPorPagina, String ordernarPeloCampo, String ordernarAscOuDesc, Map<String, String> filtros) { String jpql = Historico.ALL; jpql = adicionarParametros(filtros, jpql); if (ordernarPeloCampo != null && !ordernarPeloCampo.isEmpty()) { if (ordernarAscOuDesc.contains("DESC")) { ordernarAscOuDesc = "DESC"; } else { ordernarAscOuDesc = "ASC"; } jpql += " ORDER BY h." + ordernarPeloCampo + " " + ordernarAscOuDesc; } // metodo buscarPorPaginacao TypedQuery<Historico> query = manager.createNamedQuery(jpql, Historico.class); popularParametros(query, filtros); query.setFirstResult(posicaoPrimeiraLinha); query.setMaxResults(maximoPorPagina); return query.getResultList(); } public int countAllPrevisao(Map<String, String> filtros) { String jpql = Historico.COUNTPREVISAO; jpql = adicionarParametros(filtros, jpql); TypedQuery<Long> query = manager.createNamedQuery(jpql, Long.class); query.setParameter("codigo", usuario.getCodigo()); popularParametros(query, filtros); return query.getSingleResult().intValue(); } public List<Historico> buscaPorPaginacaoPrevisao(int posicaoPrimeiraLinha, int maximoPorPagina, String ordernarPeloCampo, String ordernarAscOuDesc, Linha filtros) { String jpql = "select (p) from Produto p where p.gerenteFilial.codigo=:codigo)"; if (filtros != null){ jpql +="and p.linha.codigo=:codigolinha"; } //jpql = adicionarParametros(filtros, jpql); if (ordernarPeloCampo != null && !ordernarPeloCampo.isEmpty()) { if (ordernarAscOuDesc.contains("DESC")) { ordernarAscOuDesc = "DESC"; } else { ordernarAscOuDesc = "ASC"; } jpql += " ORDER BY h." + ordernarPeloCampo + " " + ordernarAscOuDesc; } // metodo buscarPorPaginacao TypedQuery<Historico> query = manager.createQuery(jpql, Historico.class); query.setParameter("codigo", usuario.getCodigo()); if (filtros != null){ query.setParameter("codigolinha",filtros.getCodigo()); } //popularParametros(query, filtros); query.setFirstResult(posicaoPrimeiraLinha); query.setMaxResults(maximoPorPagina); return query.getResultList(); } // Evitando SQL Injection private void popularParametros(TypedQuery<?> query, Map<String, String> filtros) { for (Map.Entry<String, String> entry : filtros.entrySet()) { query.setParameter(entry.getKey(), "%" + entry.getValue() + "%"); } } private String adicionarParametros(Map<String, String> filtros, String jpql) { if (filtros != null && !filtros.isEmpty()) { jpql += " where "; for (Map.Entry<String, String> entry : filtros.entrySet()) { jpql += entry.getKey() + " like :" + entry.getKey() + " and "; } // remove ultimo and desnecessario jpql = jpql.substring(0, jpql.length() - 4); } return jpql; } public List<Historico> carregaHistorico() { try { return manager.createNamedQuery(Historico.ALL, Historico.class) .getResultList(); } catch (NoResultException e) { return null; } } }
true