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
dc60b5a25d1b783b46b808e2cfde792f6449a1de
Java
SivaKrishnab/AppTesting
/app/src/main/java/com/example/sivakrishna/myapplication/PathResult.java
UTF-8
2,048
2.71875
3
[]
no_license
package com.example.sivakrishna.myapplication; public class PathResult { boolean isPathComplete; boolean isValidColumns; boolean isValidRows; int leastCostSum; int[][] gridPathTotals; int[] pathTaken; public PathResult() { isValidColumns = true; isValidRows = true; isPathComplete = true; } public boolean getIsPathComplete() { return isPathComplete; } public void setPathComplete(boolean isPathComplete) { this.isPathComplete = isPathComplete; } public boolean getIsValidColumns() { return isValidColumns; } public void setIsValidColumns(boolean isValidColumns) { this.isValidColumns = isValidColumns; } public boolean getIsValidRows() { return isValidRows; } public void setIsValidRows(boolean isValidRows) { this.isValidRows = isValidRows; } public int getLeastCostSum() { return leastCostSum; } public void setLeastCostSum(int leastCostSum) { this.leastCostSum = leastCostSum; } public int[][] getGridPathTotals() { return gridPathTotals; } public void setGridPathTotals(int[][] gridPathTotals) { this.gridPathTotals = gridPathTotals; } public int[] getPathTaken() { return pathTaken; } public void setPathTaken(int[] pathTaken) { this.pathTaken = pathTaken; } @Override public String toString() { int[] pathTaken = getPathTaken(); String pathTakenString = ""; for (int i = 0; i < pathTaken.length; i++) { pathTakenString += String.valueOf(pathTaken[i]); if (i < pathTaken.length - 1) { pathTakenString += " "; } } String pathCompleteString; if (isPathComplete) { pathCompleteString = "Yes"; } else { pathCompleteString = "No"; } return pathCompleteString + "\n" + getLeastCostSum() + "\n" + pathTakenString; } }
true
a44c2cdcfbabb542ce6246d2966daf4367f82fbf
Java
andresmorenocivica/CobroCoactivo_v1
/CobroCoactivo/src/java/CobroCoactivo/Persistencia/CivEstadoValorTipoDetcobro.java
UTF-8
3,119
1.992188
2
[]
no_license
package CobroCoactivo.Persistencia; // Generated 30/08/2018 09:56:13 AM by Hibernate Tools 4.3.1 import java.math.BigDecimal; import java.util.Date; import java.util.HashSet; import java.util.Set; /** * CivEstadoValorTipoDetcobro generated by hbm2java */ public class CivEstadoValorTipoDetcobro implements java.io.Serializable { private BigDecimal estvaltipdetcobId; private String estvaltipdetcobDescripcion; private Date estvaltipdetcobFechainicial; private Date estvaltipdetcobFechafinal; private Date estvaltipdetcobFechaproceso; private Set civValorTipoDetalleCobros = new HashSet(0); public CivEstadoValorTipoDetcobro() { } public CivEstadoValorTipoDetcobro(BigDecimal estvaltipdetcobId, String estvaltipdetcobDescripcion) { this.estvaltipdetcobId = estvaltipdetcobId; this.estvaltipdetcobDescripcion = estvaltipdetcobDescripcion; } public CivEstadoValorTipoDetcobro(BigDecimal estvaltipdetcobId, String estvaltipdetcobDescripcion, Date estvaltipdetcobFechainicial, Date estvaltipdetcobFechafinal, Date estvaltipdetcobFechaproceso, Set civValorTipoDetalleCobros) { this.estvaltipdetcobId = estvaltipdetcobId; this.estvaltipdetcobDescripcion = estvaltipdetcobDescripcion; this.estvaltipdetcobFechainicial = estvaltipdetcobFechainicial; this.estvaltipdetcobFechafinal = estvaltipdetcobFechafinal; this.estvaltipdetcobFechaproceso = estvaltipdetcobFechaproceso; this.civValorTipoDetalleCobros = civValorTipoDetalleCobros; } public BigDecimal getEstvaltipdetcobId() { return this.estvaltipdetcobId; } public void setEstvaltipdetcobId(BigDecimal estvaltipdetcobId) { this.estvaltipdetcobId = estvaltipdetcobId; } public String getEstvaltipdetcobDescripcion() { return this.estvaltipdetcobDescripcion; } public void setEstvaltipdetcobDescripcion(String estvaltipdetcobDescripcion) { this.estvaltipdetcobDescripcion = estvaltipdetcobDescripcion; } public Date getEstvaltipdetcobFechainicial() { return this.estvaltipdetcobFechainicial; } public void setEstvaltipdetcobFechainicial(Date estvaltipdetcobFechainicial) { this.estvaltipdetcobFechainicial = estvaltipdetcobFechainicial; } public Date getEstvaltipdetcobFechafinal() { return this.estvaltipdetcobFechafinal; } public void setEstvaltipdetcobFechafinal(Date estvaltipdetcobFechafinal) { this.estvaltipdetcobFechafinal = estvaltipdetcobFechafinal; } public Date getEstvaltipdetcobFechaproceso() { return this.estvaltipdetcobFechaproceso; } public void setEstvaltipdetcobFechaproceso(Date estvaltipdetcobFechaproceso) { this.estvaltipdetcobFechaproceso = estvaltipdetcobFechaproceso; } public Set getCivValorTipoDetalleCobros() { return this.civValorTipoDetalleCobros; } public void setCivValorTipoDetalleCobros(Set civValorTipoDetalleCobros) { this.civValorTipoDetalleCobros = civValorTipoDetalleCobros; } }
true
67da6e030c3b11f3abb704cd060a627b56b57240
Java
sshhyy-mail/DHRM-2197
/src/main/java/com/kingland/dhrm2197/config/SecurityConfig.java
UTF-8
2,816
2.0625
2
[]
no_license
package com.kingland.dhrm2197.config; import com.alibaba.fastjson.JSON; import com.kingland.dhrm2197.mapper.UserMapper; import com.kingland.dhrm2197.service.impl.UserDetailsServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.DisabledException; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.factory.PasswordEncoderFactories; import org.springframework.security.crypto.password.PasswordEncoder; import javax.servlet.http.HttpServletResponse; import javax.sql.DataSource; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { final UserMapper userMapper; @Autowired MyAuthenticationSuccessHandler myAuthenticationSuccessHandler; @Autowired MyAuthenticationFailureHandler myAuthenticationFailureHandler; @Autowired PasswordEncoder passwordEncoder; @Autowired DataSource dataSource; public SecurityConfig(UserMapper userMapper) { this.userMapper = userMapper; } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(new UserDetailsServiceImpl(userMapper)); } @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/register").permitAll() .anyRequest() .authenticated() .and() .formLogin() .successHandler(myAuthenticationSuccessHandler) .failureHandler(myAuthenticationFailureHandler) .and() .formLogin() .and() .csrf().disable() .cors().disable(); } // Pass "/static/**" all request @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/static/**"); } @Bean PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } }
true
d6b0f4ab0268c40e58154f7f5bfe2a2df2c00843
Java
ivanBobrov/hearingCollector
/src/main/java/org/home/hearing/collector/provider/AheadHearingProvider.java
UTF-8
470
2.296875
2
[]
no_license
package org.home.hearing.collector.provider; import org.home.hearing.collector.Hearing; import java.util.List; public class AheadHearingProvider implements HearingProvider { private final int daysLoadAhead; private final String url; public AheadHearingProvider(int daysLoadAhead, String url) { this.daysLoadAhead = daysLoadAhead; this.url = url; } @Override public List<Hearing> getHearings() { return null; } }
true
593e3cfae4fd27ca46d8fd9d9f3af67c0b36447d
Java
pursue-wind/mybatis-plus-sharding-plugin
/mybatis-plus-sharding-plugin/src/main/java/io/github/pursuewind/mybatisplus/plugin/interceptor/DateShardingStrategy.java
UTF-8
1,515
2.359375
2
[ "Apache-2.0" ]
permissive
package io.github.pursuewind.mybatisplus.plugin.interceptor; import io.github.pursuewind.mybatisplus.plugin.support.ShardingStrategy; import org.apache.ibatis.annotations.Param; import java.sql.Timestamp; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.Date; /** * 简单的时间策略 eg: sourceTableName_2020_11 * * @author Chan */ public class DateShardingStrategy implements ShardingStrategy { @Override public String getTableName(String tableName, Object param, Object prefixParam) { if (null == param) { LocalDate now = LocalDate.now(); return tableName + "_" + now.getYear() + "_" + now.getMonth().getValue(); } else { if (param instanceof Timestamp) { return tableName + "_" + (((Date) param).getYear() + 1900) + "_" + (((Date) param).getMonth() + 1); } else if (param instanceof Date) { return tableName + "_" + (((Date) param).getYear() + 1900) + "_" + (((Date) param).getMonth() + 1); } else if (param instanceof LocalDateTime) { return tableName + "_" + ((LocalDateTime) param).getYear() + "_" + ((LocalDateTime) param).getMonth().getValue(); } else if (param instanceof LocalDate) { return tableName + "_" + ((LocalDate) param).getYear() + "_" + ((LocalDate) param).getMonth().getValue(); } else { throw new RuntimeException("类型不支持"); } } } }
true
0676953d7df93f0cbec5fe36ba1376708bc1e517
Java
SAP/olingo-jpa-processor-v4
/jpa/odata-jpa-test/src/main/java/com/sap/olingo/jpa/processor/core/testmodel/DateTimeTest.java
UTF-8
1,031
2.25
2
[ "Apache-2.0" ]
permissive
package com.sap.olingo.jpa.processor.core.testmodel; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.Date; import javax.persistence.Column; import javax.persistence.Convert; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * Test for time conversion * @author Oliver Grande * @since 1.0.1 * Created 2020-10-31 */ @Entity(name = "DateTimeTest") @Table(schema = "\"OLINGO\"", name = "\"BusinessPartner\"") public class DateTimeTest { @Id @Column(name = "\"ID\"") protected String iD; @Column(name = "\"CreatedAt\"", precision = 3, insertable = false, updatable = false) @Convert(converter = DateTimeConverter.class) private LocalDateTime creationDateTime; @Column(name = "\"CreatedAt\"", precision = 9) @Temporal(TemporalType.TIMESTAMP) private Date at; @Column(name = "\"BirthDay\"") private LocalDate birthDay; }
true
4f27aa7a11ea19701ed5bb4de612179453e4a4f5
Java
xie-summer/GWR
/gewara-new/src/main/java/com/gewara/model/movie/CinemaProfile.java
GB18030
7,232
2.125
2
[]
no_license
package com.gewara.model.movie; import java.io.Serializable; import java.sql.Timestamp; import org.apache.commons.lang.StringUtils; import com.gewara.constant.Status; import com.gewara.model.BaseObject; import com.gewara.util.DateUtil; /** * @author acerge(acerge@163.com) * @since 3:05:09 PM Jan 15, 2010 */ public class CinemaProfile extends BaseObject{ private static final long serialVersionUID = -3804714651086763962L; public static final String STATUS_OPEN = "open"; public static final String STATUS_CLOSE = "close"; public static final String POPCORN_STATUS_Y ="Y";//б׻ public static final String POPCORN_STATUS_N ="N";//ûб׻ public static final String SERVICEFEE_Y ="Y";//з public static final String SERVICEFEE_N ="N";//ûз public static final String TAKEMETHOD_P = "P";//ֳ public static final String TAKEMETHOD_W = "W";//ӰԺƱ public static final String TAKEMETHOD_A = "A";//ȡƱ public static final String TAKEMETHOD_U = "U";//Ժ public static final String TAKEMETHOD_L = "L";//¬װӰԺȡƱ public static final String TAKEMETHOD_D = "D";//ԺȡƱ public static final String TAKEMETHOD_J = "J";//ԺȡƱ public static final String TAKEMETHOD_M = "M";//ӰԺԱȡƱ private Long id; //CinemaID private String notifymsg1; //ȡƱ private String notifymsg2; //ǰ3СʱѶ private String takemethod; //ȡƱʽ: PֳͣWӰԺƱڣAԶȡƱ private Long topicid; //ȡƱ private String takeAddress; //ȡƱλ private String opentime; //ÿ쿪ŹƱʱ䣬6:00д 0600 private String closetime; //ÿرչƱʱ private String startsale; //ÿײ͵Ŀʼʱ 0800 private String endsale; //ÿײ͵Ľʱ 2300 private String popcorn; //ǷǺб׻ӰԺ private String servicefee; // private String status; //״̬ private Integer cminute; //ǰ೤ʱر() private Integer openDay; //ǰʱ(磺1 ʾ1) private String openDayTime; //ǰżľʱ(磺6:00д 0600) private Integer fee; // private String isRefund; //ǷƱY or N private String opentype; //ӰԺͣHFH, MTX, DX private String direct; //ǷֱY or N private String prompting; //ʾ˵ @Override public Serializable realId() { return id; } public Integer getFee() { return fee; } public void setFee(Integer fee) { this.fee = fee; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public CinemaProfile(){ } public CinemaProfile(Long cinemaid){ this(); this.opentime = "0000"; this.closetime = "2400"; this.cminute = 60; this.id = cinemaid; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getNotifymsg1() { return notifymsg1; } public void setNotifymsg1(String notifymsg1) { this.notifymsg1 = notifymsg1; } public String getNotifymsg2() { return notifymsg2; } public void setNotifymsg2(String notifymsg2) { this.notifymsg2 = notifymsg2; } public Long getTopicid() { return topicid; } public void setTopicid(Long topicid) { this.topicid = topicid; } public String getTakemethod() { return takemethod; } public void setTakemethod(String takemethod) { this.takemethod = takemethod; } public String getOpentime() { return opentime; } public void setOpentime(String opentime) { this.opentime = opentime; } public String getClosetime() { return closetime; } public void setClosetime(String closetime) { this.closetime = closetime; } public String getStartsale() { return startsale; } public void setStartsale(String startsale) { this.startsale = startsale; } public String getEndsale() { return endsale; } public void setEndsale(String endsale) { this.endsale = endsale; } public String getTakeAddress() { return takeAddress; } public void setTakeAddress(String takeAddress) { this.takeAddress = takeAddress; } public boolean isBuyItem(Timestamp playtime){ if(StringUtils.isNotBlank(startsale) && StringUtils.isNotBlank(endsale)){ String time = DateUtil.format(playtime, "HHmm"); if(time.compareTo(startsale)<0 || time.compareTo(endsale)>0) return false; } return true; } public String getPopcorn() { return popcorn; } public void setPopcorn(String popcorn) { this.popcorn = popcorn; } public String getTakeInfo(){ String result = "λӰԺĸȡƱȡƱ"; if(StringUtils.equals(takemethod, TAKEMETHOD_U)){ result = "λӰԺԺȡƱȡƱ"; }else if(StringUtils.equals(takemethod, TAKEMETHOD_W)){ result = "ӰԺƱȡƱ"; }else if(StringUtils.equals(takemethod, TAKEMETHOD_P)){ result = "ֳ"; }else if(StringUtils.equals(takemethod, TAKEMETHOD_L)){ result = "λӰԺ¬װӰԺȡƱ"; }else if(StringUtils.equals(takemethod, TAKEMETHOD_D)){ result = "λӰԺԺȡƱ"; }else if(StringUtils.equals(takemethod, TAKEMETHOD_J)){ result = "λӰԺĽԺȡƱ"; }else if(StringUtils.equals(takemethod, TAKEMETHOD_M)){ result = "λӰԺӰԺԱȡƱ"; } return result; } public String getServicefee() { return servicefee; } public void setServicefee(String servicefee) { this.servicefee = servicefee; } public Integer getCminute() { return cminute; } public void setCminute(Integer cminute) { this.cminute = cminute; } public String getIsRefund() { return isRefund; } public void setIsRefund(String isRefund) { this.isRefund = isRefund; } public String getDirect() { return direct; } public void setDirect(String direct) { this.direct = direct; } public String getPrompting() { return prompting; } public void setPrompting(String prompting) { this.prompting = prompting; } public boolean hasDirect(){ return StringUtils.equals(this.direct, Status.Y); } public String getOpentype() { return opentype; } public void setOpentype(String opentype) { this.opentype = opentype; } public Integer getOpenDay() { return openDay; } public void setOpenDay(Integer openDay) { this.openDay = openDay; } public String getOpenDayTime() { return openDayTime; } public void setOpenDayTime(String openDayTime) { this.openDayTime = openDayTime; } public boolean hasDefinePaper(){//ȡƱʽǸȡƱҹƱ return StringUtils.isNotBlank(this.takemethod) && CinemaProfile.TAKEMETHOD_A.equals(this.takemethod) && CinemaProfile.STATUS_OPEN.equals(this.status); } }
true
800f5e1667c12833f285ab507f374ed811569211
Java
mjiana/java
/Block.java
UHC
609
3.46875
3
[]
no_license
package chapter10; public class Block { String block = "ٶ "; public static void main(String[] args) { // TODO Auto-generated method stub String block = "Ʈ"; System.out.println("Movie : "+block); int i = 0; { //block in String block2 = " λ"; System.out.println("Movie : "+block2); System.out.println("j = "); for(int j=0; j<5; j++) { System.out.print(j); } System.out.println("\ni = "); for(i=0; i<5; i++) { System.out.print(i); } System.out.println(); }//block out }//main }//class
true
b035d9ce2c2fcf003f4fa91dc180e40e85de8518
Java
amitjoy/Java-8-Practice
/com.amitinside.java8.practice/src/main/java/com/amitinside/java8/design/pattern/command/Client.java
UTF-8
1,440
2.5625
3
[]
no_license
/******************************************************************************* * Copyright 2016 Amit Kumar Mondal * * 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.amitinside.java8.design.pattern.command; public final class Client { public static void main(final String[] args) { final Macro macro = new Macro(); final Editor editor = new MockEditor(); final Command openCommand = new Open(editor); final Command saveCommand = new Save(editor); macro.record(openCommand); macro.record(saveCommand); macro.run(); // 1st way macro.record(() -> new Open(editor)); macro.record(() -> new Save(editor)); macro.run(); // 2nd way macro.record(() -> editor.open()); macro.record(() -> editor.save()); macro.run(); // 3rd way macro.record(editor::open); macro.record(editor::save); macro.run(); // 4th way } }
true
a43128e2852cd498c38664ce6847cce7774f363f
Java
TuInexplicable/communityTest
/src/main/java/com/icss/hotel/service/impl/RoomServiceImpl.java
UTF-8
1,069
1.953125
2
[]
no_license
package com.icss.hotel.service.impl; import com.icss.hotel.dao.RoomMapper; import com.icss.hotel.domain.Room; import com.icss.hotel.service.RoomService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; import java.util.Map; @Service public class RoomServiceImpl implements RoomService { @Resource private RoomMapper roomMapper; @Override public List<Map> queryAllRoom() { return roomMapper.queryAllRoom(); } @Override public int addRoom(Room room) { return roomMapper.addRoom(room); } @Override public List<Map> selectAllRoom_0() { return roomMapper.selectAllRoom_0(); } @Override public Integer delRoomByTno(Integer tno) { return roomMapper.delRoomByTno(tno); } @Override public Integer updataRoomState(Integer rno, Integer rstate) { return roomMapper.updataRoomState(rno, rstate); } }
true
d6e05cda783b538e6a8b1264d09c158e35be1559
Java
sec00/osee-4
/plugins/org.eclipse.osee.ats.client.integration.tests/src/org/eclipse/osee/ats/client/integration/tests/ats/dialog/ActionableItemTreeWithChildrenDialogTest.java
UTF-8
1,257
1.835938
2
[]
no_license
/******************************************************************************* * Copyright (c) 2014 Boeing. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Boeing - initial API and implementation *******************************************************************************/ package org.eclipse.osee.ats.client.integration.tests.ats.dialog; import org.eclipse.osee.ats.util.widgets.dialog.ActionableItemTreeWithChildrenDialog; import org.eclipse.osee.framework.core.enums.Active; import org.junit.Assert; import org.junit.Test; /** * @author Donald G. Dunne */ public class ActionableItemTreeWithChildrenDialogTest { @Test public void testNewActionWizard() { ActionableItemTreeWithChildrenDialog dialog = new ActionableItemTreeWithChildrenDialog(Active.Active); try { dialog.setBlockOnOpen(false); dialog.open(); int count = dialog.getTreeViewer().getViewer().getTree().getItemCount(); Assert.assertTrue(count >= 5); } finally { dialog.close(); } } }
true
0301e2ede3066d462e7530a4ec6fb166ee02425f
Java
LukasBoril/OOP21_BachmannMaster
/src/main/java/ch/zhaw/exercise/le03b/task4/Test1.java
UTF-8
439
3.109375
3
[]
no_license
package ch.zhaw.exercise.le03b.task4; public class Test1 { public static void main(String[] args) { int[] intarr = new int[4]; for (int i = 0; i < 8; i++) { try { intarr[i] = i; System.out.println(intarr[i]); //throw new NullPointerException(); } catch (ArrayIndexOutOfBoundsException e) { System.out.println(e.getClass().getName()); System.out.println("Index zu gross: " + e.getMessage()); } } } }
true
45045f1b939ee855bc9b25061c4fb369f46f5062
Java
KamilZemczak/StudentApp
/src/test/java/com/project/service/StudentService_createTest.java
UTF-8
4,122
2.5
2
[]
no_license
package com.project.service; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.when; import static org.mockito.Mockito.verify; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.RandomUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import com.project.dao.StudentRepository; import com.project.model.Student; @RunWith(MockitoJUnitRunner.class) public class StudentService_createTest { @InjectMocks private final StudentServiceImpl testedService = new StudentServiceImpl(); @Mock private Student student; @Mock private StudentRepository studentRepository; public static final String DATE_PATTERN = "dd/MM/yyyy"; private final String firstName = RandomStringUtils.randomAlphabetic(6); private final String lastName = RandomStringUtils.randomAlphabetic(6); private final String className = RandomStringUtils.randomAlphabetic(6); private final String streetAdress = RandomStringUtils.randomAlphabetic(6); private final String houseNumber = RandomStringUtils.randomAlphabetic(6); private final String city = RandomStringUtils.randomAlphabetic(6); private final String zipCode = RandomStringUtils.randomAlphabetic(6); private final String pesel = "90090515836"; private final Date dateOfBirth = stringToDate("28/09/1995"); private final Boolean dyslexia = RandomUtils.nextBoolean(); @Before public void setUp() { when(student.getFirstName()).thenReturn(firstName); when(student.getLastName()).thenReturn(lastName); when(student.getClassName()).thenReturn(className); when(student.getStreetAdress()).thenReturn(streetAdress); when(student.getHouseNumber()).thenReturn(houseNumber); when(student.getCity()).thenReturn(city); when(student.getZipCode()).thenReturn(zipCode); when(student.getPesel()).thenReturn(pesel); when(student.getDateOfBirth()).thenReturn(dateOfBirth); when(student.getDyslexia()).thenReturn(dyslexia); when(studentRepository.save(student)).thenReturn(student); } @After public void clean() { reset(student, studentRepository); } @Test public void correctData_create() { final Student result = testedService.create(student); assertNotNull(result); assertEquals(firstName, result.getFirstName()); assertEquals(lastName, result.getLastName()); assertEquals(className, result.getClassName()); assertEquals(streetAdress, result.getStreetAdress()); assertEquals(houseNumber, result.getHouseNumber()); assertEquals(city, result.getCity()); assertEquals(zipCode, result.getZipCode()); assertEquals(pesel, result.getPesel()); assertEquals(dateOfBirth, result.getDateOfBirth()); assertEquals(dyslexia, result.getDyslexia()); verify(studentRepository).save(result); } @Test public void getDateByPesel_correct() { final String pesel = "90090515836"; final Date date = stringToDate("05/09/1990"); when(student.getPesel()).thenReturn(pesel); when(student.getDateOfBirth()).thenReturn(date); final Student result = testedService.create(student); assertEquals(date, result.getDateOfBirth()); } private static Date stringToDate(final String value, final SimpleDateFormat formatter) { try { return formatter.parse(value); } catch (ParseException | NullPointerException e) { return null; } } private static Date stringToDate(final String value) { final SimpleDateFormat formatter = new SimpleDateFormat(DATE_PATTERN); return stringToDate(value, formatter); } }
true
296528376428d44ff0e93920933b19f211d1e465
Java
jyril81/blog.svpino
/hanoi/src/test/java/com/jyril/HanoiTest.java
UTF-8
875
3.03125
3
[]
no_license
package com.jyril; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * Created by jyril81 on 13.06.2015. */ public class HanoiTest { @Test public void noDisksIsNoMoves() throws Exception { assertEquals(0, Hanoi.classicHanoi(0, 1, 3, 2, 0)); } @Test public void onwDiskIsOneMove() throws Exception { assertEquals(1, Hanoi.classicHanoi(1, 1, 3, 2, 0)); } @Test public void twoDisksIs3Moves() throws Exception { assertEquals(3, Hanoi.classicHanoi(2, 1, 3, 2, 0)); } @Test public void threeDisksIs7Moves() throws Exception { assertEquals(7, Hanoi.classicHanoi(3, 1, 3, 2, 0)); } @Test public void nDisksIs2PowernMinus1() throws Exception { int nrDisks = 10; assertEquals((int) Math.pow(2, 10) - 1, Hanoi.classicHanoi(10, 1, 3, 2, 0)); } }
true
62412e42d48f6e3410c4f1c2f494d289e054907a
Java
insecthunter/open-source
/elastic-job/code/elasticjob-lite/src/main/java/com/simba/elasticjob/executor/item/dataflow/DataflowJobProperties.java
UTF-8
317
1.765625
2
[]
no_license
package com.simba.elasticjob.executor.item.dataflow; /** * Dataflow job properties. 数据流作业的属性信息 */ public final class DataflowJobProperties { /** * Whether use stream mode to process dataflow job. */ public static final String STREAM_PROCESS_KEY = "streaming.process"; }
true
b9b997a93d271a99cde331abc345e9e38a9957ee
Java
kyungilll/bigdatajava
/java24/src/인터페이스/MemberInterface.java
UTF-8
756
2.796875
3
[]
no_license
package 인터페이스; public interface MemberInterface { // 문법적으로 강제성있게 기능을 추상메소드로 정의 (구체적이지 않은, 불완전한) public abstract void insert(MemberDTO dto); void delete(String id); void update(MemberDTO dto); MemberDTO select(String id); // 위 메소드가 반드시 구현되어야 한다. // 이름, 반환값 등만 반드시 입력되어있어야 함 // 정확하게 구현하지 않음 // 기능만 정의하다보니 일반변수,일반메소드 사용불가 // > 상수는 사용가능 // 기능을 메소드로 정의 // 인터페이스는 객체를 생성하여 쓸 수 없다 // interface name = new interface(); > 식으로 쓸 수 없음 }
true
3f309396a838d68e91087d70cb4e193254319c03
Java
herbert1228/test
/src/yr2/sem1/lab05/TestAccount.java
UTF-8
322
2.8125
3
[]
no_license
package yr2.sem1.lab05; public class TestAccount { public static void main(String[] args) { Account myAccount = new Account("Kitty", 3.5); String aName = myAccount.getHolderName(); System.out.println("The holder name is " + aName); System.out.println(myAccount); } }
true
513a4c601a21e9b44403bb62f14681faecc05f74
Java
RihabGharbii/ForumBackend
/src/main/java/org/sid/web/QuestionRestService.java
UTF-8
1,476
2.3125
2
[]
no_license
package org.sid.web; import java.util.List; import java.util.Optional; import org.sid.dao.QuestionRepository; import org.sid.entities.Question; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @CrossOrigin(origins="*",maxAge=3600) @RestController public class QuestionRestService { @Autowired private QuestionRepository questionRepository; @RequestMapping(value="/Questions",method=RequestMethod.GET) public List<Question> getquestion(){ return questionRepository.findAll(); } @RequestMapping(value="/Questions/{Q_id}",method=RequestMethod.GET) public Optional<Question> getquestions(@PathVariable Long Q_id){ return questionRepository.findById(Q_id); } @RequestMapping(value="/Questions",method=RequestMethod.POST) public Question save(@RequestBody Question q){ System.out.println(q.getE_contenent()+" "+q.getNb_comment()); return questionRepository.save(q); } @RequestMapping(value="/Questions/{Q_id}",method=RequestMethod.DELETE) public boolean supprimer(@PathVariable Long Q_id){ questionRepository.deleteById(Q_id); return true; } }
true
ca31033d2a54af30b8c2e481bf76984d24b46f39
Java
askellio/fastPizza
/PizzaClient/app/src/main/java/com/example/askellio/pizzaclient/activities/InfoOrderActivity.java
UTF-8
2,167
2.359375
2
[]
no_license
package com.example.askellio.pizzaclient.activities; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.widget.TextView; import com.example.askellio.pizzaclient.R; import com.example.askellio.pizzaclient.adapters.OrderAdapter; import com.example.askellio.pizzaclient.adapters.PizzaFromOrderAdapter; import com.example.askellio.pizzaclient.structs.StructOrder; import com.example.askellio.pizzaclient.structs.StructPizzaFromOrder; import java.util.List; public class InfoOrderActivity extends AppCompatActivity { private StructOrder order; private RecyclerView rv; private LinearLayoutManager manager; private PizzaFromOrderAdapter adapter; TextView txtSummary; TextView txtDate; TextView txtAddress; TextView txtId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_info_order); Intent intent = getIntent(); if (intent != null) { order = (StructOrder) intent.getSerializableExtra("order"); rv = (RecyclerView) findViewById(R.id.rvPizzaFromOrder); manager = new LinearLayoutManager(this); adapter = new PizzaFromOrderAdapter(this); rv.setLayoutManager(manager); rv.setAdapter(adapter); txtId = (TextView) findViewById(R.id.txtOrderId); txtSummary = (TextView) findViewById(R.id.txtOrderSummary); txtDate = (TextView) findViewById(R.id.txtOrderDate); txtAddress = (TextView) findViewById(R.id.txtOrderAddress); txtId.setText(Integer.toString(order.getId())); txtAddress.setText(order.getAddress()); txtDate.setText(order.getDate().toString()); txtSummary.setText(Double.toString(order.getSummary())); } } public void setData (List<StructPizzaFromOrder> pizzas) { adapter.setData(pizzas); adapter.notifyDataSetChanged(); } }
true
e0a1917912e74b646c9575cdf25db613188a9944
Java
Goldenbullet/presentationCODE
/express28/express-client/src/main/java/express/businessLogic/stub/PaymentBLService_stub.java
UTF-8
832
2.265625
2
[]
no_license
package express.businessLogic.stub; import express.businesslogicService.financialBLService.PaymentBLService; import express.vo.DateAvailableVO; import express.vo.PaymentDocVO; public class PaymentBLService_stub implements PaymentBLService{ PaymentDocVO payment; public PaymentBLService_stub(PaymentDocVO payment){ this.payment=payment; } public boolean addPaymentDoc(PaymentDocVO payment){ System.out.println("Add payment"); return true; } public PaymentDocVO getPaymentDoc(String id){ System.out.println("Get payment"); return payment; } public DateAvailableVO checkDateAvailable(String date){ if(date.equals("2015-10-26")) return DateAvailableVO.Found; else return DateAvailableVO.NotFound; } public void endPaymentDoc(){ System.out.println("2015-10-25 10:50:40"+"管理成本"); } }
true
ff99a0f7e780706a284901ba5c3a43cbb0d2d3aa
Java
douglasmen/ge
/ge_comuns/src/main/java/com/consisti/sisgesc/entidade/MovimentoDia.java
UTF-8
3,280
2.078125
2
[]
no_license
package com.consisti.sisgesc.entidade; import java.math.BigDecimal; import java.util.Date; import javax.persistence.Column; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.MappedSuperclass; import javax.persistence.Temporal; import javax.persistence.TemporalType; import com.powerlogic.jcompany.dominio.tipo.PlcSimNao; import com.powerlogic.jcompany.dominio.valida.PlcValidacaoUnificada; @SuppressWarnings("serial") @MappedSuperclass @PlcValidacaoUnificada public abstract class MovimentoDia extends AppBaseEntity { @Id @GeneratedValue(strategy=GenerationType.AUTO, generator = "SE_MOVIMENTO_DIA") @Column (name = "ID_MOVIMENTO_DIA", nullable=false, length=5) private Long id; @Column (name = "SALDO_DIA", nullable=false, length=19) private BigDecimal saldoDia; @Column (name = "TOTAL_ENTRADA", nullable=false, length=19) private BigDecimal totalEntrada; @Column (name = "TOTAL_SAIDA", nullable=false, length=19) private BigDecimal totalSaida; @Column (name = "SALDO_TOTAL", nullable=false, length=19) private BigDecimal saldoTotal; @Column (name = "VALOR_RETIRADA", length=19) private BigDecimal valorRetirada; @Column (name = "DATA_MOVIMENTO", nullable=false, length=11) @Temporal(TemporalType.TIMESTAMP) private Date dataMovimento; @Column (name = "SALDO_DIA_ANTERIOR", length=10, precision=10, scale=2) private BigDecimal saldoDiaAnterior; @Enumerated(EnumType.STRING) @Column (name = "CAIXA_FECHADO", length=1) private PlcSimNao caixaFechado; @Column (name = "DATA_FECHAMENTO", length=11) @Temporal(TemporalType.TIMESTAMP) private Date dataFechamento; public Long getId() { return id; } public void setId(Long id) { this.id=id; } public BigDecimal getSaldoDia() { return saldoDia; } public void setSaldoDia(BigDecimal saldoDia) { this.saldoDia=saldoDia; } public BigDecimal getTotalEntrada() { return totalEntrada; } public void setTotalEntrada(BigDecimal totalEntrada) { this.totalEntrada=totalEntrada; } public BigDecimal getTotalSaida() { return totalSaida; } public void setTotalSaida(BigDecimal totalSaida) { this.totalSaida=totalSaida; } public BigDecimal getSaldoTotal() { return saldoTotal; } public void setSaldoTotal(BigDecimal saldoTotal) { this.saldoTotal=saldoTotal; } public Date getDataMovimento() { return dataMovimento; } public void setDataMovimento(Date dataMovimento) { this.dataMovimento=dataMovimento; } public BigDecimal getValorRetirada() { return valorRetirada; } public void setValorRetirada(BigDecimal valorRetirada) { this.valorRetirada = valorRetirada; } public BigDecimal getSaldoDiaAnterior() { return saldoDiaAnterior; } public void setSaldoDiaAnterior(BigDecimal saldoDiaAnterior) { this.saldoDiaAnterior = saldoDiaAnterior; } public PlcSimNao getCaixaFechado() { return caixaFechado; } public void setCaixaFechado(PlcSimNao caixaFechado) { this.caixaFechado = caixaFechado; } public Date getDataFechamento() { return dataFechamento; } public void setDataFechamento(Date dataFechamento) { this.dataFechamento = dataFechamento; } }
true
72ad91d318848345de3c8a977ed9e96cbe5f723f
Java
b-alina/n26
/n26-statistics/src/main/java/com/aballa/n26/statistics/service/StatisticsService.java
UTF-8
173
1.632813
2
[]
no_license
package com.aballa.n26.statistics.service; import com.aballa.n26.statistics.model.Statistics; public interface StatisticsService { Statistics getStatistics(); }
true
c5ebd71b9c16df0069962c1b1f5691cd44e61cc5
Java
lukcho/subastas
/subastas/src/main/java/subastas/controller/access/test.java
UTF-8
1,707
2.015625
2
[]
no_license
package subastas.controller.access; //import org.json.simple.JSONArray; //import org.json.simple.JSONObject; // //import com.google.gson.JsonArray; // //import subastas.model.dao.entities.Persona; //import subastas.model.generic.ConsumeREST; //import subastas.model.manager.ManagerCarga; //import subastas.model.manager.ManagerGestion; public class test { public static void main(String[] args) { // // TODO Auto-generated method stub // // http://yachay-ws.yachay.gob.ec/data/WSParametrosEntity // // ManagerCarga mg = new ManagerCarga(); // ManagerGestion mges = new ManagerGestion(); // try { //// String a = "aquina"; //// Persona per = mg.funcionarioByDNI(a); //// System.out.println(per.getPerNombres() + " " //// + per.getPerApellidos()); // // Integer item_id = 15; // System.out.println(item_id); // Integer automatico = mges.ofertaXItem(item_id); // System.out.println("no sale nada : "+automatico); // // mges.ganadorItemAutom(item_id, "I",mges.itemByID(item_id),automatico); // } catch (Exception e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } int numeroAleatorio = (int)Math.round(Math.random()*1); int numeroAleatorio1 = (int)Math.round(Math.random()*0); if(numeroAleatorio1 < numeroAleatorio){ System.out.println("valor real"); }else { System.out.println("valor nada"); } // try { // System.out.println(ConsumeREST // .consumeGetRestEasyObject("http://yachay-ws.yachay.gob.ec/data/WSParametrosEntity/SRV_IMG_SYS_SUBASTAS") // .get("parValor")); // } catch (Exception e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } } }
true
b3d21163713a0bdfdcce329e9b2e5a99c2bca449
Java
rohankumardubey/code-DataStructures
/data-structures/src/interview_questions/Poison.java
UTF-8
2,109
3.3125
3
[]
no_license
package interview_questions; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Stack; public class Poison { static class pair { int a; int b; public pair(int a, int b) { this.a = a; this.b = b; } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Integer n = 0; if ( scanner.hasNext()){ n = scanner.nextInt(); } while (n-- > 0) { List<Integer> arr = new ArrayList<>(); for (int i = 0; i < n; i++) { arr.add(scanner.nextInt()); } Stack<pair> s = new Stack<>(); int maxa = 0; for (int i = 0; i < n; i++) { if (s.empty()) { s.push(new pair(arr.get(i), 0)); } else { pair temp = s.peek(); if (arr.get(i) < temp.a) { int sc = 1; maxa = Math.max(maxa, sc); s.push(new pair(arr.get(i), sc)); } else { pair v = s.peek(); int pr = v.b; while (!s.empty() && v.a <= arr.get(i)) { s.pop(); if (s.empty()) break; pr = Math.max(pr, v.b); v = s.peek(); } if (s.empty()) { s.push(new pair(arr.get(i), 0)); } else { s.push(new pair(arr.get(i), pr + 1)); maxa = Math.max(maxa, pr + 1); } } } } System.out.println(maxa); } } }
true
c6a9f5771034bf2e06c0d44ea7f899238bfddc3f
Java
rw2409/LeetCode
/algo/src/wr/leetcode/algo/paint_house_ii/Solution.java
UTF-8
4,016
3.390625
3
[]
no_license
package wr.leetcode.algo.paint_house_ii; public class Solution { private int minIndex(int[][] dp, int i, int ignore) { int min = Integer.MAX_VALUE; int index = -1; int k = dp[i].length; for (int j = 0; j < k; ++j) { if(j != ignore && dp[i][j] < min) { min = dp[i][j]; index = j; } } return index; } public int minCostII(int[][] costs) { int ret = 0; if ( costs.length > 0 && costs[0].length > 0) { int n = costs.length; int k = costs[0].length; int[][] dp = new int[n][k]; int minIndex = 0; int secondMin = 0; for (int i = 0; i < n; ++i) { for (int j = 0; j < k; ++j) { dp[i][j] += costs[i][j]; if( i == 0) { continue; } if(1 == k) { dp[i][j] += dp[i-1][j]; } else if( j == minIndex ) { dp[i][j] += dp[i-1][secondMin]; } else { dp[i][j] += dp[i-1][minIndex]; } } minIndex = minIndex(dp, i, -1); secondMin = minIndex(dp, i, minIndex); } ret = dp[n-1][minIndex]; } return ret; } /* public int minCostII(int[][] costs) { int ret = 0; if( null != costs && 0 < costs.length && costs[0].length > 0) { int n = costs.length; int k = costs[0].length; int [][] minCosts = new int[k][2]; for (int i = 1; i <= n; ++i ) { int minColor = minColor(i-1, -1, minCosts); int subColor = minColor(i-1, minColor, minCosts); for (int color = 0; color < k; ++color) { int prev; if(color == minColor) { prev = minCosts[subColor][(i-1)%2]; } else { prev = minCosts[minColor][(i-1)%2]; } minCosts[color][i%2] = prev + costs[i-1][color]; } } int lastColor = minColor(n, -1, minCosts); ret = minCosts[lastColor][n%2]; } return ret; } int minColor( int day, int skipColor, int[][] minCosts ) { int k = minCosts.length; int minColor = 0; if( k > 1 ) { int minValue = Integer.MAX_VALUE; minColor = -1; for (int color = 0; color < minCosts.length; ++color) { if(skipColor != color && minCosts[color][day%2] < minValue ) { minValue = minCosts[color][day%2]; minColor = color; } } } return minColor; } public static void main(String[] args) { int[][] arr = {{8}}; Solution sol = new Solution(); System.out.println(sol.minCostII(arr)); } //BUG: Wrong fix int minColor( int day, int skipColor, int[][] minCosts ) { int minValue = minCosts[0][day%2]; int minColor = 0; for (int color = 1; color < minCosts.length; ++color) { if(skipColor != color && minCosts[color][day%2] < minValue ) { minValue = minCosts[color][day%2]; minColor = color; } } return minColor; }*/ //BUG: cannot deal with single color, single day /* int minColor( int day, int skipColor, int[][] minCosts ) { int minValue = Integer.MAX_VALUE; int minColor = -1; for (int color = 0; color < minCosts.length; ++color) { if(skipColor != color && minCosts[color][day%2] < minValue ) { minValue = minCosts[color][day%2]; minColor = color; } } return minColor; }*/ }
true
f3d5f4f1cfa2153179b561afdb5d53b85bdc8bcc
Java
xiaoxiaoyangyang/elastic-springboot
/src/main/java/com/example/createdata/entity/RegionInfo.java
UTF-8
553
1.929688
2
[]
no_license
package com.example.createdata.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * * @ClassName: RegionInfo * @Description: 区域详情 * @author liufulu_vendor * @date 2018年9月7日 * */ @Data @NoArgsConstructor @AllArgsConstructor public class RegionInfo { /** * 区域id */ private String regionId; /** * 区域名称 */ private String regionName; /** * 区域所在楼层id */ private String floorId; /** * 区域所在楼层 */ private String floorName; }
true
a1270badf1d3572ef7ca77110967a869e4bac95d
Java
abdullah230695/face-collage-maker-master
/dauroiimageprocessing/src/main/java/dauroi/com/imageprocessing/filter/blend/SourceOverBlendFilter.java
UTF-8
999
2.59375
3
[ "Apache-2.0" ]
permissive
package dauroi.com.imageprocessing.filter.blend; import dauroi.com.imageprocessing.filter.TwoInputFilter; public class SourceOverBlendFilter extends TwoInputFilter { public static final String SOURCE_OVER_BLEND_FRAGMENT_SHADER = "precision highp float;\n" + "varying highp vec2 textureCoordinate;\n" + " varying highp vec2 textureCoordinate2;\n" + " \n" + " uniform sampler2D inputImageTexture;\n" + " uniform sampler2D inputImageTexture2;\n" + " \n" + " void main()\n" + " {\n" + " lowp vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);\n" + " lowp vec4 textureColor2 = texture2D(inputImageTexture2, textureCoordinate);\n" + " \n" + " gl_FragColor = mix(textureColor, textureColor2, textureColor2.a);\n" + " }"; public SourceOverBlendFilter() { super(SOURCE_OVER_BLEND_FRAGMENT_SHADER); } }
true
5096468a244c65256a13e9115ef692a72058c63e
Java
juliasad18/learningJava
/src/com/wall/Application.java
UTF-8
889
2.71875
3
[]
no_license
package com.wall; import com.bank.BankAccount; import com.bank.VipCustomer; public class Application { public static void main(String[] args) { System.out.println("____________________________________________________________"); System.out.println(" "); Wall wall = new Wall(5, 4); System.out.println(wall.getArea()); wall.setHeight(-1.5); System.out.println(wall.getWidth()); System.out.println(wall.getHeight()); System.out.println(wall.getArea()); Wall wall2 = new Wall(-1.5, 2); System.out.println(wall2.getWidth()); System.out.println(wall2.getHeight()); System.out.println(wall2.getArea()); Wall wall3 = new Wall(1.5, 2); System.out.println(wall3.getWidth()); System.out.println(wall3.getHeight()); System.out.println(wall3.getArea()); } }
true
7d500fca054e39aa68cdf952f631c544fc2fda0b
Java
fcas/dev-sys-mobile-project
/DM_UFRN/src/dao/DAOTarefa.java
UTF-8
5,932
2.171875
2
[]
no_license
package dao; import java.util.ArrayList; import java.util.List; import model.Comentarios; import model.Tarefas; import activities.DataCalculos; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.util.Log; public class DAOTarefa { private SQLiteDatabase database; private MySQLiteHelper dbHelper; private DAOLugar daoLugar; @SuppressWarnings("unused") private String[] allColumns = { MySQLiteHelper.COLUNA_ID, Tarefas.COLUNA_USUARIO, Tarefas.COLUNA_ID_LUGAR, Tarefas.COLUNA_DATA, Tarefas.COLUNA_HORARIO, Tarefas.COLUNA_DESCRICAO }; public DAOTarefa(Context context) { dbHelper = new MySQLiteHelper(context); daoLugar = new DAOLugar(context); } public void open() throws SQLException { database = dbHelper.getWritableDatabase(); } public void close() { dbHelper.close(); } public Tarefas createTarefa(Tarefas tarefa) { ContentValues values = new ContentValues(); values.put(MySQLiteHelper.COLUNA_ID, tarefa.getId()); values.put(Tarefas.COLUNA_USUARIO, tarefa.getUsuario()); values.put(Tarefas.COLUNA_ID_LUGAR, tarefa.getLugar().getId_local()); values.put(Tarefas.COLUNA_DATA, DataCalculos.visaoToBanco(tarefa.getData())); values.put(Tarefas.COLUNA_HORARIO, tarefa.getHorario()); values.put(Tarefas.COLUNA_DESCRICAO, tarefa.getDescricao()); @SuppressWarnings("unused") long insertId = database.insert(Tarefas.TABELA_TAREFA, null, values); return tarefa; } public Tarefas updateTarefa(Tarefas tarefa) { Log.d("Nova Data", tarefa.getData()); Log.d("ID Tarefa", String.valueOf(tarefa.getId())); String strFilter = MySQLiteHelper.COLUNA_ID + "='" + tarefa.getId() + "'"; ContentValues args = new ContentValues(); args.put(Tarefas.COLUNA_DESCRICAO, tarefa.getDescricao()); args.put(Tarefas.COLUNA_ID_LUGAR, tarefa.getLugar().getId_local()); args.put(Tarefas.COLUNA_DATA, DataCalculos.visaoToBanco(tarefa.getData())); args.put(Tarefas.COLUNA_HORARIO, tarefa.getHorario()); // args.put(Tarefas.COLUNA_LOCAL, tarefa.getLocal()); database.update(Tarefas.TABELA_TAREFA, args, strFilter, null); return tarefa; } public void deleteTarefa(Tarefas tarefa) { long id = tarefa.getId(); System.out.println("Tarefa deleted with id: " + id); database.delete(Tarefas.TABELA_TAREFA, MySQLiteHelper.COLUNA_ID + " = " + id, null); } public List<Tarefas> getFutureTasksByUser(String userLogin) { List<Tarefas> tarefas = new ArrayList<Tarefas>(); Log.d("Login-Parametro", userLogin); String now = DataCalculos.dataHoraAtual(); String[] dataHora = new String[2]; dataHora = now.split(" "); Cursor cursor = database.rawQuery("Select * from " + Tarefas.TABELA_TAREFA + " where Usuario = ? and Data >= ? order by Data, Horario", new String[] { userLogin , dataHora[0]}); cursor.moveToFirst(); while (!cursor.isAfterLast()) { Tarefas tarefa = cursorToTarefa(cursor); Log.d("Login", tarefa.getUsuario()); Log.d("Data", DataCalculos.bancoToVisao(tarefa.getData())); Log.d("Hora", tarefa.getHorario()); Log.d("Descricao", tarefa.getDescricao()); tarefa.setData(DataCalculos.bancoToVisao(tarefa.getData())); tarefas.add(tarefa); cursor.moveToNext(); } // Make sure to close the cursor cursor.close(); return tarefas; } public List<Tarefas> getAllTasks() { List<Tarefas> tarefas = new ArrayList<Tarefas>(); /* * Cursor cursor = database.query(Tarefas.TABELA_TAREFA, allColumns, * null, null, null, null, null); */ Cursor cursor = database.rawQuery("Select * from " + Tarefas.TABELA_TAREFA + " order by Data, Horario", null); cursor.moveToFirst(); while (!cursor.isAfterLast()) { Tarefas tarefa = cursorToTarefa(cursor); Log.d("Login", tarefa.getUsuario()); Log.d("Data", DataCalculos.bancoToVisao(tarefa.getData())); Log.d("Hora", tarefa.getHorario()); Log.d("Descricao", tarefa.getDescricao()); tarefa.setData(DataCalculos.bancoToVisao(tarefa.getData())); tarefas.add(tarefa); cursor.moveToNext(); } // Make sure to close the cursor cursor.close(); return tarefas; } public List<Tarefas> getTasksByUser(String userLogin) { List<Tarefas> tarefas = new ArrayList<Tarefas>(); /* * Cursor cursor = database.query(Tarefas.TABELA_TAREFA, allColumns, * null, null, null, null, null); */ Log.d("Login-Parametro", userLogin); Cursor cursor = database.rawQuery("Select * from " + Tarefas.TABELA_TAREFA + " where Usuario = ? order by Data, Horario", new String[] { userLogin }); cursor.moveToFirst(); while (!cursor.isAfterLast()) { Tarefas tarefa = cursorToTarefa(cursor); Log.d("Login", tarefa.getUsuario()); Log.d("Data", DataCalculos.bancoToVisao(tarefa.getData())); Log.d("Hora", tarefa.getHorario()); Log.d("Descricao", tarefa.getDescricao()); tarefa.setData(DataCalculos.bancoToVisao(tarefa.getData())); tarefas.add(tarefa); cursor.moveToNext(); } // Make sure to close the cursor cursor.close(); return tarefas; } private Tarefas cursorToTarefa(Cursor cursor) { daoLugar.open(); Tarefas tarefa = new Tarefas(); tarefa.setId(cursor.getLong(0)); tarefa.setUsuario(cursor.getString(1)); tarefa.setLugar(daoLugar.getLugarById(cursor.getInt(2))); tarefa.setData(cursor.getString(3)); tarefa.setHorario(cursor.getString(4)); tarefa.setDescricao(cursor.getString(5)); daoLugar.close(); return tarefa; } public void atualizarTarefas(List<Tarefas> tarefas){ open(); database.delete(Tarefas.TABELA_TAREFA, null, null); for(int i = 0; i < tarefas.size(); i++){ createTarefa(tarefas.get(i)); } } }
true
39466ca36cd6934df8e071239b8e07b161f2ac47
Java
LyMarita/Android
/Class_Family.java
UTF-8
2,451
2.609375
3
[]
no_license
package com.rupp.mrt.ditionary; import android.app.Activity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; public class Class_Family extends BaseAdapter { private final Activity context; private final String[] names; static class ViewHolder{ public TextView text; public ImageView image; } public Class_Family(Activity context,String[] names){ this.context=context; this.names=names; } @Override public int getCount() { return names.length; } @Override public Object getItem(int position) { return names[position]; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { View rowView=convertView; if(rowView==null){ LayoutInflater inflater=context.getLayoutInflater(); rowView=inflater.inflate(R.layout.list_item,null); ViewHolder viewHolder=new ViewHolder(); viewHolder.text=(TextView) rowView.findViewById(R.id.label); viewHolder.image = (ImageView) rowView.findViewById(R.id.icon); rowView.setTag(viewHolder); } ViewHolder holder = (ViewHolder) rowView.getTag(); String s = names[position]; holder.text.setText(s); if(s.startsWith("Aunt")) holder.image.setImageResource(R.drawable.aunt); else if(s.startsWith("Daughter")) holder.image.setImageResource(R.drawable.daugter); else if(s.startsWith("Father")) holder.image.setImageResource(R.drawable.father); else if(s.startsWith("Grandmother")) holder.image.setImageResource(R.drawable.grandmother); else if(s.startsWith("Husband")) holder.image.setImageResource(R.drawable.husband); else if(s.startsWith("Mother")) holder.image.setImageResource(R.drawable.mother); else if(s.startsWith("Sister")) holder.image.setImageResource(R.drawable.sister); else if(s.startsWith("Son")) holder.image.setImageResource(R.drawable.son); else if(s.startsWith("Wife")) holder.image.setImageResource(R.drawable.wife); return rowView; } }
true
be8b5918f00f6a44266c6677891234cbe006bdde
Java
aayushnayak/aayush_class_10
/Aayush Java Project Backup/prog_27_pg_368_display_function_2.java
UTF-8
1,690
4.3125
4
[]
no_license
import java.util.*; public class prog_27_pg_368_display_function_2 { public static void main(String args[]) { Scanner sc = new Scanner(System.in); prog_27_pg_368_display_function_2 obj=new prog_27_pg_368_display_function_2(); System.out.println("ENTER 1] IF YOU WANT TO CHECK AND PRINT WHETHER THE NUMBER IS PERFECT SQUARE NUMBER OR NOT "); System.out.println("ENTER 2] IF YOU WANT TO CHECK AND PRINT WHETHER THE ENTERED STRING CONTAINS THE ENTERED CHARACTER OR NOT"); System.out.println("ENTER 3] IF YOU WANT TO CHECK AND PRINT NUMBER OF SPECIAL CHARACTERS IN THE ENTERED STRING "); char choice = sc.next().charAt(0); switch (choice) { case '1': System.out.println("ENTER A NUMBER TO CHECK WHETHER THE NUMBER IS PERFECT NUMBER OR NOT "); int n = sc.nextInt(); // obj.display(n); break; case '2': System.out.println("ENTER A STRING AND A CHARACTER TO CHECK AND PRINT WHETHER THE ENTERED STRING CONTAINS THE ENTERED CHARACTER OR NOT "); String st = sc.next(); char c = sc.next().charAt(0); // obj.display(st, c); break; case '3': System.out.println("ENTER A STRING TO CHECK PRINT NUMBER OF SPECIAL CHARACTERS IN THE ENTERED STRING "); String st1 = sc.next(); //obj.display(st1); break; default: System.out.println("SORRY SOMETHING WENT WRONG!"); System.out.println("PLEASE ENTER THE CHOICE PROPERLY"); return; } } }
true
6132184f4df601bb651421071de01818f6ca7610
Java
jtransc/jtransc-examples
/stress/src/main/java/com/stress/sub1/sub4/sub0/Class3961.java
UTF-8
394
2.140625
2
[]
no_license
package com.stress.sub1.sub4.sub0; import com.jtransc.annotation.JTranscKeep; @JTranscKeep public class Class3961 { public static final String static_const_3961_0 = "Hi, my num is 3961 0"; static int static_field_3961_0; int member_3961_0; public void method3961() { System.out.println(static_const_3961_0); } public void method3961_1(int p0, String p1) { System.out.println(p1); } }
true
2e3dcff15a7bd78496f7087464742e8182feadad
Java
brucelang/FoodPicker
/app/src/main/java/com/lang/bruce/foodpicker/FoodAdapter.java
UTF-8
2,124
2.53125
3
[]
no_license
package com.lang.bruce.foodpicker; import android.content.Context; import android.support.annotation.NonNull; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; import static java.lang.String.format; class FoodAdapter extends ArrayAdapter<Food> { public boolean rank = true; private TextView txtName; private TextView txtType; private TextView txtRankKcal; private ImageView image; private Food food; FoodAdapter(Context context, ArrayList<Food> food) { super(context, 0, food); } @NonNull @Override public View getView(int position, View convertView, @NonNull ViewGroup parent) { //fixme ? food = getItem(position); if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.food_item, parent, false); } txtName = convertView.findViewById(R.id.textViewName); txtType = convertView.findViewById(R.id.textViewType); txtRankKcal = convertView.findViewById(R.id.textViewRankOrKcal); image = convertView.findViewById(R.id.imageViewVeggie); assert food != null; txtName.setText(food.getName()); txtType.setText(food.getType()); if (rank) { txtRankKcal.setText(format("%dx", food.getRank())); adjustWidth(); } else { txtRankKcal.setVisibility(View.GONE); txtName.setText(format("%s (%d kcal)", food.getName(), Math.round(food.getKcal()))); } if(food.getVegetarian() == 0) { image.setVisibility(View.GONE); } return convertView; } private void adjustWidth() { if (food.getRank() > 100) { txtRankKcal.setWidth(70); } if (food.getRank() > 1000) { txtRankKcal.setWidth(90); } if (food.getRank() > 10000) { txtRankKcal.setWidth(100); } } }
true
db041ba21b4d8bf3d6550ddcb6018d5cd29992ef
Java
BasiqueEvangelist/Watson
/src/main/java/eu/minemania/watson/analysis/ModModeAnalysis.java
UTF-8
1,634
2.53125
3
[ "MIT" ]
permissive
package eu.minemania.watson.analysis; import java.util.regex.Matcher; import java.util.regex.Pattern; import eu.minemania.watson.chat.IMatchedChatHandler; import eu.minemania.watson.config.Configs; import net.minecraft.util.text.ITextComponent; public class ModModeAnalysis extends Analysis { public ModModeAnalysis() { IMatchedChatHandler modmodeHandler = new IMatchedChatHandler() { @Override public boolean onMatchedChat(ITextComponent chat, Matcher m) { changeModMode(chat, m); return true; } }; addMatchedChatHandler(Configs.Analysis.MODMODE_ENABLE, modmodeHandler); addMatchedChatHandler(Configs.Analysis.MODMODE_DISABLE, modmodeHandler); IMatchedChatHandler dutiesHandler = new IMatchedChatHandler() { @Override public boolean onMatchedChat(ITextComponent chat, Matcher m) { changeDutyMode(chat, m); return true; } }; addMatchedChatHandler(Configs.Analysis.DUTYMODE_ENABLE, dutiesHandler); addMatchedChatHandler(Configs.Analysis.DUTYMODE_DISABLE, dutiesHandler); } void changeModMode(ITextComponent chat, Matcher m) { Configs.Generic.DISPLAYED.setBooleanValue(m.pattern() == Pattern.compile(Configs.Analysis.MODMODE_ENABLE.getStringValue())); } void changeDutyMode(ITextComponent chat, Matcher m) { Configs.Generic.DISPLAYED.setBooleanValue(m.pattern() == Pattern.compile(Configs.Analysis.DUTYMODE_ENABLE.getStringValue())); } }
true
9850bd9599ccdb4d16a3b5f278ce27a59b2f873e
Java
lagomezz/EjerciciosJava
/src/PruebasJunit/OperacionesMatematicasTest.java
UTF-8
303
2.40625
2
[ "MIT" ]
permissive
package PruebasJunit; import static org.junit.Assert.*; import org.junit.Test; public class OperacionesMatematicasTest { OperacionesMatematicas obj=new OperacionesMatematicas(); @Test public void TestSuma() { int valor1 = obj.Suma(2,4); int valor2 = 6; assertEquals(valor2, valor1); } }
true
bbccd467c38c5e5b0d35b7f44c1fecbe79ebf626
Java
OpenAPITools/openapi-generator
/samples/client/echo_api/java/native/src/test/java/org/openapitools/client/model/NumberPropertiesOnlyTest.java
UTF-8
1,405
1.710938
2
[ "Apache-2.0" ]
permissive
/* * Echo Server API * Echo Server API * * The version of the OpenAPI document: 0.1.0 * Contact: team@openapitools.org * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package org.openapitools.client.model; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonValue; import java.math.BigDecimal; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; /** * Model tests for NumberPropertiesOnly */ public class NumberPropertiesOnlyTest { private final NumberPropertiesOnly model = new NumberPropertiesOnly(); /** * Model tests for NumberPropertiesOnly */ @Test public void testNumberPropertiesOnly() { // TODO: test NumberPropertiesOnly } /** * Test the property 'number' */ @Test public void numberTest() { // TODO: test number } /** * Test the property '_float' */ @Test public void _floatTest() { // TODO: test _float } /** * Test the property '_double' */ @Test public void _doubleTest() { // TODO: test _double } }
true
46618e4cb20f2aaa50493a84460dbdd2d6991a4c
Java
Deansquirrel/jtools-http
/src/main/java/com/github/deansquirrel/tools/http/OkHttpHelper.java
UTF-8
12,831
2.484375
2
[]
no_license
package com.github.deansquirrel.tools.http; import okhttp3.*; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Map; public class OkHttpHelper { public static final String SCHEME_HTTP = "http"; public static final String SCHEME_HTTPS = "https"; public static final String METHOD_GET = "GET"; public static final String METHOD_POST = "POST"; private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); private static final MediaType XML = MediaType.parse("application/xml; charset=utf-8"); private static final MediaType FORM_DATA = MediaType.parse("multipart/form-data"); private static final MediaType FILE = MediaType.parse("application/octet-stream"); private OkHttpHelper(){} private static OkHttpClient getOkHttpClient() { return OkHttpUtil.getOkHttpClient(); } private static Request getGetRequest(String url, Map<String, String> headers, Map<String, String> params) { Request request = null; if(params != null && !params.isEmpty()) { HttpUrl httpUrl = HttpUrl.parse(url); if(httpUrl != null) { httpUrl = addQueryParameter(httpUrl, params); request = getRequest(httpUrl, METHOD_GET, getHeaders(headers), null); } } if(request == null) { request = getRequest(url, METHOD_GET, getHeaders(headers), null); } return request; } public static String doGet(String url) throws IOException { return doGet(url, null, null); } public static String doGet(String url, Map<String, String> params) throws IOException { return doGet(url, null, params); } public static String doGet(String url, Map<String, String> headers, Map<String, String> params) throws IOException { return execute(getGetRequest(url, headers, params)); } public static void doGetAsync(String url, ICallback callback) { doGetAsync(url, null, null, callback); } public static void doGetAsync(String url, Map<String, String> params, ICallback callback) { doGetAsync(url, null, params, callback); } public static void doGetAsync(String url, Map<String, String> headers, Map<String, String> params, ICallback callback) { execute(getGetRequest(url, headers, params), callback); } public static String doPost(String url, MediaType contentType, String content) throws IOException { return doPost(url, null, contentType, content); } public static String doPost(String url, Map<String, String> headers, MediaType contentType, String content) throws IOException { return execute(getRequest(url, METHOD_POST, getHeaders(headers), getRequestBody(contentType, content))); } public static void doPostAsync(String url, MediaType contentType, String content, ICallback callback) { doPostAsync(url, null, contentType, content, callback); } public static void doPostAsync(String url, Map<String, String> headers, MediaType contentType, String content, ICallback callback) { execute(getRequest(url, METHOD_POST, getHeaders(headers), getRequestBody(contentType, content)), callback); } public static String doPostJson(String url, String content) throws IOException { return doPost(url, JSON, content); } public static String doPostJson(String url, Map<String, String> headers, String content) throws IOException { return doPost(url, headers, JSON, content); } public static void doPostJsonAsync(String url, String content, ICallback callback) { doPostAsync(url, JSON, content, callback); } public static void doPostJsonAsync(String url, Map<String, String> headers, String content, ICallback callback) { doPostAsync(url, headers, JSON, content, callback); } public static HttpUrl addPathSegment(HttpUrl httpUrl, String pathSegment) { return httpUrl.newBuilder().addPathSegment(pathSegment).build(); } public static HttpUrl addPathSegment(HttpUrl httpUrl, List<String> pathSegment) { HttpUrl.Builder builder = httpUrl.newBuilder(); if(pathSegment != null) { for(String p : pathSegment) { builder.addPathSegment(p); } } return builder.build(); } public static HttpUrl addEncodedPathSegment(HttpUrl httpUrl, String pathSegment) { return httpUrl.newBuilder().addEncodedPathSegment(pathSegment).build(); } public static HttpUrl addEncodedPathSegment(HttpUrl httpUrl, List<String> pathSegment) { HttpUrl.Builder builder = httpUrl.newBuilder(); if(pathSegment != null) { for(String p : pathSegment) { builder.addEncodedPathSegment(p); } } return builder.build(); } public static HttpUrl addQueryParameter(HttpUrl httpUrl, String name, String value) { return httpUrl.newBuilder().addQueryParameter(name,value).build(); } public static HttpUrl addQueryParameter(HttpUrl httpUrl, Map<String, String> queryParameter) { HttpUrl.Builder builder = httpUrl.newBuilder(); if(queryParameter != null) { for(String p : queryParameter.keySet()) { builder.addQueryParameter(p, queryParameter.get(p)); } } return builder.build(); } public static HttpUrl addEncodedQueryParameter(HttpUrl httpUrl, String name, String value) { return httpUrl.newBuilder().addEncodedQueryParameter(name,value).build(); } public static HttpUrl addEncodedQueryParameter(HttpUrl httpUrl, Map<String, String> encodedQueryParameter) { HttpUrl.Builder builder = httpUrl.newBuilder(); if(encodedQueryParameter != null) { for(String p : encodedQueryParameter.keySet()) { builder.addQueryParameter(p, encodedQueryParameter.get(p)); } } return builder.build(); } public static HttpUrl getHttpUrl(String scheme, String host){ return getHttpUrl(scheme, host, null, null, null); } public static HttpUrl getHttpUrl(String scheme, String host,List<String> pathSegment){ return getHttpUrl(scheme, host, pathSegment, null, null); } public static HttpUrl getHttpUrl(String scheme, String host, List<String> pathSegment, Map<String, String> queryParameter){ return getHttpUrl(scheme, host, pathSegment, queryParameter, null); } public static HttpUrl getHttpUrl(String scheme, String host, List<String> pathSegment, Map<String, String> queryParameter, Map<String, String> encodedQueryParameter){ HttpUrl.Builder builder = new HttpUrl.Builder() .scheme(scheme) .host(host); if(pathSegment != null) { for(String p : pathSegment) { builder.addPathSegment(p); } } if(queryParameter != null) { for(String p : queryParameter.keySet()) { builder.addQueryParameter(p, queryParameter.get(p)); } } if(encodedQueryParameter != null) { for(String p : encodedQueryParameter.keySet()) { builder.addEncodedQueryParameter(p, encodedQueryParameter.get(p)); } } return builder.build(); } public static Headers getHeaders(Headers headers, String name, String value) { return headers.newBuilder().add(name, value).build(); } public static Headers getHeaders(Headers headers, Map<String, String> headersMap) { return headers.newBuilder().addAll(getHeaders(headersMap)).build(); } public static Headers getHeaders(Headers headers, String... add) { if(add.length < 1) { return headers; } Headers addHeaders = getHeaders(add); if(addHeaders == null) { return headers; } return headers.newBuilder().addAll(addHeaders).build(); } public static Headers getHeaders(String... headers) { if(headers.length < 1) { return null; } return Headers.of(headers); } public static Headers getHeaders(Map<String, String> headersMap) { if(headersMap == null) { return null; } return Headers.of(headersMap); // Headers.Builder headers = new Headers.Builder(); // for(String k : headersMap.keySet()) { // headers.add(k, headersMap.get(k)); // } // return headers.build(); } public static Headers getHeaders(Headers headers) { if(headers == null) { return null; } return new Headers.Builder().addAll(headers).build(); } public static RequestBody getRequestBody(MediaType contentType, String content) { return RequestBody.create(contentType, content); } public static RequestBody getRequestBodyJSON(String content) { return RequestBody.create(JSON, content); } public static RequestBody getRequestBodyXML(String content) { return RequestBody.create(XML, content); } public static RequestBody getRequestBody(File file) { return RequestBody.create(FILE, file); } public static FormBody getRequestBody(Map<String, String> map) { return getFormBody(map, null); } public static FormBody getFormBody(Map<String, String> map, Map<String, String> encodedMap) { FormBody.Builder builder = new FormBody.Builder(); if(map != null) { for(String k:map.keySet()) { builder.add(k, map.get(k)); } } if(encodedMap != null) { for(String k:encodedMap.keySet()) { String v = encodedMap.get(k); if(v != null) { builder.addEncoded(k, v); } } } return builder.build(); } public static MultipartBody getMultipartBody(Map<String, String> dataPart, Map<String, File> filePart) { MultipartBody.Builder builder = new MultipartBody.Builder(); if(FORM_DATA != null) { builder.setType(OkHttpHelper.FORM_DATA); } if(dataPart != null) { for(String k : dataPart.keySet()) { builder.addFormDataPart(k, dataPart.get(k)); } } if(filePart != null) { for(String k : filePart.keySet()) { File f = filePart.get(k); if(k != null) { builder.addFormDataPart(k, f.getName(), getRequestBody(f)); } } } return builder.build(); } public static Request getRequest(HttpUrl url, String method, Headers headers, RequestBody requestBody) { Request.Builder builder = new Request.Builder().url(url); if(headers != null) { builder = builder.headers(headers); } if(requestBody != null) { builder = builder.method(method, requestBody); } return builder.build(); } public static Request getRequest(String url, String method, Headers headers, RequestBody requestBody) { return getRequest(HttpUrl.get(url), method, headers, requestBody); } public static String execute(Request request) throws IOException { try (Response response = getOkHttpClient().newCall(request).execute()) { if (response.body() != null) { return response.body().string(); } } throw new IOException("返回数据为空"); } public static void execute(Request request, ICallback callback) { getOkHttpClient().newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { callback.onFailure(call, e); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.body() != null) { try { callback.onResponse(call, response.body().string()); } catch (IOException e) { onFailure(call, e); } } else { onFailure(call, new IOException("返回数据为空")); } response.close(); } }); } }
true
ae18149a570290a0887c7514b1cb305b0674461f
Java
simonacorde/elders-skill-match-mongo
/src/main/java/diploma/elders/up/optimization/domain/Bird.java
UTF-8
2,057
2.8125
3
[]
no_license
package diploma.elders.up.optimization.domain; import java.util.ArrayList; import java.util.List; /** * Created by Simonas on 3/5/2016. */ public class Bird { private BirdGender birdGender; private BirdType birdType; private double matchingScore; private boolean mated; private int nrOfMates = 0; private List<Genome> genome; public Bird() { genome = new ArrayList<>(); } public BirdGender getBirdGender() { return birdGender; } public void setBirdGender(BirdGender birdGender) { this.birdGender = birdGender; } public BirdType getBirdType() { return birdType; } public void setBirdType(BirdType birdType) { this.birdType = birdType; } public double getMatchingScore() { return matchingScore; } public void setMatchingScore(double matchingScore) { this.matchingScore = matchingScore; } public List<Genome> getGenome() { return genome; } public void setGenome(List<Genome> genome) { this.genome = genome; } public boolean isMated() { return mated; } public void setMated(boolean mated) { this.mated = mated; } public int getNrOfMates() { return nrOfMates; } public void setNrOfMates(int nrOfMates) { this.nrOfMates = nrOfMates; } public void increaseNrOfMates() { this.nrOfMates ++; if(this.getBirdType().equals(BirdType.MONOGAMOUS) && this.nrOfMates >= 1){ this.mated = true; }else if(this.getBirdType().equals(BirdType.POLYGYNOUS) && this.nrOfMates >= 3){ this.mated = true; } } @Override public String toString() { return "Bird{" + "birdGender=" + birdGender + ", birdType=" + birdType + ", matchingScore=" + matchingScore + ", mated=" + mated + ", genome=" + genome + ", nrOfMates=" + nrOfMates + '}'; } }
true
2b26c585cb8c14b8d8026c6e824abe1040ef7af1
Java
raghuteja/COMS
/COMS/src/java/insert/upload.java
UTF-8
9,250
2.0625
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package insert; import connect.db_connect; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.*; import java.util.logging.*; import java.util.logging.Level; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.servlet.http.Part; /** * * @author raghuteja */ @WebServlet(name = "upload", urlPatterns = {"/upload"}) public class upload extends HttpServlet { /** * Processes requests for both HTTP * <code>GET</code> and * <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { /* TODO output your page here. You may use following sample code. */ out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet upload at " + request.getContextPath() + "</h1>"); out.println("</body>"); out.println("</html>"); } finally { out.close(); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP * <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP * <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // processRequest(request, response); response.setContentType("text/html"); PrintWriter out = response.getWriter(); String saveFile=""; String contentType = request.getContentType(); if((contentType != null)&&(contentType.indexOf("multipart/form-data") >= 0)){ DataInputStream in = new DataInputStream(request.getInputStream()); int formDataLength = request.getContentLength(); byte dataBytes[] = new byte[formDataLength]; int byteRead = 0; int totalBytesRead = 0; while(totalBytesRead < formDataLength){ byteRead = in.read(dataBytes, totalBytesRead,formDataLength); totalBytesRead += byteRead; } String file = new String(dataBytes); saveFile = file.substring(file.indexOf("filename=\"") + 10); saveFile = saveFile.substring(0, saveFile.indexOf("\n")); saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\"")); int lastIndex = contentType.lastIndexOf("="); String boundary = contentType.substring(lastIndex + 1,contentType.length()); int pos; pos = file.indexOf("filename=\""); pos = file.indexOf("\n", pos) + 1; pos = file.indexOf("\n", pos) + 1; pos = file.indexOf("\n", pos) + 1; int boundaryLocation = file.indexOf(boundary, pos) - 4; int startPos = ((file.substring(0, pos)).getBytes()).length; int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length; File ff = new File(saveFile); FileOutputStream fileOut = new FileOutputStream(ff); fileOut.write(dataBytes, startPos, (endPos - startPos)); fileOut.flush(); fileOut.close(); out.println("You have successfully upload the file:"+saveFile); Connection connection = null; ResultSet rs = null; PreparedStatement psmnt = null; FileInputStream fis; HttpSession session = request.getSession(); String confid = (String)session.getAttribute("conf_ID").toString(); String appid = (String)session.getAttribute("userid").toString(); String title = (String)session.getAttribute("title").toString(); String topic = (String)session.getAttribute("topic").toString(); System.out.println(confid + "----" + appid + "----" + title + "----" + topic); db_connect cont = new db_connect(); System.out.println("Connecting to a database..."); try { try { connection = cont.connect(); } catch (Exception ex) { Logger.getLogger(upload.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("Connected database successfully..."); File f = new File(saveFile); try { psmnt = connection.prepareStatement("insert into papers(title,topic,app_ID,conf_ID,paper) values('" + title + "','" + topic + "','" + appid + "','" + confid + "',?)"); } catch (SQLException ex) { Logger.getLogger(upload.class.getName()).log(Level.SEVERE, null, ex); } fis = new FileInputStream(f); try { psmnt.setBinaryStream(1, (InputStream)fis, (int)(f.length())); } catch (SQLException ex) { Logger.getLogger(upload.class.getName()).log(Level.SEVERE, null, ex); } int s; s = 0; try { s = psmnt.executeUpdate(); } catch (SQLException ex) { Logger.getLogger(upload.class.getName()).log(Level.SEVERE, null, ex); } if(s>0){ System.out.println("Uploaded successfully !"); int lastInsertedId = 0; Statement stmt = null; PreparedStatement pss = connection.prepareStatement("select paper_id from papers order by paper_id desc limit 1"); ResultSet getKeyRs = pss.executeQuery(); System.out.println("-----------here-----------"); if (getKeyRs.next()) { lastInsertedId=getKeyRs.getInt(1); } System.out.println("Last inserted conference ID = " + lastInsertedId); String assign = "SELECT num_papers.rev_ID, num_papers FROM num_papers,rev_topics,users where num_papers.rev_ID = rev_topics.rev_ID and num_papers.rev_ID = users.user_ID and topic ='" + topic + "' and users.conf_ID = '" + confid + "' order by num_papers limit 1"; PreparedStatement ps = connection.prepareStatement(assign); rs = ps.executeQuery(); if(rs.next()) { String rev_id = rs.getString("rev_ID"); int num_papers = rs.getInt("num_papers") + 1; String update = "update num_papers set num_papers = " + num_papers + " where rev_ID = '" + rev_id + "'"; PreparedStatement ps1; ps1 = connection.prepareStatement(update); ps1.executeUpdate(); String push = "INSERT INTO reviews(rev_ID, paper_ID, conf_ID) VALUES (?,?,?)"; ps1 = connection.prepareStatement(push); ps1.setString(1,rev_id); ps1.setInt(2,lastInsertedId); ps1.setString(3,confid); System.out.println(push); ps1.executeUpdate(); } response.sendRedirect("applicant.jsp?u=1"); } else{ System.out.println("Error!"); } } catch (Exception ex) { System.out.println("Exception occured"); } } } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
true
cee3d85498f44ee5f58439e019fa2119cbc793b1
Java
zsl131/xh-springboot
/src/main/java/com/zslin/business/dao/IOrdersDao.java
UTF-8
2,423
2.1875
2
[]
no_license
package com.zslin.business.dao; import com.zslin.business.model.Orders; import com.zslin.core.repository.BaseRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * Created by 钟述林 on 2019-12-18. */ public interface IOrdersDao extends BaseRepository<Orders, Integer>, JpaSpecificationExecutor<Orders> { Orders findByOrdersNo(String ordersNo); Orders findByOrdersKey(String ordersKey); @Query("FROM Orders o WHERE o.id=?1 AND o.customId=?2") Orders findOne(Integer id, Integer customId); Orders findByOrdersNoAndCustomId(String ordersNo, Integer customId); /** 查询订单编号,用于支付 */ @Query("SELECT o.ordersNo FROM Orders o WHERE o.ordersKey=?1 AND o.customId=?2") String queryOrdersNo(String ordersKey, Integer customId); @Query("UPDATE Orders o SET o.status=?1 WHERE o.ordersNo=?2 AND o.customId=?3") @Modifying @Transactional int updateStatus(String status, String ordersNo, Integer customId); @Query("SELECT COUNT(o.id) FROM Orders o WHERE o.status=?1 AND o.customId=?2 ") Integer queryCount(String status, Integer customId); /** 获取超时未付款的订单 */ @Query("FROM Orders o WHERE o.status='0' AND o.createLong<=?1") List<Orders> findTimeoutOrders(Long timeout); /** 获取长时间未确认收货的订单 */ @Query("FROM Orders o WHERE o.status='2' AND o.sendLong<=?1") List<Orders> findTimeoutConfirmOrders(Long timeout); /** 获取时间段内订单金额总和 */ @Query("SELECT SUM(o.totalMoney) FROM Orders o WHERE o.payLong IS NOT NULL AND o.payLong>=?1 AND o.payLong<=?2") Double findMoney(Long startLong, Long endLong); /** 获取时间段内订单优惠金额总和 */ @Query("SELECT SUM(o.discountMoney) FROM Orders o WHERE o.discountMoney IS NOT NULL AND o.payLong IS NOT NULL AND o.payLong>=?1 AND o.payLong<=?2") Double findDiscountMoney(Long startLong, Long endLong); /** 获取时间段内订单退款 */ /*@Query("SELECT SUM(o.backMoney) FROM Orders o WHERE o.backMoney IS NOT NULL AND o.payLong IS NOT NULL AND o.payLong>=?1 AND o.payLong<=?2 ") Double findBackMoney(Long startLong, Long endLong);*/ }
true
9cf7986ef39eef64d2fe4e287f97a7fbd48f85f4
Java
bouyass/chess
/src/echecs/Pieces/Piece.java
UTF-8
718
2.34375
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 echecs.Pieces; import javax.swing.Icon; import echecs.Couleur; import echecs.Type; /** * * @author lyes */ public abstract class Piece { int x,y,id; Type type = null; String icone; Couleur couleur; //boolean jouante = true; public int getX(){return this.x;} public int getY(){return this.y;} public Type getType(){return this.type;} public Couleur getCouleur(){return this.couleur;} public String getIcone(){return icone;} public int getId(){return this.id;} }
true
fd53134195f4bc2ce92ccd035ec9253d96edc3bb
Java
Mikhail1995-25/job4j-2
/chapter_001/src/main/java/ru/job4j/Car.java
UTF-8
1,482
3.875
4
[]
no_license
package ru.job4j; /** * Car * @author Mikhail Pushkarev * @since 05.03.2020 * @version 0.16 */ public class Car { private double value; /** * Method inDrive * @param cilometr - Принимает значение. */ public void inDrive(int cilometr) { this.value = this.value - cilometr; } /** * Method fill * @param gas - Параметр принмает значение. */ public void fill(int gas) { this.value = this.value + 10 * gas; } /** * Method canDrive * @return - Возвращает результат проверки значения. */ public boolean canDrive() { boolean result = this.value > 0; return result; } /** * Method gasInfo */ public void gasInfo() { System.out.println("I can drive " + this.value + " kilometrs"); } } class CarUsege { /** * Main * @param args - Выводит результат на консоль. */ public static void main(String[]args) { Car audi = new Car(); boolean driving = audi.canDrive(); System.out.println("Can you drive " + driving); System.out.println("I am going to a gas station"); int gas = 25; audi.fill(gas); driving = audi.canDrive(); System.out.println("Can you drive now " + driving); int distance = 10; audi.inDrive(distance); audi.gasInfo(); } }
true
83dce5b224b9d8ec2ed24a6867e4aca3e4c434ba
Java
TheMarvellousTeam/The-Marvellous-Crab
/TheMarvellousCrab/src/org/ggj/imposteurs/builder/data/EmitterData.java
UTF-8
132
1.703125
2
[]
no_license
package org.ggj.imposteurs.builder.data; public class EmitterData { public String color; public TransformData transform; }
true
50de3fb3b41014019b492b01b3996b59028329e7
Java
BackmanLab/mmPWSPlugin
/src/main/java/edu/bpl/pwsplugin/acquisitionManagers/ListAcquisitionBase.java
UTF-8
4,824
2.140625
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 edu.bpl.pwsplugin.acquisitionManagers; import edu.bpl.pwsplugin.Globals; import edu.bpl.pwsplugin.UI.utils.PWSAlbum; import edu.bpl.pwsplugin.acquisitionManagers.fileSavers.ImageIOSaver; import edu.bpl.pwsplugin.acquisitionManagers.fileSavers.ImageSaver; import edu.bpl.pwsplugin.FileSpecs; import edu.bpl.pwsplugin.hardware.configurations.ImagingConfiguration; import edu.bpl.pwsplugin.metadata.MetadataBase; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import mmcorej.DoubleVector; import org.micromanager.data.Image; import org.micromanager.internal.utils.ReportingUtils; /** * * @author nick */ abstract class ListAcquisitionBase<S> implements Acquisition<List<S>>{ //A base class for an acquisition that acquires from a list of settings and puts the resulting images all into a shared display. //Images are saved to individual numbered folders. private List<S> settingsList; private final PWSAlbum display; protected ListAcquisitionBase(PWSAlbum album) { this.display = album; } @Override public void acquireImages(String savePath, int cellNum) throws Exception { this.display.clear(); //The implementation of `runSingleImageAcquisition` call `displayImage` to add images to the display throughout the imaging process. this.initializeAcquisitions(settingsList); try { for (int i=0; i< this.settingsList.size(); i++) { S settings = this.settingsList.get(i); this.setCurrentSettings(settings); ImagingConfiguration imConf = this.getImgConfig(); //Activation must occur every time the imaging configuration changes. Initializemetadata requires that the correct configuration is active. if (!(imConf == Globals.getHardwareConfiguration().getActiveConfiguration())) { //It's important that the configuration is activated before we try pulling metadata like the affine transform Globals.getHardwareConfiguration().activateImagingConfiguration(imConf); //Activation must occur every time the imaging configuration changes. } MetadataBase md = this.initializeMetadata(imConf); String subFolderName = String.format("%s_%d", FileSpecs.getSubfolderName(this.getFileType()), i); Path fullSavePath = FileSpecs.getCellFolderName(Paths.get(savePath), cellNum).resolve(subFolderName); ImageSaver imSaver = new ImageIOSaver(); imSaver.configure(fullSavePath.toString(), FileSpecs.getFilePrefix(this.getFileType()), this.numFrames()); this.runSingleImageAcquisition(imSaver, md); } } finally { this.finalizeAcquisitions(); } } @Override public void setSettings(List<S> settingList) { this.settingsList = settingList; } private MetadataBase initializeMetadata(ImagingConfiguration imConf) throws Exception { if (Globals.core().getPixelSizeUm() == 0.0) { //This information gets saved to the metadata below in the form of an affine transform. ReportingUtils.showMessage("It is highly recommended that you provide MicroManager with a pixel size setting for the current setup. Having this information is useful for analysis."); } DoubleVector aff = Globals.core().getPixelSizeAffine(); List<Double> trans = new ArrayList<>(); for (int i=0; i<aff.size(); i++) { trans.add(aff.get(i)); } MetadataBase metadata = new MetadataBase( imConf.camera().getSettings().linearityPolynomial, Globals.getHardwareConfiguration().getSettings().systemName, imConf.camera().getSettings().darkCounts, trans); return metadata; } protected abstract void setCurrentSettings(S settings); protected abstract ImagingConfiguration getImgConfig(); protected abstract void finalizeAcquisitions() throws Exception; protected abstract void initializeAcquisitions(List<S> settings) throws Exception; protected abstract void runSingleImageAcquisition(ImageSaver saver, MetadataBase md) throws Exception; protected abstract FileSpecs.Type getFileType(); //Return the type enumerator for this acquisition, used for file saving information. protected abstract Integer numFrames(); protected void displayImage(Image img) { //Call this from within the implementation to add images to the display. this.display.addImage(img); } }
true
505ca03dd2d2d7a8dacb6be0e0e79352ce9ffbef
Java
cdai/interview
/1-algorithm/13-leetcode/java/src/advanced/greedy/lc122_besttimetobuyandsellstock2/Solution.java
UTF-8
2,321
4.09375
4
[ "MIT" ]
permissive
package advanced.greedy.lc122_besttimetobuyandsellstock2; /** * Say you have an array for which the ith element is the price of a given stock on day i. * Design an algorithm to find the maximum profit. * You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). * However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). */ public class Solution { public static void main(String[] args) { Solution sol = new Solution(); System.out.println(sol.maxProfit(new int[]{3, 2, 6, 5, 0, 3})); } // 4AC. Not greedy strategy. Not good. public int maxProfit(int[] prices) { if (prices.length == 0) return 0; int max = 0, buy = prices[0], n = prices.length; for (int i = 1; i < n; i++) { if (prices[i] < prices[i - 1]) { // increasing sequence max += prices[i - 1] - buy; buy = prices[i]; } } max += prices[n - 1] - buy; return max; } // My 3AC: accumulate if cur > prev (low) public int maxProfit3(int[] prices) { int profit = 0, low = Integer.MAX_VALUE; for (int price : prices) { if (price > low) profit += price - low; low = price; } return profit; } // My 2AC: form [low,high] a increasing window // Eg-1: 1 3 9 2 8 // low : 1 2 // high: 1 3 9 2 8 // prof: 8 14 // Eg-2: 7 6 5 4 3 // low : 7 6 5 4 3 // high: 7 6 5 4 3 // prof: 0 public int maxProfit2(int[] prices) { int profit = 0, low = Integer.MAX_VALUE, high = Integer.MAX_VALUE; for (int price : prices) { if (price < high) { profit += high - low; high = low = price; } else { high = price; } } return profit + (high - low); // don't forget last batch and high must be MAX_INT } // Greedy public int maxProfit1(int[] prices) { int max = 0; for (int i = 1; i < prices.length; i++) { if (prices[i] > prices[i-1]) { max += (prices[i] - prices[i-1]); } } return max; } }
true
9644a84d52cb4def99f7cf50e38ad51d04c166a8
Java
samzorik/SelengWeb
/Runner/src/test/java/TestMavenProject/Runner/hello.java
UTF-8
1,538
2.796875
3
[]
no_license
package TestMavenProject.Runner; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; public class hello { private EntityManagerFactory emf; private EntityManager em; private String PERSISTENCE_UNIT_NAME = "COLIBRI"; @Test public static void main(String []args) throws Exception { hello hello = new hello(); hello.initEntityManager(); hello.create(); hello.read(); hello.closeEntityManager(); } private void initEntityManager() { em = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME).createEntityManager(); } private void closeEntityManager() { em.close(); emf.close(); } private void create() { em.getTransaction().begin(); Greeting g_en = new Greeting("hello world", "en"); Greeting g_es = new Greeting("hola, mundo", "es"); Greeting[] greetings = new Greeting[]{g_en, g_es}; for(Greeting g : greetings) { em.persist(g); } em.getTransaction().commit(); } private void read() { Greeting g = (Greeting) em.createQuery("select g from Greeting g where .language = :language").setParameter("language", "en").getSingleResult(); System.out.println("Query returned: " + g); } }
true
1ed069ed090a66ffb4049318d747f8ac52e2ccc6
Java
NurikN999/Java
/Bitlab/FirstCourse/third_lesson/Exercise20.java
UTF-8
310
2.65625
3
[]
no_license
package Bitlab.third_lesson; import java.util.Scanner; public class Exercise20 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int counter = 0; while(in.nextInt() != 0){ counter++; } System.out.println(counter); } }
true
755a5e1ebef30cd7d26703119f3d54303be94034
Java
Hey-Sir/wisdomblog
/src/main/java/com/wisdom/blog/service/BlogService.java
UTF-8
1,092
1.898438
2
[]
no_license
package com.wisdom.blog.service; import com.wisdom.blog.domain.Blog; import com.wisdom.blog.domain.Catalog; import com.wisdom.blog.domain.User; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; public interface BlogService { Blog saveBlog(Blog blog); void removeBlog(Long id); Blog updateBlog(Blog blog); Blog getBlogById(Long id); /** * 根据用户名进行分页模糊查询(最新) * @param user * @return */ Page<Blog> listBlogsByTitleLike(User user, String title, Pageable pageable); /** * 根据用户名进行分页模糊查询(最热) * @param user * @return */ Page<Blog> listBlogsByTitleLikeAndSort(User suser, String title, Pageable pageable); void readingIncrease(Long id); Blog createComment(Long blogId,String commentContent); void removeComment(Long blogId,Long commentId); Blog createVote(Long blogId); void removeVote(Long blogId,Long voteId); Page<Blog> listBlogsByCatalog(Catalog catalog,Pageable pageable); }
true
931a61e3e274c0a78a88e7ee8535ba3eb240a2cf
Java
Ana2295/Multitablas-Sqlite
/app/src/main/java/com/example/anahi/multitablas/data/repo/ClienteRepo.java
UTF-8
2,432
2.359375
2
[]
no_license
package com.example.anahi.multitablas.data.repo; import android.content.ContentValues; import android.database.sqlite.SQLiteDatabase; import com.example.anahi.multitablas.data.DatabaseManager; import com.example.anahi.multitablas.data.model.Cliente; /** * Created by Anahi on 21/09/2018. */ public class ClienteRepo { private final String TAG = ClienteRepo.class.getSimpleName().toString(); public ClienteRepo(){ } private ClienteRepo clienteRepo; public static String createTable(){ return "CREATE TABLE "+ Cliente.TABLE + "(" +Cliente.KEY_CLIENTEID + " INTEGER PRIMARY KEY AUTOINCREMENT ," +Cliente.KEY_NOMBRE + "TEXT," +Cliente.KEY_APELLIDOP + "TEXT," +Cliente.KEY_APELLIDOM + "TEXT," +Cliente.KEY_CODIGO + "TEXT," +Cliente.KEY_RFC + "TEXT," +Cliente.KEY_TELEFONO + "TEXT," +Cliente.KEY_CALLE + "TEXT," +Cliente.KEY_FECHACR + "TEXT," +Cliente.KEY_FECHAAC + "TEXT," +Cliente.KEY_ESTADO + "TEXT," +Cliente.KEY_ZonaId + "TEXT," +Cliente.KEY_LocalID+ "TEXT," +Cliente.KEY_ColID + "TEXT)"; } public void insert(Cliente cliente){ SQLiteDatabase db = DatabaseManager.getInstance().openDatabase(); ContentValues values = new ContentValues(); values.put(Cliente.KEY_NOMBRE, cliente.getNombre()); values.put(Cliente.KEY_APELLIDOP, cliente.getApellidoP()); values.put(Cliente.KEY_APELLIDOM, cliente.getApellidoM()); values.put(Cliente.KEY_CODIGO, cliente.getCP()); values.put(Cliente.KEY_RFC, cliente.getRFC()); values.put(Cliente.KEY_TELEFONO, cliente.getTelefono()); values.put(Cliente.KEY_CALLE, cliente.getCalle()); values.put(Cliente.KEY_Colonia, cliente.getColonia()); values.put(Cliente.KEY_FECHACR, cliente.getFechaCr()); values.put(Cliente.KEY_FECHAAC, cliente.getFechaAc()); values.put(Cliente.KEY_ESTADO, cliente.getEstado()); values.put(Cliente.KEY_ZonaId, cliente.getZonaId()); db.insert(Cliente.TABLE, null,values); DatabaseManager.getInstance().closeDatabase(); } public void delete(){ SQLiteDatabase db = DatabaseManager.getInstance().openDatabase(); DatabaseManager.getInstance().closeDatabase(); } }
true
f66b022ec810dfd5b3acaa85b048bc7d9db10a38
Java
FER-Group-Projects/Don-Quixote
/src/main/java/hr/fer/zemris/projekt/model/ElmanNetwork/ElmanNeuralNetwork.java
UTF-8
2,999
3.0625
3
[]
no_license
package hr.fer.zemris.projekt.model.ElmanNetwork; import java.io.Serializable; import java.util.Arrays; public class ElmanNeuralNetwork implements Serializable { private int[] layout; private double[] contextLayer; public ElmanNeuralNetwork(int[] layout){ this.layout = Arrays.copyOf(layout, layout.length); contextLayer = new double[layout[1]]; this.layout[0]+= contextLayer.length; } public void setContextLayer(double[] contextLayer) { this.contextLayer = Arrays.copyOf(contextLayer, contextLayer.length); } public double[] getContextLayer() { return contextLayer; } //calculate the output of the neural network public double[] calcOutput(double[] inputs, double[] weights ){ checkArgs(inputs, weights); double[] layer_input=new double [inputs.length+ contextLayer.length]; double[] layer_output=new double [layout[1]]; System.arraycopy(inputs,0,layer_input,0,inputs.length); System.arraycopy(contextLayer,0,layer_input,inputs.length, contextLayer.length); int weightIndex = 0; for(int i=1; i<layout.length; i++){ for(int j=0; j<layout[i]; j++){ double bias=weights[weightIndex]; weightIndex++; double sum=0; for(int k=0; k<layer_input.length; k++){ sum+=weights[weightIndex]*layer_input[k]; weightIndex++; } sum+=bias; layer_output[j]=transfer_function(sum); } layer_input = new double [layer_output.length]; System.arraycopy(layer_output,0,layer_input,0,layer_output.length); if(i==layout.length-1){ break; } if(i==1){ System.arraycopy(layer_output,0, contextLayer,0,layer_output.length); } layer_output=new double[layout[i+1]]; } return layer_output.clone(); } //need to add the transfer fuction, for now it just returns the sum private double transfer_function(double sum){ return (1/( 1 + Math.pow(Math.E,(-1*sum)))); } //check that the args are valid private void checkArgs(double[] inputs, double[] weights){ if (layout[0] != inputs.length+ contextLayer.length){ throw new IllegalArgumentException("Invalid number of input values! Expected: " +layout[0] + " Received " + inputs.length); } int num = getNumberOfWeights(); if(num!=weights.length){ throw new IllegalArgumentException("Invalid number of weights! Expected: " +num+ " Recieved: " + weights.length); } } public int getNumberOfWeights() { int num = 0; for (int i = 1; i < layout.length; i++){ num += ((layout[i - 1]+1) * layout[i]); } return num; } }
true
a8500ee301859702b8bb57a29fdfc88288a3e4a0
Java
xyang4/renren-security
/renren-api/src/main/java/io/renren/modules/user/service/impl/UserServiceImpl.java
UTF-8
4,547
1.960938
2
[ "Apache-2.0" ]
permissive
/** * Copyright (c) 2016-2019 人人开源 All rights reserved. * <p> * https://www.renren.io * <p> * 版权所有,侵权必究! */ package io.renren.modules.user.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import io.renren.common.enums.UserEntityEnum; import io.renren.common.exception.RRException; import io.renren.common.utils.DateUtils; import io.renren.common.utils.R; import io.renren.common.utils.SpringContextUtils; import io.renren.modules.account.entity.AccountEntity; import io.renren.modules.account.service.AccountService; import io.renren.modules.system.service.IConfigService; import io.renren.modules.user.dao.AgentUserDao; import io.renren.modules.user.dao.UserDao; import io.renren.modules.user.entity.AgentUserEntity; import io.renren.modules.user.entity.UserEntity; import io.renren.modules.user.service.IUserService; import org.apache.commons.codec.digest.DigestUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import java.math.BigDecimal; import java.util.Date; import java.util.Map; @Service public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements IUserService { @Autowired private AgentUserDao agentUserDao; @Autowired private IConfigService configService; @Override public UserEntity queryByMobile(String mobile) { return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("mobile", mobile)); } // @Override // public Integer registeredQuickly(String mobile) { // UserEntity entity = new UserEntity(); // // TODO 账户初始化 // entity.setMobile(mobile); // entity.setPasswd(DigestUtils.sha256Hex(mobile.substring(mobile.length() - 7))); // save(entity); // return entity.getUserId(); // } /** * 全面校验用户:所有用户状态校验 */ public boolean overallCheckUser(UserEntity userEntity) { //校验用户状态 return userEntity.getStatus() == 1; } @Autowired UserDao userDao; @Override public Map<String, Object> getAccountBaseInfo(Integer userId, String mobile) { return userDao.getAccountBaseInfo(userId, mobile); } /** * 添加推荐人 * @param userId * @param mobile * @param nickName * @param pwd * @return */ @Override @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class) public R recommendUser(Integer userId, String mobile, String nickName, String pwd) { UserEntity userEntity = new UserEntity(); userEntity.setPasswd(DigestUtils.sha256Hex(pwd)); userEntity.setNickName(nickName); userEntity.setMobile(mobile); userEntity.setCreateTime(DateUtils.format(new Date(),DateUtils.DATE_TIME_PATTERN)); userEntity.setUserType(UserEntityEnum.UserType.PORTER.getValue()); userEntity.setUserLevel(1); userEntity.setStatus(1); userEntity.setUserGroup(1); int r = userDao.insert(userEntity); if(r>0){ AccountEntity accountEntity = new AccountEntity(); accountEntity.setUserId(userEntity.getUserId()); accountEntity.setCreateTime(DateUtils.format(new Date(),DateUtils.DATE_TIME_PATTERN)); boolean rr = SpringContextUtils.getBean(AccountService.class).save(accountEntity); if(!rr){ throw new RRException("添加推荐人失败"); } AgentUserEntity agentUserEntity = new AgentUserEntity(); agentUserEntity.setAgentId(userId); agentUserEntity.setUserId(userEntity.getUserId()); agentUserEntity.setCreateTime(DateUtils.format(new Date(),DateUtils.DATE_TIME_PATTERN)); agentUserEntity.setModifyTime(DateUtils.format(new Date(),DateUtils.DATE_TIME_PATTERN)); //添加默认收益费率 String recvRate = configService.selectConfigByKey("recv_mer_chargeRate");//公共收益率 agentUserEntity.setRecvChargeRate(recvRate == null ? new BigDecimal(0) : new BigDecimal(recvRate)); int rrr = agentUserDao.insert(agentUserEntity); if(rrr < 1){ throw new RRException("添加推荐人失败"); } } return R.ok(); } }
true
219447e72ccf65063f6ec6c04c343707fee1ba3b
Java
GMasthan/FlightPro
/FlightPro/src/main/java/com/cg/flight/dao/AirportDao.java
UTF-8
524
1.882813
2
[]
no_license
package com.cg.flight.dao; 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 com.cg.flight.entity.Airport; @Repository public interface AirportDao extends JpaRepository<Airport, String>{ //airport @Query("from Airport where airportCode=:sairport") public Airport getAirport(@Param("sairport") String sourceAirport); }
true
7173abfa5474052ff650df85184d97fce7154cdc
Java
hmsck/gosu-lang
/gosu-lab/src/main/java/editor/search/AbstractSearcher.java
UTF-8
1,996
2.328125
2
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer", "BSD-3-Clause" ]
permissive
package editor.search; import editor.FileTree; import editor.FileTreeUtil; import editor.NodeKind; import editor.util.IProgressCallback; import java.util.Collections; import java.util.List; import java.util.function.Predicate; /** */ public abstract class AbstractSearcher { public abstract boolean search( FileTree tree, SearchTree results ); public boolean searchTree( FileTree tree, SearchTree results, Predicate<FileTree> filter, IProgressCallback progress ) { return searchTrees( Collections.singletonList( tree ), results, filter, progress ); } public boolean searchTrees( List<FileTree> trees, SearchTree results, Predicate<FileTree> filter, IProgressCallback progress ) { if( progress != null && progress.isAbort() ) { return false; } boolean bFound = false; for( FileTree tree: trees ) { if( tree.isFile() && filter.test( tree ) ) { if( progress != null ) { progress.incrementProgress( tree.getName() ); } bFound = bFound | search( tree, results ); } else if( !tree.isLeaf() ) { if( searchTrees( tree.getChildren(), results, filter, progress ) ) { bFound = true; } } } return bFound; } protected SearchTree getOrMakePath( FileTree tree, SearchTree results ) { if( tree.getParent() != null ) { results = getOrMakePath( tree.getParent(), results ); } for( SearchTree child: results.getChildren() ) { SearchTree.SearchTreeNode node = child.getNode(); if( node != null && node.getFile() == tree ) { return child; } } SearchTree.SearchTreeNode node = new SearchTree.SearchTreeNode( tree, null ); SearchTree searchTree = new SearchTree( NodeKind.Directory, node ); results.addViaModel( searchTree ); return searchTree; } protected boolean isExcluded( FileTree tree ) { return !FileTreeUtil.isSupportedTextFile( tree ); } }
true
fe43fd6384025655ef2788b53408ff6ba8acee14
Java
cha63506/CompSecurity
/Photography/amazon_photos_source/src/com/squareup/okhttp/internal/http/SocketConnector$ConnectedSocket.java
UTF-8
1,036
1.953125
2
[]
no_license
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.squareup.okhttp.internal.http; import com.squareup.okhttp.Handshake; import com.squareup.okhttp.Protocol; import com.squareup.okhttp.Route; import java.net.Socket; import javax.net.ssl.SSLSocket; // Referenced classes of package com.squareup.okhttp.internal.http: // SocketConnector public static class handshake { public final Protocol alpnProtocol; public final Handshake handshake; public final Route route; public final Socket socket; public (Route route1, Socket socket1) { route = route1; socket = socket1; alpnProtocol = null; handshake = null; } public handshake(Route route1, SSLSocket sslsocket, Protocol protocol, Handshake handshake1) { route = route1; socket = sslsocket; alpnProtocol = protocol; handshake = handshake1; } }
true
cb6096ebaee35c9321420a900041b96bb321cb19
Java
JunHwaPark/AESExample
/app/src/test/java/com/junhwa/aesexample/AesUnitTest.java
UTF-8
663
2.390625
2
[]
no_license
package com.junhwa.aesexample; import org.junit.Test; import static org.junit.Assert.assertEquals; public class AesUnitTest { @Test public void encrypt_test() throws Exception{ assertEquals(Aes.encrypt(Aes.hexToByteArray("0f000101000000000000000000000000")), "09dccd7658c6878534eda38ddba1d47b"); } @Test public void decrypt_test() throws Exception{ assertEquals(Aes.decrypt(Aes.hexToByteArray("0f000101000000000000000000000000")), "2cffb904609377dcb0b953e23967119c"); } @Test public void byteToString() { assertEquals(Aes.byteArrayToHex(new byte[] {0x17, 0x18, (byte)0xff, 0x00}), "1718ff00"); } }
true
b2bdfcef18ab8761b6a0bce2da0229df5e709f20
Java
dingqing-ryan/Androider
/lib_core/src/main/java/com/ryan/core/helper/Listener.java
UTF-8
177
1.773438
2
[ "Apache-2.0" ]
permissive
package com.ryan.core.helper; /** * @Description: Result类作用描述 * @Author: yzh * @CreateDate: 2019/11/1 11:43 */ public interface Listener { void onResult(); }
true
111657502adc6c5069c7e57adf5c9faae57e117f
Java
Fedwar/FIM
/src/fleetmanagement/backend/repositories/disk/OnDiskPackageTypeRepository.java
UTF-8
3,943
2.546875
3
[]
no_license
package fleetmanagement.backend.repositories.disk; import fleetmanagement.backend.packages.PackageType; import fleetmanagement.backend.packages.PackageTypeRepository; import fleetmanagement.config.FimConfig; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.HashSet; import java.util.Properties; import java.util.Set; @Component public class OnDiskPackageTypeRepository implements PackageTypeRepository { private static final Logger logger = Logger.getLogger(OnDiskPackageTypeRepository.class); private final Set<PackageType> garbageCollection = new HashSet<>(); private final Set<PackageType> autoSync = new HashSet<>(); private String dataFile; private String autoSyncFile; @Autowired public OnDiskPackageTypeRepository(FimConfig config) throws IOException { this(config.getDataDirectory()); } OnDiskPackageTypeRepository(File dataDirectory) throws IOException { this.dataFile = dataDirectory.getPath() + File.separator + "datatype.properties"; this.autoSyncFile = dataDirectory.getPath() + File.separator + "autosync.properties"; try { loadSettings(this.dataFile, this.garbageCollection); } catch (FileNotFoundException e) { logger.warn("Can't load package types settings. GC is disabled."); return; } try { loadSettings(this.autoSyncFile, this.autoSync); } catch (FileNotFoundException e) { logger.warn("Can't load package automatic synchronization settings. Automatic synchronization is disabled."); } } private void loadSettings(String filename, Set<PackageType> list) throws IOException { list.clear(); Properties properties = new Properties(); properties.load(new FileInputStream(filename)); for (String key : properties.stringPropertyNames()) { list.add(PackageType.getByResourceKey(key)); } } @Override public void enableGC(PackageType packageType) { garbageCollection.add(packageType); } @Override public void disableGC(PackageType packageType) { garbageCollection.remove(packageType); } @Override public void enableAutoSync(PackageType packageType) { autoSync.add(packageType); } @Override public void disableAutoSync(PackageType packageType) { autoSync.remove(packageType); } @Override public boolean isGCEnabled(PackageType packageType) { return garbageCollection.contains(packageType); } @Override public boolean isAutoSyncEnabled(PackageType packageType) { return autoSync.contains(packageType); } @Override public void disableAll() { garbageCollection.clear(); } @Override public void disableAllAutoSync() { autoSync.clear(); } private void saveSettings(String filename, Set<PackageType> list) throws IOException { Properties properties = new Properties(); for (PackageType packageType: list) { properties.put(packageType.getResourceKey(), "1"); } properties.store(new FileOutputStream(filename), null); } public void save() throws IOException { try { saveSettings(dataFile, garbageCollection); } catch (FileNotFoundException e) { logger.error("Datatypes properties file not found!", e); throw e; } try { saveSettings(autoSyncFile, autoSync); } catch (FileNotFoundException e) { logger.error("Automatic synchronization properties file not found!", e); throw e; } } }
true
7347f2afb2c84c874b25b141397c9062e0f77125
Java
pedrolyma/story-apils
/src/main/java/com/storyapils/model/GeneroProduto.java
UTF-8
93
1.757813
2
[]
no_license
package com.storyapils.model; public enum GeneroProduto { Feminino, Masculino, Unisex }
true
b9f4dfcddb1a8c3ad20014f2313154741d710d7f
Java
hldni/ny-cloud
/admin/src/main/java/com/nycloud/admin/model/SysRole.java
UTF-8
383
1.8125
2
[]
no_license
package com.nycloud.admin.model; import lombok.Data; import javax.persistence.Id; import javax.validation.constraints.NotEmpty; @Data public class SysRole { @Id private Integer id; @NotEmpty(message = "角色名称不能为空") private String name; @NotEmpty(message = "角色编码不能为空") private String code; private String description; }
true
85ef36ae74592a4ecbf9e9fa4ac171733eb27ea9
Java
LowTix/palabox-plugin
/PalaBox/src/fr/lowtix/palabox/listeners/DeathListener.java
UTF-8
1,970
2.734375
3
[]
no_license
package fr.lowtix.palabox.listeners; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.PlayerDeathEvent; import fr.lowtix.palabox.Main; import fr.lowtix.palabox.enumerations.Locations; import fr.lowtix.palabox.users.GameUser; public class DeathListener implements Listener { @EventHandler public void onDeath(PlayerDeathEvent event) { Player player = event.getEntity(); GameUser user = Main.getInstance().getGameUser(player); user.getStats().setDeaths(user.getStats().getDeaths() + 1); user.getStats().setCurrentStreak(0); if(player.getKiller() == null) { player.sendMessage("§8[§6§l!§8] §7Vous vous êtes suicidé."); playerDeath(player); } else { Player killer = player.getKiller(); GameUser killerUser = Main.getInstance().getGameUser(killer); killerUser.getStats().setKills(killerUser.getStats().getDeaths() + 1); killerUser.getStats().setCurrentStreak(killerUser.getStats().getCurrentStreak() + 1); if(killerUser.getStats().getMaxStreak() < killerUser.getStats().getCurrentStreak()) { killerUser.getStats().setMaxStreak(killerUser.getStats().getCurrentStreak()); } player.sendMessage("§8[§6§l!§8] §f" + killerUser.getRank().getPrefixColor() + killerUser.getRank().getPrefix() + " "+killer.getName()+" §7vous a tué."); killer.sendMessage("§8[§6§l!§8] §7Elimination de §f" + user.getRank().getPrefixColor() + user.getRank().getPrefix() + " "+player.getName()); playerDeath(player); } } private void playerDeath(Player player) { player.spigot().respawn(); player.setBedSpawnLocation(Main.getInstance().getLocationsConfiguration().getSavedLocation(Locations.SPAWN_LOCATION)); player.teleport(Main.getInstance().getLocationsConfiguration().getSavedLocation(Locations.SPAWN_LOCATION)); } }
true
85097f5c73b3593c083fd903ca34c9549dd95cb4
Java
gizmomogwai/GetPix
/lib/src/main/java/com/flopcode/getpix/NoopLogging.java
UTF-8
326
1.96875
2
[ "MIT" ]
permissive
package com.flopcode.getpix; /** * Created by gizmo on 25/09/16. */ class NoopLogging implements Logging { @Override public void error(String tag, String msg, Exception e) { } @Override public void info(String logTag, String s, Exception e) { } @Override public void debug(String tag, String msg) { } }
true
99881939051e2dcc8c95700cb6e6e59e90dc7eef
Java
pcieszynski/tablettop-2
/src/main/java/com/ender/tablettop/domain/Monster.java
UTF-8
2,959
2.59375
3
[]
no_license
package com.ender.tablettop.domain; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import javax.persistence.*; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import java.util.Objects; /** * A Monster. */ @Entity @Table(name = "monster") public class Monster implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator") @SequenceGenerator(name = "sequenceGenerator") private Long id; @Column(name = "current_hp") private Integer currentHP; @ManyToOne @JsonIgnoreProperties("monsters") private MonsterType type; @ManyToMany(mappedBy = "monsters") @JsonIgnore private Set<Battle> battles = new HashSet<>(); // jhipster-needle-entity-add-field - JHipster will add fields here, do not remove public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Integer getCurrentHP() { return currentHP; } public Monster currentHP(Integer currentHP) { this.currentHP = currentHP; return this; } public void setCurrentHP(Integer currentHP) { this.currentHP = currentHP; } public MonsterType getType() { return type; } public Monster type(MonsterType monsterType) { this.type = monsterType; return this; } public void setType(MonsterType monsterType) { this.type = monsterType; } public Set<Battle> getBattles() { return battles; } public Monster battles(Set<Battle> battles) { this.battles = battles; return this; } public Monster addBattle(Battle battle) { this.battles.add(battle); battle.getMonsters().add(this); return this; } public Monster removeBattle(Battle battle) { this.battles.remove(battle); battle.getMonsters().remove(this); return this; } public void setBattles(Set<Battle> battles) { this.battles = battles; } // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Monster monster = (Monster) o; if (monster.getId() == null || getId() == null) { return false; } return Objects.equals(getId(), monster.getId()); } @Override public int hashCode() { return Objects.hashCode(getId()); } @Override public String toString() { return "Monster{" + "id=" + getId() + ", currentHP=" + getCurrentHP() + "}"; } }
true
15273dbb0d7c275bae63cb9313c5d98ae65aa9ea
Java
itduoduo/wechat-demo
/src/main/java/com/ssz/wechat/wechatdemo/quartz/ScheduledTaskOfGetAccessToken.java
UTF-8
2,439
2.171875
2
[ "Apache-2.0" ]
permissive
package com.ssz.wechat.wechatdemo.quartz; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.stereotype.Component; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.ssz.wechat.wechatdemo.commom.WeChatConfig; import com.ssz.wechat.wechatdemo.redis.RedisUtil; import com.ssz.wechat.wechatdemo.util.HttpUtils; @Component @Configuration @EnableScheduling public class ScheduledTaskOfGetAccessToken { private static Logger logger = LoggerFactory.getLogger(ScheduledTaskOfGetAccessToken.class); @Autowired private RedisUtil redisUtil; @Autowired private WeChatConfig weChatConfig; public void getAccessToken() { try { logger.info("get accessToken begin ......"); Map<String, String> params = new HashMap<String, String>(); // 获取token执行体 params.put("grant_type", "client_credential"); params.put("appid", weChatConfig.getAppId()); params.put("secret", weChatConfig.getAppSecret()); String jsTokenStr; jsTokenStr = HttpUtils.sendGet(weChatConfig.getTokenUrl(), params); logger.info("get accessToken token: " + jsTokenStr); JSONObject jsTokenObj = JSON.parseObject(jsTokenStr); String access_token = jsTokenObj.getString("access_token"); redisUtil.set("access_token", access_token); // 获取jsticket的执行体 params.clear(); params.put("access_token", access_token); params.put("type", "jsapi"); String jsApiTicket = HttpUtils.sendGet(weChatConfig.getTicketUrl(), params); logger.info("get accessToken jsApiTicket: " + jsApiTicket); JSONObject jsApiTicketObj = JSON.parseObject(jsApiTicket); String ticket = jsApiTicketObj.getString("ticket"); redisUtil.set("jsapi_ticket", ticket); logger.info("get accessToken end ......"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); logger.info("get accessToken error ......"); } } }
true
aef5a786fe6c5b145fe4cca5c25be17b679e882f
Java
smshen/otg
/otg/src/test/java/com/springtour/otg/infrastructure/persistence/ibatis/IBatisChannelRepositoryImplIntegrationTests.java
UTF-8
2,819
1.914063
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.springtour.otg.infrastructure.persistence.ibatis; import com.springtour.otg.FixtureClearer; import com.springtour.otg.domain.model.channel.Channel; import com.springtour.otg.domain.model.channel.ChannelFixture; import com.springtour.otg.domain.model.channel.Gateway; import com.springtour.otg.domain.model.channel.Gateways; import com.springtour.otg.infrastructure.persistence.ibatis.IBatisChannelRepositoryImpl; import com.springtour.otg.integration.*; import java.util.Arrays; import java.util.List; import javax.annotation.Resource; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class IBatisChannelRepositoryImplIntegrationTests extends AbstractOtgApplicationContextIntegrationTests { @Resource(name = "otg.IBatisChannelRepositoryImpl") private IBatisChannelRepositoryImpl target; @Resource(name = "jdbcFixtureClearer") private FixtureClearer fixtureClearer; private static Channel EXPECT; @Before public void resetFixture() throws Exception { Channel expect = new ChannelFixture().build(); fixtureClearer.clear("t_otg_channel", new String[]{"id"}, new String[]{expect.getId()}); target.store(expect); EXPECT = expect; } @Test //@Rollback(true) public void updateAvailableCurrencies() throws Exception { Channel reconsititute = assertResetFixture(); final String currencies = "CNY"; reconsititute.updateAvailableCurrencies(currencies); update(reconsititute); Channel actual = target.find(EXPECT.getId()); Assert.assertTrue(new ChannelMatcher().matchesSafely(reconsititute, actual)); } @Test public void updateGateways() throws Exception { Channel reconsititute = assertResetFixture(); final List<Gateway> gateways = Arrays.asList(new Gateway(Gateways.ABC, "YX", 0), new Gateway(Gateways.BOC, "XX", 1)); reconsititute.updateGateways(gateways); update(reconsititute); Channel actual = target.find(EXPECT.getId()); Assert.assertTrue(new ChannelMatcher().matchesSafely(reconsititute, actual)); } private Channel assertResetFixture() { Channel reconsititute = target.find(EXPECT.getId()); Assert.assertTrue(new ChannelMatcher().matchesSafely(EXPECT, reconsititute)); return reconsititute; } private void update(Channel channel) throws Exception { target.store(channel); addVersion(channel); } private void addVersion(Channel channel) { channel.setVersion(channel.getVersion() + 1); } }
true
75db590c4c794c71fe41b575a695dc2c0f52453f
Java
liukang83254/demo
/src/main/java/cn/net/ohf/dao/TestTableMapper.java
UTF-8
921
1.914063
2
[]
no_license
package cn.net.ohf.dao; import cn.net.ohf.pojo.TestTable; import cn.net.ohf.pojo.TestTableExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface TestTableMapper { int countByExample(TestTableExample example); int deleteByExample(TestTableExample example); int deleteByPrimaryKey(Integer id); int insert(TestTable record); int insertSelective(TestTable record); List<TestTable> selectByExample(TestTableExample example); TestTable selectByPrimaryKey(Integer id); int updateByExampleSelective(@Param("record") TestTable record, @Param("example") TestTableExample example); int updateByExample(@Param("record") TestTable record, @Param("example") TestTableExample example); int updateByPrimaryKeySelective(TestTable record); int updateByPrimaryKey(TestTable record); List<TestTable> selectAll(); }
true
776d583147fb575a4638b6722d1e9acb9ad2ac4c
Java
snuk182/aceim
/app/src/main/java/aceim/app/screen/tablet/TabletScreen.java
UTF-8
8,939
1.820313
2
[ "Apache-2.0" ]
permissive
package aceim.app.screen.tablet; import static aceim.app.utils.linq.KindaLinq.from; import java.util.ArrayList; import java.util.List; import aceim.app.MainActivity; import aceim.app.R; import aceim.app.screen.Screen; import aceim.app.utils.PageManager; import aceim.app.utils.linq.KindaLinqRule; import aceim.app.view.page.Page; import aceim.app.view.page.contactlist.ContactList; import aceim.app.view.page.other.Splash; import aceim.app.widgets.bottombar.BottomBarButton; import aceim.app.widgets.pageselector.PageAdapter; import aceim.app.widgets.pageselector.TabSelector; import android.annotation.SuppressLint; import android.os.Build; import android.os.Bundle; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewConfiguration; public class TabletScreen extends Screen { private final PageAdapter mPageAdapterLeft; private final TabSelector mTabHolderLeft; private final PageManager mPageManagerLeft; private final PageAdapter mPageAdapterRight; private final TabSelector mTabHolderRight; private final PageManager mPageManagerRight; private final BottomBarButton mMenuButton; private final OnHierarchyChangeListener mTabChangedListener = new OnHierarchyChangeListener() { @Override public void onChildViewRemoved(View parent, View child) { if (parent == mTabHolderLeft) { findViewById(R.id.fragment_holder_left).setBackgroundResource(mPageAdapterLeft.getCount() > 0 ? 0 : R.drawable.cornered_background); } else { findViewById(R.id.fragment_holder_right).setBackgroundResource(mPageAdapterRight.getCount() > 0 ? 0 : R.drawable.cornered_background); } } @Override public void onChildViewAdded(View parent, View child) { if (parent == mTabHolderLeft) { mTabHolderLeft.setSelectedPage((Page) child.getTag()); findViewById(R.id.fragment_holder_left).setBackgroundResource(0); } else { mTabHolderRight.setSelectedPage((Page) child.getTag()); findViewById(R.id.fragment_holder_right).setBackgroundResource(0); } } }; public TabletScreen(MainActivity activity) { super(activity); LayoutInflater.from(activity).inflate(R.layout.screen_tablet, this); mMenuButton = (BottomBarButton) findViewById(R.id.menu_button); mMenuButton.setOnClickListener(mMenuButtonClickListener); mMenuButton.setOnLongClickListener(mMenuButtonLongClickListener); mTabHolderLeft = (TabSelector) findViewById(R.id.tab_selector_left); mPageManagerLeft = new PageManager(R.id.fragment_holder_left, activity); mPageAdapterLeft = new PageAdapter(activity, mTabClickListener, activity.getThemesManager().getViewResources().getTabItemLayout(), mPageManagerLeft.getPages()); mPageAdapterLeft.setNotifyOnChange(true); mTabHolderLeft.setPageAdapter(mPageAdapterLeft); mTabHolderLeft.setOnHierarchyChangeListener(mTabChangedListener); mTabHolderRight = (TabSelector) findViewById(R.id.tab_selector_right); mPageManagerRight = new PageManager(R.id.fragment_holder_right, activity); mPageAdapterRight = new PageAdapter(activity, mTabClickListener, activity.getThemesManager().getViewResources().getTabItemLayout(), mPageManagerRight.getPages()); mPageAdapterRight.setNotifyOnChange(true); mTabHolderRight.setPageAdapter(mPageAdapterRight); mTabHolderRight.setOnHierarchyChangeListener(mTabChangedListener); } @Override public void addPage(Page page, boolean setAsCurrent) { String pageId = page.getPageId(); if (findPage(pageId) == null) { if (page instanceof ContactList) { mPageAdapterLeft.add(page); } else { mPageAdapterRight.add(page); } } if (setAsCurrent) { setSelectedPage(pageId); } if (!(page instanceof Splash)) { setMenuButtonAvailability(); } } @Override public Page findPage(final String pageId) { return from(getAllPages()).where(new KindaLinqRule<Page>() { @Override public boolean match(Page t) { return t.getPageId().equals(pageId); } }).first(); } @Override public void onPageChanged(String pageId) { if (pageId.startsWith(ContactList.class.getSimpleName())) { mPageManagerLeft.onPageChanged(findPage(mPageManagerLeft.getPages(), pageId)); } else { mPageManagerRight.onPageChanged(findPage(mPageManagerRight.getPages(), pageId)); } } @Override public void setSelectedPage(String pageId) { onPageChanged(pageId); if (pageId.startsWith(ContactList.class.getSimpleName())) { Page page = findPage(mPageManagerLeft.getPages(), pageId); mTabHolderLeft.setSelectedPage(page); } else { Page page = findPage(mPageManagerRight.getPages(), pageId); mTabHolderRight.setSelectedPage(page); } } @Override public List<Page> findPagesByRule(KindaLinqRule<Page> rule) { return from(getAllPages()).where(rule).all(); } @Override public Page getSelectedPage() { return mPageManagerRight.getSelectedPage() != null ? mPageManagerRight.getSelectedPage() : mPageManagerLeft.getSelectedPage(); } @Override public Page getSelectedContactList() { return mPageManagerLeft.getSelectedPage(); } @Override public void removePage(Page page) { if (mPageManagerRight.getPages().contains(page)) { mPageAdapterRight.remove(page); mPageManagerRight.onPageRemoved(page); if (mPageAdapterRight.getCount() > 0) { setSelectedPage(mPageManagerRight.getPages().get(0).getPageId()); } } else { mPageAdapterLeft.remove(page); mPageManagerLeft.onPageRemoved(page); if (mPageAdapterLeft.getCount() > 0) { setSelectedPage(mPageManagerLeft.getPages().get(0).getPageId()); } } if (mPageAdapterLeft.getCount() + mPageAdapterRight.getCount() < 1) { getActivity().exitApplication(); } } @Override public void updateTabWidget(Page p) { if (mPageManagerLeft.getPages().contains(p)) { View tabWidget = mTabHolderLeft.findViewWithTag(p); mPageAdapterLeft.fillWithImageAndTitle(tabWidget, p); } else { View tabWidget = mTabHolderRight.findViewWithTag(p); mPageAdapterRight.fillWithImageAndTitle(tabWidget, p); } } @SuppressWarnings("serial") @Override public List<Page> getAllPages() { return new ArrayList<Page>(mPageAdapterLeft.getCount() + mPageAdapterRight.getCount()){ { addAll(mPageManagerLeft.getPages()); addAll(mPageManagerRight.getPages()); } }; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) { Page leftSelectedPage = mPageManagerLeft.getSelectedPage(); Page rightSelectedPage = mPageManagerRight.getSelectedPage(); if (rightSelectedPage != null) { rightSelectedPage.onCreateOptionsMenu(menu, menuInflater); } if (leftSelectedPage != null) { leftSelectedPage.onCreateOptionsMenu(menu, menuInflater); } } @Override public void onPrepareOptionsMenu(Menu menu) { Page leftSelectedPage = mPageManagerLeft.getSelectedPage(); Page rightSelectedPage = mPageManagerRight.getSelectedPage(); if (rightSelectedPage != null && rightSelectedPage.hasMenu()) { rightSelectedPage.onPrepareOptionsMenu(menu); } if (leftSelectedPage != null) { leftSelectedPage.onPrepareOptionsMenu(menu); } } @Override public void onOptionsItemSelected(MenuItem item) { Page leftSelectedPage = mPageManagerLeft.getSelectedPage(); Page rightSelectedPage = mPageManagerRight.getSelectedPage(); if (rightSelectedPage != null) { rightSelectedPage.onOptionsItemSelected(item); } if (leftSelectedPage != null) { leftSelectedPage.onOptionsItemSelected(item); } } @Override public boolean onCurrentPageKeyDown(int i, KeyEvent event) { Page leftSelectedPage = mPageManagerLeft.getSelectedPage(); Page rightSelectedPage = mPageManagerRight.getSelectedPage(); if (rightSelectedPage != null) { return rightSelectedPage.onKeyDown(i, event); } if (leftSelectedPage != null) { return leftSelectedPage.onKeyDown(i, event); } return false; } @Override public void storeScreenSpecificData(Bundle bundle) {} @Override public void recoverScreenSpecificData(Bundle bundle) {} private Page findPage(List<Page> pages, final String pageId) { return from(pages).where(new KindaLinqRule<Page>() { @Override public boolean match(Page t) { return t.getPageId().equals(pageId); } }).first(); } @SuppressLint("NewApi") private void setMenuButtonAvailability() { mMenuButton.setVisibility( Build.VERSION.SDK_INT <= 10 || (Build.VERSION.SDK_INT >= 14 && ViewConfiguration.get(getContext()).hasPermanentMenuKey()) ? View.GONE : View.VISIBLE); } }
true
60f510b70407b35c0dd36af7af5fd29cc04f264d
Java
reginatojames/tsam-oojava
/Azienda/src/reginato/james/azienza/Test.java
UTF-8
779
2.4375
2
[]
no_license
package reginato.james.azienza; public class Test { public static void main(String[] args) { // TODO Auto-generated method stub Azienda microsoft = new Azienda(); microsoft.setpIva("0000000001"); microsoft.setRagoioneSociale("Microsoft snc"); ContrattoLavoro contratto = new ContrattoLavoro(); contratto.setPagaBase(600*100); contratto.setTipo("Apprendista"); Dipendente bill = new Dipendente(); bill.setCognome("Gates"); bill.setNome("Bill"); bill.setContratto(contratto); Dipendente steve = new Dipendente(); steve.setCognome("Jobs"); steve.setNome("Steve"); steve.setContratto(contratto); Dipendente[] dips = new Dipendente[]{bill, steve}; microsoft.setDipendenti(dips); System.out.println(microsoft.stipendi()); } }
true
d4ec2d1b9792b8ceddc99b4ddce255bba2773281
Java
everlen/Sistema_Manad
/DAO/Conexao.java
UTF-8
1,552
2.5
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 DAO; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Everlen */ public class Conexao { protected Connection con; protected Statement st; protected String query; public Conexao() { try{ final String URL = "jdbc:mysql://localhost/bd_manad?zeroDateTimeBehavior=round"; final String DRIVER = "com.mysql.jdbc.Driver"; final String USUARIO = "root"; final String SENHA = ""; Class.forName(DRIVER); con = DriverManager.getConnection(URL,USUARIO,SENHA); st = con.createStatement(); } catch(Exception e){ e.printStackTrace(); } } public boolean Max_connections(int valor){ PreparedStatement ps = null; try { query = "set global max_connections = ?;"; ps = con.prepareStatement(query); ps.setInt(1, valor); if (ps.executeUpdate()>0){ return true; } } catch (SQLException ex) { Logger.getLogger(Conexao.class.getName()).log(Level.SEVERE, null, ex); } return false; } }
true
b30886dcc44ebbed5cb2ec016aad23489c7f5d27
Java
toyangel0710/diuit.uikit.demo.android
/app/src/main/java/diuit/duolc/com/myapplication/DirectChatSettingActivity.java
UTF-8
5,846
2.171875
2
[ "Apache-2.0" ]
permissive
package diuit.duolc.com.myapplication; import android.app.Activity; import android.app.ProgressDialog; import android.graphics.PorterDuff; import android.os.Build; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.widget.CompoundButton; import android.widget.Switch; import com.duolc.DiuitChat; import com.duolc.DiuitMessagingAPI; import com.duolc.DiuitMessagingAPICallback; import com.duolc.DiuitUser; import com.duolc.diuitapi.messageui.setting.DiuitParticipantSettingView; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; /** * Created by doulc on 5/20/16. */ public class DirectChatSettingActivity extends Activity { private DiuitParticipantSettingView settingView; private DiuitChat currentChat; private DiuitUser diuitUser; private Switch blockSwitch; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.initializeView(); this.currentChat = Utils.selectedChat; /** * Step1. initialize DiuitUser **/ this.initializeDiuitUser(); /** * Step2. Bind DiuitUser with DiuitParticipantSettingView **/ this.settingView.bindUser(this.diuitUser).load(); /** * Step3. Check Block Status **/ boolean isBlockedByMe = DiuitMessagingAPI.getCurrentUser().getBlockList().contains(this.diuitUser.getSerial()); this.blockSwitch.setChecked(isBlockedByMe); /** * Step4. Implement Block event **/ blockSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(Build.VERSION.SDK_INT >= 16) { int thumbColor = isChecked ? R.color.diu_block_switch_check_thumb : R.color.diu_block_switch_uncheck_thumb; blockSwitch.getThumbDrawable().setColorFilter(ContextCompat.getColor(DirectChatSettingActivity.this, thumbColor), PorterDuff.Mode.MULTIPLY); int trackColor = isChecked ? R.color.diu_block_switch_check_track: R.color.diu_block_switch_uncheck_track; blockSwitch.getTrackDrawable().setColorFilter( ContextCompat.getColor(DirectChatSettingActivity.this, trackColor), PorterDuff.Mode.MULTIPLY); } ArrayList<String> blockList = DiuitMessagingAPI.getCurrentUser().getBlockList(); if(isChecked) { if( !blockList.contains(diuitUser.getSerial()) ) block(); } else { if( blockList.contains(diuitUser.getSerial()) ) unblock(); } } }); } private void initializeView() { this.setContentView(R.layout.activity_direct_chat_setting); this.settingView = (DiuitParticipantSettingView) this.findViewById(R.id.diuitSettingView); this.blockSwitch = this.settingView.getBlockSwitch(); } private void initializeDiuitUser() { try { JSONObject userObj = new JSONObject(); userObj.put("serial", currentChat.getMemberSerials().get(0) ); JSONObject metaObj = new JSONObject(); metaObj.put("name", currentChat.getMemberSerials().get(0) ); userObj.put("meta", metaObj); this.diuitUser = new DiuitUser(userObj); } catch (JSONException e) { e.printStackTrace();} } private void block() { final ProgressDialog progress = ProgressDialog.show(this, "Blocking", "", true, false); DiuitMessagingAPI.block(diuitUser.getSerial(), new DiuitMessagingAPICallback<JSONObject>() { @Override public void onSuccess(JSONObject result) { DirectChatSettingActivity.this.runOnUiThread(new Runnable() { @Override public void run() { progress.dismiss(); DiuitMessagingAPI.getCurrentUser().getBlockList().add(diuitUser.getSerial()); } }); } @Override public void onFailure(final int code, final JSONObject result) { DirectChatSettingActivity.this.runOnUiThread(new Runnable() { @Override public void run() { Utils.showErrorToast(DirectChatSettingActivity.this, code, result); progress.dismiss(); } }); } }); } private void unblock() { final ProgressDialog progress = ProgressDialog.show(this, "Unblocking", "", true, false); DiuitMessagingAPI.unblock(diuitUser.getSerial(), new DiuitMessagingAPICallback<JSONObject>() { @Override public void onSuccess(JSONObject result) { DirectChatSettingActivity.this.runOnUiThread(new Runnable() { @Override public void run() { progress.dismiss(); DiuitMessagingAPI.getCurrentUser().getBlockList().remove(diuitUser.getSerial()); } }); } @Override public void onFailure(final int code, final JSONObject result) { DirectChatSettingActivity.this.runOnUiThread(new Runnable() { @Override public void run() { Utils.showErrorToast(DirectChatSettingActivity.this, code, result); progress.dismiss(); } }); } }); } }
true
f65bfa9c16b18a314a20d38d33f475e09aaf606d
Java
eifel3577/ReactionTimeX
/core/src/com/argo_entertainment/reactiontime/ActionResolver.java
UTF-8
541
1.609375
2
[]
no_license
package com.argo_entertainment.reactiontime; import com.badlogic.gdx.math.Vector2; public interface ActionResolver { public boolean getSignedInGPGS(); public void loginGPGS(); public void silentLoginGPGS(); public void showLeaderboard(); public void showPop(); public void submitScoreGPGS(int score); public void buyCoins(int coins); public void unlockAchievementGPGS(String achievementId); public void getLeaderboardGPGS(); public void getAchievementsGPGS(); public Vector2 getSceenOffset(); }
true
42ce7457d7074fd3851350c466709e69e61a263e
Java
libill/DebugAndroidFramework
/app/src/main/java/com/android/net/module/util/structs/TcpHeader.java
UTF-8
3,502
2.171875
2
[]
no_license
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.net.module.util.structs; import com.android.net.module.util.Struct; import com.android.net.module.util.Struct.Field; import com.android.net.module.util.Struct.Type; /** * L4 TCP header as per https://tools.ietf.org/html/rfc793. * This class does not contain option and data fields. * * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Source Port | Destination Port | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Sequence Number | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Acknowledgment Number | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Data | |U|A|P|R|S|F| | * | Offset| Reserved |R|C|S|S|Y|I| Window | * | | |G|K|H|T|N|N| | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Checksum | Urgent Pointer | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Options | Padding | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | data | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ public class TcpHeader extends Struct { @Field(order = 0, type = Type.U16) public final int srcPort; @Field(order = 1, type = Type.U16) public final int dstPort; @Field(order = 2, type = Type.U32) public final long seq; @Field(order = 3, type = Type.U32) public final long ack; @Field(order = 4, type = Type.S16) // data Offset (4 bits), reserved (6 bits), control bits (6 bits) // TODO: update with bitfields once class Struct supports it public final short dataOffsetAndControlBits; @Field(order = 5, type = Type.U16) public final int window; @Field(order = 6, type = Type.S16) public final short checksum; @Field(order = 7, type = Type.U16) public final int urgentPointer; public TcpHeader(final int srcPort, final int dstPort, final long seq, final long ack, final short dataOffsetAndControlBits, final int window, final short checksum, final int urgentPointer) { this.srcPort = srcPort; this.dstPort = dstPort; this.seq = seq; this.ack = ack; this.dataOffsetAndControlBits = dataOffsetAndControlBits; this.window = window; this.checksum = checksum; this.urgentPointer = urgentPointer; } }
true
93151b2859bae41ddcb734e1d01fe0215c1caeaf
Java
pankajpriyansh/YITS-IssueTracker
/yashissuetrackersystem-core/src/main/java/com/yash/yits/form/ProjectForm.java
UTF-8
678
2.109375
2
[]
no_license
package com.yash.yits.form; public class ProjectForm{ private Long projectId; private String projectDuration; private String projectName; public ProjectForm() { } public Long getProjectId() { return this.projectId; } public void setProjectId(Long projectId) { this.projectId = projectId; } public String getProjectDuration() { return this.projectDuration; } public void setProjectDuration(String projectDuration) { this.projectDuration = projectDuration; } public String getProjectName() { return this.projectName; } public void setProjectName(String projectName) { this.projectName = projectName; } }
true
24b3d6e8a351b21fb3a297e5f3a28e4302ff8c6b
Java
LazarJovic/literary-association
/Literary-Association-Application/src/main/java/goveed20/LiteraryAssociationApplication/utils/Coordinates.java
UTF-8
311
1.835938
2
[ "MIT" ]
permissive
package goveed20.LiteraryAssociationApplication.utils; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import java.util.List; @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class Coordinates { private List<Coordinate> data; }
true
e0641b946d78f368c752b0ce46eb6ba97c071e5e
Java
val100/webchick
/src/main/java/com/agrologic/app/web/ExpHistory24ToExcel.java
UTF-8
7,841
2.34375
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.agrologic.app.web; //~--- non-JDK imports -------------------------------------------------------- import com.agrologic.app.dao.FlockDao; import com.agrologic.app.dao.impl.FlockDaoImpl; import com.agrologic.app.model.DataFormat; import com.agrologic.app.model.FlockDto; import com.agrologic.app.excel.DataForExcelCreator; import com.agrologic.app.excel.WriteToExcel; import com.agrologic.app.utils.FileDownloadUtil; import org.apache.log4j.Logger; //~--- JDK imports ------------------------------------------------------------ import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.TreeMap; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author Administrator */ public class ExpHistory24ToExcel extends HttpServlet { private static final long serialVersionUID = 1L; private static String outfile; /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /** Logger for this class and subclasses */ final Logger logger = Logger.getLogger(ExpHistory24ToExcel.class); response.setContentType("text/html;charset=UTF-8"); long flockId = Long.parseLong(request.getParameter("flockId")); int growDay = 1; try { growDay = Integer.parseInt(request.getParameter("growDay")); } catch (Exception ex) { growDay = 1; } Locale locale = Locale.ENGLISH; try { FlockDao flockDao = new FlockDaoImpl(); Long resetTime = new Long(flockDao.getResetTime(flockId, growDay)); if (resetTime != null) { resetTime = DataFormat.convertToTimeFormat(resetTime); } else { resetTime = Long.valueOf("0"); } String values1 = flockDao.getHistory24(flockId, growDay, "D18"); String values2 = flockDao.getHistory24(flockId, growDay, "D19"); String values3 = flockDao.getHistory24(flockId, growDay, "D20"); String values4 = flockDao.getHistory24(flockId, growDay, "D21"); String values5 = flockDao.getHistory24(flockId, growDay, "D72"); values1 = getDefaultValuesIfEmpty(values1); values2 = getDefaultValuesIfEmpty(values2); values3 = getDefaultValuesIfEmpty(values3); values4 = getDefaultValuesIfEmpty(values4); values5 = getDefaultValuesIfEmpty(values5); String title1 = flockDao.getDNHistory24("D18"); String title2 = flockDao.getDNHistory24("D19"); String title3 = flockDao.getDNHistory24("D20"); String title4 = flockDao.getDNHistory24("D21"); String title5 = flockDao.getDNHistory24("D72"); Map<Integer, String> history24ByHour = parseHistory24(resetTime, values1); List<List<String>> allHistory24DataForExcel = new ArrayList<List<String>>(); allHistory24DataForExcel.add((DataForExcelCreator.createDataList(history24ByHour.keySet()))); history24ByHour = parseHistory24(resetTime, values1); allHistory24DataForExcel.add(DataForExcelCreator.createDataHistory24List(history24ByHour, DataFormat.DEC_1)); history24ByHour = parseHistory24(resetTime, values2); allHistory24DataForExcel.add(DataForExcelCreator.createDataHistory24List(history24ByHour, DataFormat.DEC_1)); history24ByHour = parseHistory24(resetTime, values3); allHistory24DataForExcel.add(DataForExcelCreator.createDataHistory24List(history24ByHour, DataFormat.HUMIDITY)); history24ByHour = parseHistory24(resetTime, values4); allHistory24DataForExcel.add(DataForExcelCreator.createDataHistory24List(history24ByHour, DataFormat.DEC_4)); history24ByHour = parseHistory24(resetTime, values5); allHistory24DataForExcel.add(DataForExcelCreator.createDataHistory24List(history24ByHour, DataFormat.DEC_4)); List<String> tableTitles = new ArrayList<String>(); tableTitles.add("Grow day " + growDay + "\nHour(24)"); tableTitles.add(title1); tableTitles.add(title2); tableTitles.add(title3); tableTitles.add(title4); tableTitles.add(title5); FlockDto flock = flockDao.getById(flockId); outfile = "c:/flock-" + flock.getFlockName() + "-history.xls"; WriteToExcel excel = new WriteToExcel(); excel.setTitleList(tableTitles); excel.setCellDataList(allHistory24DataForExcel); excel.setOutputFile(outfile); excel.write(); FileDownloadUtil.doDownload(response, outfile, "xls"); } catch (Exception e) { logger.error("Unknown error. ", e); } finally { response.getOutputStream().close(); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; } // </editor-fold> public String getDefaultValuesIfEmpty(String values) { if (values.equals("-1 ") || values.equals("")) { values = "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 "; } return values; } private Map<Integer, String> parseHistory24(long resetTime, String values) { String[] valueList = values.split(" "); Map<Integer, String> valuesMap = new TreeMap<Integer, String>(); int j = (int) resetTime / 100; for (int i = 0; i < 24; i++) { if (j == 24) { j = 0; } valuesMap.put(j++, valueList[i]); } return valuesMap; } } //~ Formatted by Jindent --- http://www.jindent.com
true
793cba8fd055b1e828019c19ad35d5289fef730f
Java
masharp/shoreside-apps
/apptlogJ/src/application/User.java
UTF-8
1,441
2.484375
2
[ "Apache-2.0" ]
permissive
package application; import com.j256.ormlite.dao.ForeignCollection; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.field.ForeignCollectionField; import com.j256.ormlite.table.DatabaseTable; @DatabaseTable(tableName = "users") public class User { public static final String USERNAME_FIELD_NAME = "username"; public static final String PASSWORD_FIELD_NAME = "password_hash"; @DatabaseField(generatedId = true) private int id; @DatabaseField(columnName = USERNAME_FIELD_NAME, canBeNull = false) private String username; @DatabaseField(columnName = PASSWORD_FIELD_NAME, canBeNull = false) private String passwordHash; @ForeignCollectionField private ForeignCollection<Log> logs; User() { //ORMlite persisted classes must define a no-arg constructor with at least package visibility } public User(String sUsername, String sPassword) { this.username = sUsername; this.passwordHash = Security.hashPassword(sPassword); } public int getId() { return id; } public String getUsername() { return username; } public void setUsername(String sUsername) { this.username = sUsername; } public String getPasswordHash() { return passwordHash; } public void setPassword(String sPassword) { this.passwordHash = Security.hashPassword(sPassword); } public ForeignCollection<Log> getLogs() { return logs; } @Override public int hashCode() { return username.hashCode(); } }
true
bda807f81ed96c4a76bb8bac1e1357aa17ff5b07
Java
raquelbromao/GrupoJava
/JavaBasico/src/org/javabasico/Exercicio04.java
UTF-8
462
3.125
3
[]
no_license
package org.javabasico; import java.lang.Math; import java.util.Scanner; public class Exercicio04 { public static void main(String[] args) { Scanner buffer = new Scanner(System.in); System.out.println("Digite x:"); float x = buffer.nextFloat(); System.out.println("Digite y:"); float y = buffer.nextFloat(); double conta = Math.pow(x, 120) / Math.sqrt(y); System.out.println("Resultado:"+conta); buffer.close(); } }
true
afb069adc134453dbcc8ff83368b6510a8b98912
Java
Ifgk1/Pacman
/src/de/infogk1/pacman/Game.java
UTF-8
575
1.976563
2
[]
no_license
package de.infogk1.pacman; public class Game implements Runnable{ private Board b; public static boolean gestoppt; public Game(){ gestoppt = false; b = new Board(); } @Override public void run() { Spriteloader.loadMaze(); while(!gestoppt){ if(!Var.pausiert) b.repaint(); if(Listener.keys.get("space").triggered){ gestoppt = true; System.exit(0); } try { Thread.sleep(10); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
true
37b953d3b595c49d3ba0bc75e3765ec9fbcdd01f
Java
lojack636/LeetCode-2
/question17/Solution.java
UTF-8
1,775
3.5
4
[]
no_license
package com.leetcode.question17; import java.util.*; public class Solution { public List<String> letterCombinations(String digits) { if(digits.length() == 0) return Collections.emptyList(); HashMap<Character, char[]> map = new HashMap<>(); map.put('2', new char[]{'a', 'b', 'c'}); map.put('3', new char[]{'d', 'e', 'f'}); map.put('4', new char[]{'g', 'h', 'i'}); map.put('5', new char[]{'j', 'k', 'l'}); map.put('6', new char[]{'m', 'n', 'o'}); map.put('7', new char[]{'p', 'q', 'r', 's'}); map.put('8', new char[]{'t', 'u', 'v'}); map.put('9', new char[]{'w', 'x', 'y', 'z'}); List<String> answer = letterCombinations(map, digits, 0); return answer; } private List<String> letterCombinations(Map<Character, char[]> map, String digits, int start) { if (start >= digits.length()) { return null; } List<String> backAnswer = letterCombinations(map, digits, start + 1); char[] currentWordGroup = map.get(digits.charAt(start)); LinkedList<String> answer = new LinkedList<>(); for (char c : currentWordGroup) { StringBuilder sb = new StringBuilder(); sb.append(c); if (backAnswer == null) { answer.add(sb.toString()); } else { for (String s : backAnswer) { StringBuilder temp = new StringBuilder(sb); temp.append(s); answer.add(temp.toString()); } } } return answer; } public static void main(String[] args) { Solution solution = new Solution(); solution.letterCombinations(new String("23")); } }
true
04852c3a939135880508c2e6bb695bc78aa89a57
Java
JohnNPhillips/OpenClicker
/app/src/main/java/edu/pitt/cs/cs1635/openclicker/Question.java
UTF-8
3,282
2.53125
3
[]
no_license
package edu.pitt.cs.cs1635.openclicker; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.support.v4.app.NotificationCompat; import android.support.v4.app.TaskStackBuilder; import java.util.Date; import java.util.Hashtable; import java.util.Set; import java.util.Map; import edu.pitt.cs.cs1635.openclicker.student.AnswerQuestionActivity; public class Question { public String text; public String[] answers; public int correct; public int seconds; private long startTime; private Hashtable<String, Integer> studentAnswers = new Hashtable<String, Integer>(); public Question(String text, String[] answers, int correct, int seconds) { this.text = text; this.answers = answers; this.correct = correct; this.seconds = seconds; } public Question(String text, String ans1, String ans2, String ans3, String ans4, String ans5, int correct, int seconds) { this(text, new String[]{ans1, ans2, ans3, ans4, ans5}, correct, seconds); } public void start() { startTime = new Date().getTime(); } public String[] getAnswers() { return answers; } public boolean hasBeenAsked() { return startTime != 0; } public int getTimeRemaining() { long elapsed = new Date().getTime() - startTime; return (int) (seconds - elapsed / 1000); } public void setStudentAnswer(String s, Integer answer) { studentAnswers.put(s, answer); } public int getStudentAnswer(String s) { if(studentAnswers.containsKey(s)) { return studentAnswers.get(s); } return -1; } public Set<Map.Entry<String, Integer>> getStudentsAnswers() { return studentAnswers.entrySet(); } public void notifyCurrentStudent(Context context) { // Build notification NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context); mBuilder.setSmallIcon(R.drawable.button); mBuilder.setContentTitle("OpenClicker"); mBuilder.setContentText(text); mBuilder.setAutoCancel(true); // Add action to be performed when notification is clicked Intent resultIntent = new Intent(context, AnswerQuestionActivity.class); TaskStackBuilder stackBuilder = TaskStackBuilder.create(context); stackBuilder.addParentStack(AnswerQuestionActivity.class); // Adds the Intent that starts the Activity to the top of the stack stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(resultPendingIntent); // Issue notification (this only sends a notification to the demo student; // in reality we would send it to all the students in the class) int notificationId = 100; // this could be the same as the student id NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager.notify(notificationId, mBuilder.build()); } }
true
fe7a177f54ca7dc6d0d26fe25f652572c92291c2
Java
SwellRT/swellrt
/wave/src/main/java/org/swellrt/beta/client/platform/web/SJsonObjectWeb.java
UTF-8
2,227
2.375
2
[ "BSD-3-Clause", "Apache-2.0", "LicenseRef-scancode-generic-export-compliance" ]
permissive
package org.swellrt.beta.client.platform.web; import org.swellrt.beta.model.json.SJsonObject; import org.waveprotocol.wave.client.common.util.JsoView; public class SJsonObjectWeb implements SJsonObject { private final JsoView jso; public SJsonObjectWeb() { this.jso = JsoView.create(); } protected SJsonObjectWeb(JsoView jso) { this.jso = jso; } @Override public SJsonObject addInt(String name, int value) { jso.setNumber(name, value); return this; } @Override public SJsonObject addLong(String name, long value) { jso.setNumber(name, value); return this; } @Override public SJsonObject addBoolean(String name, boolean value) { jso.setBoolean(name, value); return this; } @Override public SJsonObject addString(String name, String value) { jso.setString(name, value); return this; } @Override public SJsonObject addDouble(String name, Double value) { jso.setNumber(name, value); return this; } @Override public SJsonObject addObject(String name, SJsonObject value) { if (value instanceof SJsonObjectWeb) { SJsonObjectWeb jow = (SJsonObjectWeb) value; jso.setJso(name, jow.jso); } return this; } @Override public Integer getInt(String name) { if (jso.containsKey(name)) return new Double(jso.getNumber(name)).intValue(); return null; } @Override public Long getLong(String name) { if (jso.containsKey(name)) return new Double(jso.getNumber(name)).longValue(); else return null; } @Override public Double getDouble(String name) { if (jso.containsKey(name)) return new Double(jso.getNumber(name)); else return null; } @Override public boolean getBoolean(String name) { return jso.getBoolean(name); } @Override public String getString(String name) { return jso.getString(name); } @Override public SJsonObject getObject(String name) { return new SJsonObjectWeb(jso.getJsoView(name)); } @Override public boolean has(String name) { return jso.containsKey(name); } protected JsoView getJsoView() { return jso; } @Override public Object getNative() { return jso; } }
true
41d3cfab5b6db3d7ee3e119af1d7b441e66d9cf1
Java
keshavreddy1988/export-the-data-to-csv
/SampleController.java
UTF-8
2,667
2.265625
2
[]
no_license
package com.sample.app.controller; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import java.util.stream.Stream; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.sample.app.model.UserDetail; import com.sample.app.repository.SampleRepository; @RestController @RequestMapping(value = "/sample") public class SampleController { @PersistenceContext EntityManager entityManager; @Autowired private SampleRepository sampleRepository; @RequestMapping(value = "/userdetail/stream/csv", method = RequestMethod.GET) @Transactional(readOnly = true) public void generateCSVUsingStream(HttpServletResponse response) { response.addHeader("Content-Type", "application/csv"); response.addHeader("Content-Disposition", "attachment; filename=user_details.csv"); response.setCharacterEncoding("UTF-8"); try (Stream<UserDetail> userDetailsStream = sampleRepository.getAll();) { PrintWriter out = response.getWriter(); userDetailsStream.forEach(userDetail -> { out.write(userDetail.toString()); out.write("\n"); entityManager.detach(userDetail); }); out.flush(); out.close(); userDetailsStream.close(); } catch (IOException ix) { throw new RuntimeException("There is an error while downloading user_details.csv", ix); } } @RequestMapping(value = "/userdetail/list/csv", method = RequestMethod.GET) public void generateCSVUsingList(HttpServletResponse response) { response.addHeader("Content-Type", "application/csv"); response.addHeader("Content-Disposition", "attachment; filename=user_details.csv"); response.setCharacterEncoding("UTF-8"); try { List<UserDetail> userDetailsStream = sampleRepository.getAllOldWay(); PrintWriter out = response.getWriter(); userDetailsStream.forEach(userDetail -> { out.write(userDetail.toString()); out.write("\n"); entityManager.detach(userDetail); }); out.flush(); out.close(); } catch (IOException ix) { throw new RuntimeException("There is an error while downloading user_details.csv", ix); } } @RequestMapping(value = "/userdetail/rx/csv", method = RequestMethod.GET) public void generateCSVUsingRx() { return; } }
true
47ff8eb9c8ddfc2d49b17dd8ca7d2387212c78fd
Java
brunoalbrito/javacodedemo
/springFrameworkDebug/demoSrc/cn/java/demo/txtag/Test.java
UTF-8
1,125
2.296875
2
[]
no_license
package cn.java.demo.txtag; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import cn.java.demo.txtag.bean.byannotation.service.FooOneByAnnotaionService; import cn.java.demo.txtag.bean.byxml.service.FooOneByXmlService; public class Test { public static void main(String[] args) throws Exception { ApplicationContext context = new ClassPathXmlApplicationContext( "classpath:cn/java/demo/txtag/applicationContext.xml"); System.out.println("\n----------使用XML配置--------------"); { FooOneByXmlService fooOneByXmlService = (FooOneByXmlService) context.getBean("fooOneByXmlService"); System.out.println("fooOneByXmlService.insertFooInfo() = " + fooOneByXmlService.insertFooInfo()); } System.out.println("\n----------使用注解配置--------------"); { FooOneByAnnotaionService fooOneByAnnotaionService = (FooOneByAnnotaionService) context.getBean("fooOneByAnnotaionService"); System.out.println("fooOneByAnnotaionService.insertFooInfo() = " + fooOneByAnnotaionService.insertFooInfo()); } } }
true
cc249a6fab2db34ca8e727fdf91f2b2a7514b588
Java
wgslr/agh-distributed
/02_jgroups/src/pl/geisler/jgroups/MergeHandler.java
UTF-8
1,308
2.609375
3
[ "MIT" ]
permissive
package pl.geisler.jgroups; import org.jgroups.Address; import org.jgroups.JChannel; import org.jgroups.MergeView; import org.jgroups.View; import java.util.LinkedList; import java.util.List; public class MergeHandler implements Runnable { private final MergeView mergeView; private final JChannel channel; public MergeHandler(MergeView view, JChannel channel) { mergeView = view; this.channel = channel; } @Override public void run() { System.err.println("MergeHandler run"); List<View> subgroups = new LinkedList<>(mergeView.getSubgroups()); subgroups.sort((gr1, gr2) -> { if (gr1.size() == gr2.size()) { return gr1.compareTo(gr2); } else { return gr1.size() - gr2.size(); } }); View main = subgroups.get(0); Address localAddr = channel.getAddress(); try { if (!main.getMembers().contains(localAddr)) { System.err.println("Resetting node after partitions merge"); channel.getState(null, 0); } else { System.err.println("Node is in the main partition after merge"); } } catch (Exception e) { e.printStackTrace(); } } }
true
11248dbfb80b242248a7c1e2c3e490758abe76f4
Java
LiMingHuaGit/api
/src/main/java/com/liminghua/api/sysb/service/UserService.java
UTF-8
289
1.609375
2
[]
no_license
package com.liminghua.api.sysb.service; /** * @author LiMinghua */ public interface UserService { /** * getAllUser * @Description UserService * @param: * @return: String * @auther: LiMinghua * @date: 2020/6/1 11:10 */ String getAllUser(); }
true
1c160d588b9ad7add998c5dfdd6c01edd519a1bf
Java
rahulkpa/conference-demo-rahul
/src/main/java/com/wellsfargo/conferencedemo/controllers/HomeController.java
UTF-8
601
2.09375
2
[]
no_license
package com.wellsfargo.conferencedemo.controllers; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.Map; @RestController public class HomeController { @Value("${environment.value}") private String envType; @GetMapping("/") public Map getStatus(){ Map<String,String> mapResult = new HashMap<>(); mapResult.put("environment",envType); return mapResult; } }
true
800cda39be3d26db25db924a31be095a2baf1a79
Java
klyall/slinky-framework
/slinky-common-logging/src/main/java/org/slinkyframework/common/logging/extracters/name/FieldNameExtractor.java
UTF-8
933
2.234375
2
[]
no_license
package org.slinkyframework.common.logging.extracters.name; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slinkyframework.common.aop.domain.AnnotatedObject; import org.slinkyframework.common.logging.Loggable; import java.lang.reflect.Field; import java.util.Optional; final class FieldNameExtractor implements NameExtractor { private static final Logger LOGGER = LoggerFactory.getLogger(FieldNameExtractor.class); @Override public Optional<String> extractName(AnnotatedObject<?, Loggable> annotatedObject, Field field) { Optional<String> name = extractName(annotatedObject); if (name.isPresent()) { return name; } else { return Optional.of(field.getName()); } } private Optional<String> extractName(AnnotatedObject<?, Loggable> annotatedObject) { return NameExtractorFactory.extractName(annotatedObject, null); } }
true
464141f208960ca0c0ee04aa6fc757d184d4ae06
Java
ChinmayVijay/Collections-Overview
/collections-example/src/linkedlist/CreateLinkedList.java
UTF-8
765
3.21875
3
[]
no_license
package linkedlist; import java.util.LinkedList; public class CreateLinkedList { public static void main(String... args) { LinkedList<String> batsmanList = new LinkedList<String>(); batsmanList.add("Steve"); batsmanList.add("Mark"); batsmanList.add("Ricky"); batsmanList.add("Damien"); batsmanList.add("Bevan"); batsmanList.add("Adam"); batsmanList.add(2,"Darren"); batsmanList.addFirst("Hayden"); batsmanList.addLast("Mcgrath"); LinkedList<String> playersList = new LinkedList<String>(batsmanList); playersList.addLast("Gillespie"); playersList.addLast("Bracken"); playersList.addLast("Kasprowicz"); playersList.addLast("Warne"); System.out.println(playersList); } }
true
926e0437db50cd32618cd23bf2fb988c26a24faa
Java
quangtd95/xoso
/app/src/main/java/vn/asiantech/pah/model/Buy.java
UTF-8
264
1.9375
2
[]
no_license
package vn.asiantech.pah.model; import lombok.AllArgsConstructor; import lombok.Data; /** * Buy. * * @author BiNC */ @Data @AllArgsConstructor(suppressConstructorProperties = true) public class Buy { private String number; private boolean isCheck; }
true
339171d50e512b192f2235a264723343d5a33e98
Java
cdiglesias/SICC
/Construccion/PROYECTO.SICC/INC/ENTIDADES/src/es/indra/sicc/entidades/inc/SolicitudConcursoRecomendadasLocal.java
UTF-8
4,104
1.78125
2
[]
no_license
package es.indra.sicc.entidades.inc; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Column; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import java.io.Serializable; @Entity @Table(name="INC_SOLIC_CONCU_RECOM") @NamedQueries({ @NamedQuery(name="SolicitudConcursoRecomendadasLocal.FindAll",query="select object(o) from SolicitudConcursoRecomendadasLocal o"), @NamedQuery(name="SolicitudConcursoRecomendadasLocal.FindByUKConGerente",query="SELECT OBJECT(a) " + " FROM SolicitudConcursoRecomendadasLocal AS a " + " WHERE a.concurso = ?1 " + " AND a.solicitud = ?2 " + " AND a.gerente = ?3"), @NamedQuery(name="SolicitudConcursoRecomendadasLocal.FindByUKSinGerente",query="SELECT OBJECT(a) " + " FROM SolicitudConcursoRecomendadasLocal AS a " + " WHERE a.concurso = ?1 " + " AND a.solicitud = ?2 " + " AND a.gerente IS NULL"), @NamedQuery(name="SolicitudConcursoRecomendadasLocal.FindByConcurso",query="SELECT OBJECT(a) " + " FROM SolicitudConcursoRecomendadasLocal AS a " + " WHERE a.concurso = ?1") }) public class SolicitudConcursoRecomendadasLocal implements Serializable { public SolicitudConcursoRecomendadasLocal() {} public SolicitudConcursoRecomendadasLocal(Long oid, Long copaOidParaGral, Long socaOidSoliCabe, Long clieOidClie, Long perdOidPeri, Long gerente) { this.oid=oid; this.setConcurso(copaOidParaGral); this.setSolicitud(socaOidSoliCabe); this.setRecomendante(clieOidClie); this.setPeriodo(perdOidPeri); this.setGerente(gerente); } @Id @Column(name="OID_SOLI_CONC_RECO") private Long oid; @Column(name="FEC_DOCU") private java.sql.Date fechaDocumento; @Column(name="IND_SOLI_VALI") private Boolean solicitudValida; @Column(name="IMP_MONT_SOLI") private java.math.BigDecimal montoSolicitud; @Column(name="NUM_UNID_SOLI") private Integer unidadesSolicitud; @Column(name="IND_ANUL") private Boolean anulada; @Column(name="COPA_OID_PARA_GRAL") private Long concurso; @Column(name="SOCA_OID_SOLI_CABE") private Long solicitud; @Column(name="CLIE_OID_CLIE") private Long recomendante; @Column(name="PERD_OID_PERI") private Long periodo; @Column(name="CLIE_OID_RECO_DADO") private Long recomendado; @Column(name="CLIE_OID_CLIE_GERE") private Long gerente; public Long getOid() {return oid;} //public void setOid(Long oid){this.oid=oid;} public Long getPrimaryKey() {return oid;} public java.sql.Date getFechaDocumento() {return fechaDocumento;} public void setFechaDocumento(java.sql.Date fechaDocumento){this.fechaDocumento=fechaDocumento;} public Boolean getSolicitudValida() {return solicitudValida;} public void setSolicitudValida(Boolean solicitudValida){this.solicitudValida=solicitudValida;} public java.math.BigDecimal getMontoSolicitud() {return montoSolicitud;} public void setMontoSolicitud(java.math.BigDecimal montoSolicitud){this.montoSolicitud=montoSolicitud;} public Integer getUnidadesSolicitud() {return unidadesSolicitud;} public void setUnidadesSolicitud(Integer unidadesSolicitud){this.unidadesSolicitud=unidadesSolicitud;} public Boolean getAnulada() {return anulada;} public void setAnulada(Boolean anulada){this.anulada=anulada;} public Long getConcurso() {return concurso;} public void setConcurso(Long concurso){this.concurso=concurso;} public Long getSolicitud() {return solicitud;} public void setSolicitud(Long solicitud){this.solicitud=solicitud;} public Long getRecomendante() {return recomendante;} public void setRecomendante(Long recomendante){this.recomendante=recomendante;} public Long getPeriodo() {return periodo;} public void setPeriodo(Long periodo){this.periodo=periodo;} public Long getRecomendado() {return recomendado;} public void setRecomendado(Long recomendado){this.recomendado=recomendado;} public Long getGerente() {return gerente;} public void setGerente(Long gerente){this.gerente=gerente;} }
true
ec9094eb82aeccef3f19530d43b367e89a22574e
Java
sunnymaurya0123/Swabhav
/OOAD/employee-data-analyzer-revision2/src/com/techlabs/employee/test/TestEmployee.java
UTF-8
1,223
2.765625
3
[]
no_license
package com.techlabs.employee.test; import java.io.*; import java.util.*; import com.techlabs.analyzer.Analyzer; import com.techlabs.employee.Employee; import com.techlabs.loader.FileLoader; import com.techlabs.loader.UrlLoader; import com.techlabs.parser.Parser; public class TestEmployee { public static void main(String[] args) throws NumberFormatException, FileNotFoundException, IOException { Analyzer analyzer =new Analyzer(new Parser(new UrlLoader("https://swabhav-tech.firebaseapp.com/emp.txt"))); Analyzer analyzer1 =new Analyzer(new Parser(new FileLoader("Resources/dataFile.txt"))); Employee employee=analyzer.getMaxSalariedEmployee(); System.out.println(employee.getSalary()); Map<Integer,Integer> emp=analyzer.getDepartmentWiseEmployeeCount(); System.out.println(emp); Map<String,Integer> empl=analyzer.getDesignationWiseEmployeeCount(); System.out.println(empl); Employee employee1=analyzer1.getMaxSalariedEmployee(); System.out.println(employee1.getSalary()); Map<Integer,Integer> emp1=analyzer1.getDepartmentWiseEmployeeCount(); System.out.println(emp1); Map<String,Integer> empl1=analyzer1.getDesignationWiseEmployeeCount(); System.out.println(empl1); } }
true
d1ca6e501ac50e44fe825221fea14d138ff7e24d
Java
mobreza/brapi-client
/src/main/java/org/brapi/client/model/Phenotype.java
UTF-8
14,104
1.820313
2
[ "Apache-2.0" ]
permissive
/* * BrAPI implementation for PIPPA * A first draft implementation of the breeding API * * OpenAPI spec version: 1.0.0 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package org.brapi.client.model; import java.util.Objects; import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** * Phenotype */ @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-05-31T12:16:05.949+02:00") public class Phenotype { @SerializedName("observationDbId") private String observationDbId = null; @SerializedName("observationUnitDbId") private String observationUnitDbId = null; @SerializedName("observationUnitName") private String observationUnitName = null; @SerializedName("studyDbId") private String studyDbId = null; @SerializedName("studyName") private String studyName = null; @SerializedName("studyLocationDbId") private String studyLocationDbId = null; @SerializedName("studyLocation") private String studyLocation = null; @SerializedName("programName") private String programName = null; @SerializedName("observationLevel") private String observationLevel = null; @SerializedName("germplasmDbId") private String germplasmDbId = null; @SerializedName("germplasmName") private String germplasmName = null; @SerializedName("observationVariableId") private String observationVariableId = null; @SerializedName("observationVariableDbId") private String observationVariableDbId = null; @SerializedName("season") private String season = null; @SerializedName("value") private String value = null; @SerializedName("observationTimeStamp") private String observationTimeStamp = null; @SerializedName("collector") private String collector = null; @SerializedName("uploadedBy") private String uploadedBy = null; @SerializedName("additionalInfo") private Object additionalInfo = null; public Phenotype observationDbId(String observationDbId) { this.observationDbId = observationDbId; return this; } /** * Get observationDbId * @return observationDbId **/ @ApiModelProperty(example = "null", value = "") public String getObservationDbId() { return observationDbId; } public void setObservationDbId(String observationDbId) { this.observationDbId = observationDbId; } public Phenotype observationUnitDbId(String observationUnitDbId) { this.observationUnitDbId = observationUnitDbId; return this; } /** * Get observationUnitDbId * @return observationUnitDbId **/ @ApiModelProperty(example = "null", value = "") public String getObservationUnitDbId() { return observationUnitDbId; } public void setObservationUnitDbId(String observationUnitDbId) { this.observationUnitDbId = observationUnitDbId; } public Phenotype observationUnitName(String observationUnitName) { this.observationUnitName = observationUnitName; return this; } /** * Get observationUnitName * @return observationUnitName **/ @ApiModelProperty(example = "null", value = "") public String getObservationUnitName() { return observationUnitName; } public void setObservationUnitName(String observationUnitName) { this.observationUnitName = observationUnitName; } public Phenotype studyDbId(String studyDbId) { this.studyDbId = studyDbId; return this; } /** * Get studyDbId * @return studyDbId **/ @ApiModelProperty(example = "null", value = "") public String getStudyDbId() { return studyDbId; } public void setStudyDbId(String studyDbId) { this.studyDbId = studyDbId; } public Phenotype studyName(String studyName) { this.studyName = studyName; return this; } /** * Get studyName * @return studyName **/ @ApiModelProperty(example = "null", value = "") public String getStudyName() { return studyName; } public void setStudyName(String studyName) { this.studyName = studyName; } public Phenotype studyLocationDbId(String studyLocationDbId) { this.studyLocationDbId = studyLocationDbId; return this; } /** * Get studyLocationDbId * @return studyLocationDbId **/ @ApiModelProperty(example = "null", value = "") public String getStudyLocationDbId() { return studyLocationDbId; } public void setStudyLocationDbId(String studyLocationDbId) { this.studyLocationDbId = studyLocationDbId; } public Phenotype studyLocation(String studyLocation) { this.studyLocation = studyLocation; return this; } /** * Get studyLocation * @return studyLocation **/ @ApiModelProperty(example = "null", value = "") public String getStudyLocation() { return studyLocation; } public void setStudyLocation(String studyLocation) { this.studyLocation = studyLocation; } public Phenotype programName(String programName) { this.programName = programName; return this; } /** * Get programName * @return programName **/ @ApiModelProperty(example = "null", value = "") public String getProgramName() { return programName; } public void setProgramName(String programName) { this.programName = programName; } public Phenotype observationLevel(String observationLevel) { this.observationLevel = observationLevel; return this; } /** * Get observationLevel * @return observationLevel **/ @ApiModelProperty(example = "null", value = "") public String getObservationLevel() { return observationLevel; } public void setObservationLevel(String observationLevel) { this.observationLevel = observationLevel; } public Phenotype germplasmDbId(String germplasmDbId) { this.germplasmDbId = germplasmDbId; return this; } /** * Get germplasmDbId * @return germplasmDbId **/ @ApiModelProperty(example = "null", value = "") public String getGermplasmDbId() { return germplasmDbId; } public void setGermplasmDbId(String germplasmDbId) { this.germplasmDbId = germplasmDbId; } public Phenotype germplasmName(String germplasmName) { this.germplasmName = germplasmName; return this; } /** * Get germplasmName * @return germplasmName **/ @ApiModelProperty(example = "null", value = "") public String getGermplasmName() { return germplasmName; } public void setGermplasmName(String germplasmName) { this.germplasmName = germplasmName; } public Phenotype observationVariableId(String observationVariableId) { this.observationVariableId = observationVariableId; return this; } /** * Get observationVariableId * @return observationVariableId **/ @ApiModelProperty(example = "null", value = "") public String getObservationVariableId() { return observationVariableId; } public void setObservationVariableId(String observationVariableId) { this.observationVariableId = observationVariableId; } public Phenotype observationVariableDbId(String observationVariableDbId) { this.observationVariableDbId = observationVariableDbId; return this; } /** * Get observationVariableDbId * @return observationVariableDbId **/ @ApiModelProperty(example = "null", value = "") public String getObservationVariableDbId() { return observationVariableDbId; } public void setObservationVariableDbId(String observationVariableDbId) { this.observationVariableDbId = observationVariableDbId; } public Phenotype season(String season) { this.season = season; return this; } /** * Get season * @return season **/ @ApiModelProperty(example = "null", value = "") public String getSeason() { return season; } public void setSeason(String season) { this.season = season; } public Phenotype value(String value) { this.value = value; return this; } /** * Get value * @return value **/ @ApiModelProperty(example = "null", value = "") public String getValue() { return value; } public void setValue(String value) { this.value = value; } public Phenotype observationTimeStamp(String observationTimeStamp) { this.observationTimeStamp = observationTimeStamp; return this; } /** * Get observationTimeStamp * @return observationTimeStamp **/ @ApiModelProperty(example = "null", value = "") public String getObservationTimeStamp() { return observationTimeStamp; } public void setObservationTimeStamp(String observationTimeStamp) { this.observationTimeStamp = observationTimeStamp; } public Phenotype collector(String collector) { this.collector = collector; return this; } /** * Get collector * @return collector **/ @ApiModelProperty(example = "null", value = "") public String getCollector() { return collector; } public void setCollector(String collector) { this.collector = collector; } public Phenotype uploadedBy(String uploadedBy) { this.uploadedBy = uploadedBy; return this; } /** * Get uploadedBy * @return uploadedBy **/ @ApiModelProperty(example = "null", value = "") public String getUploadedBy() { return uploadedBy; } public void setUploadedBy(String uploadedBy) { this.uploadedBy = uploadedBy; } public Phenotype additionalInfo(Object additionalInfo) { this.additionalInfo = additionalInfo; return this; } /** * Get additionalInfo * @return additionalInfo **/ @ApiModelProperty(example = "null", value = "") public Object getAdditionalInfo() { return additionalInfo; } public void setAdditionalInfo(Object additionalInfo) { this.additionalInfo = additionalInfo; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Phenotype phenotype = (Phenotype) o; return Objects.equals(this.observationDbId, phenotype.observationDbId) && Objects.equals(this.observationUnitDbId, phenotype.observationUnitDbId) && Objects.equals(this.observationUnitName, phenotype.observationUnitName) && Objects.equals(this.studyDbId, phenotype.studyDbId) && Objects.equals(this.studyName, phenotype.studyName) && Objects.equals(this.studyLocationDbId, phenotype.studyLocationDbId) && Objects.equals(this.studyLocation, phenotype.studyLocation) && Objects.equals(this.programName, phenotype.programName) && Objects.equals(this.observationLevel, phenotype.observationLevel) && Objects.equals(this.germplasmDbId, phenotype.germplasmDbId) && Objects.equals(this.germplasmName, phenotype.germplasmName) && Objects.equals(this.observationVariableId, phenotype.observationVariableId) && Objects.equals(this.observationVariableDbId, phenotype.observationVariableDbId) && Objects.equals(this.season, phenotype.season) && Objects.equals(this.value, phenotype.value) && Objects.equals(this.observationTimeStamp, phenotype.observationTimeStamp) && Objects.equals(this.collector, phenotype.collector) && Objects.equals(this.uploadedBy, phenotype.uploadedBy) && Objects.equals(this.additionalInfo, phenotype.additionalInfo); } @Override public int hashCode() { return Objects.hash(observationDbId, observationUnitDbId, observationUnitName, studyDbId, studyName, studyLocationDbId, studyLocation, programName, observationLevel, germplasmDbId, germplasmName, observationVariableId, observationVariableDbId, season, value, observationTimeStamp, collector, uploadedBy, additionalInfo); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Phenotype {\n"); sb.append(" observationDbId: ").append(toIndentedString(observationDbId)).append("\n"); sb.append(" observationUnitDbId: ").append(toIndentedString(observationUnitDbId)).append("\n"); sb.append(" observationUnitName: ").append(toIndentedString(observationUnitName)).append("\n"); sb.append(" studyDbId: ").append(toIndentedString(studyDbId)).append("\n"); sb.append(" studyName: ").append(toIndentedString(studyName)).append("\n"); sb.append(" studyLocationDbId: ").append(toIndentedString(studyLocationDbId)).append("\n"); sb.append(" studyLocation: ").append(toIndentedString(studyLocation)).append("\n"); sb.append(" programName: ").append(toIndentedString(programName)).append("\n"); sb.append(" observationLevel: ").append(toIndentedString(observationLevel)).append("\n"); sb.append(" germplasmDbId: ").append(toIndentedString(germplasmDbId)).append("\n"); sb.append(" germplasmName: ").append(toIndentedString(germplasmName)).append("\n"); sb.append(" observationVariableId: ").append(toIndentedString(observationVariableId)).append("\n"); sb.append(" observationVariableDbId: ").append(toIndentedString(observationVariableDbId)).append("\n"); sb.append(" season: ").append(toIndentedString(season)).append("\n"); sb.append(" value: ").append(toIndentedString(value)).append("\n"); sb.append(" observationTimeStamp: ").append(toIndentedString(observationTimeStamp)).append("\n"); sb.append(" collector: ").append(toIndentedString(collector)).append("\n"); sb.append(" uploadedBy: ").append(toIndentedString(uploadedBy)).append("\n"); sb.append(" additionalInfo: ").append(toIndentedString(additionalInfo)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
true
ac6378dcd193ca782ab531c2b3a11c4e16f107bd
Java
WakkaFlocka239/Commands
/src/main/java/com/spleefleague/commands/commands/globalschematic.java
UTF-8
6,669
1.960938
2
[]
no_license
package com.spleefleague.commands.commands; import com.sk89q.worldedit.EmptyClipboardException; import com.sk89q.worldedit.MaxChangedBlocksException; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.bukkit.BukkitUtil; import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard; import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormat; import com.sk89q.worldedit.extent.clipboard.io.ClipboardReader; import com.sk89q.worldedit.extent.clipboard.io.ClipboardWriter; import com.sk89q.worldedit.function.operation.Operations; import com.sk89q.worldedit.math.transform.Transform; import com.sk89q.worldedit.session.ClipboardHolder; import com.sk89q.worldedit.util.io.Closer; import com.sk89q.worldedit.world.registry.WorldData; import static com.spleefleague.annotations.CommandSource.PLAYER; import com.spleefleague.annotations.Endpoint; import com.spleefleague.annotations.LiteralArg; import com.spleefleague.annotations.StringArg; import com.spleefleague.core.chat.Theme; import com.spleefleague.commands.command.BasicCommand; import com.spleefleague.core.io.Settings; import com.spleefleague.core.player.Rank; import com.spleefleague.core.plugin.CorePlugin; import com.spleefleague.core.utils.FlattenedClipboardTransform; import org.apache.commons.lang3.StringUtils; import org.bukkit.entity.Player; import java.io.*; /** * Created by Josh on 10/08/2016. */ public class globalschematic extends BasicCommand { public globalschematic(CorePlugin plugin, String name, String usage) { super(plugin, new globalschematicDispatcher(), name, usage, Rank.SENIOR_MODERATOR, Rank.BUILDER); } private boolean checkEnabled(Player p) { if (!Settings.getBoolean("global_schematics_enabled").orElse(false) || !Settings.hasKey("global_schematics_save_location")) { error(p, "This command is currently disabled!"); return false; } return true; } @Endpoint(target = {PLAYER}) public void save(Player p, @LiteralArg(value = "save") String l, @StringArg String name) { if (!checkEnabled(p)) { return; } if (name.contains(".")) { error(p, "Invalid schematic name!"); return; } File saveLocation = new File(Settings.getString("global_schematics_save_location").get()); File saveFile = new File(saveLocation, name + ".schematic"); ClipboardFormat format = ClipboardFormat.findByAlias("schematic"); ClipboardHolder holder; try { holder = WorldEdit.getInstance().getSession(p.getName()).getClipboard(); } catch (EmptyClipboardException e) { error(p, "You need to copy an area first!"); return; } Clipboard clipboard = holder.getClipboard(); Transform transform = holder.getTransform(); Clipboard target; // If we have a transform, bake it into the copy if (!transform.isIdentity()) { FlattenedClipboardTransform result = FlattenedClipboardTransform.transform(clipboard, transform, holder.getWorldData()); target = new BlockArrayClipboard(result.getTransformedRegion()); target.setOrigin(clipboard.getOrigin()); try { Operations.completeLegacy(result.copyTo(target)); } catch (MaxChangedBlocksException e) { error(p, "Too many blocks changed in one session! Please contact a developer."); return; } } else { target = clipboard; } Closer closer = Closer.create(); try { FileOutputStream fos = closer.register(new FileOutputStream(saveFile)); BufferedOutputStream bos = closer.register(new BufferedOutputStream(fos)); ClipboardWriter writer = closer.register(format.getWriter(bos)); writer.write(target, holder.getWorldData()); success(p, "Schematic saved! You can now load it on any server using /globalschematic load " + name + "!"); } catch (IOException e) { error(p, "Unable to write to schematic file - please contact a developer!"); } finally { try { closer.close(); } catch (IOException ignored) { } } } @Endpoint(target = {PLAYER}) public void load(Player p, @LiteralArg(value = "load") String l, @StringArg String name) { if (!checkEnabled(p)) { return; } if (name.contains(".")) { error(p, "Invalid schematic name!"); return; } File loadLocation = new File(Settings.getString("global_schematics_save_location").get()); File loadFile = new File(loadLocation, name + ".schematic"); if (!loadFile.exists()) { error(p, "That schematic doesn't seem to exist!"); return; } ClipboardFormat format = ClipboardFormat.findByAlias("schematic"); Closer closer = Closer.create(); try { FileInputStream fis = closer.register(new FileInputStream(loadFile)); BufferedInputStream bis = closer.register(new BufferedInputStream(fis)); ClipboardReader reader = format.getReader(bis); WorldData worldData = BukkitUtil.getLocalWorld(p.getWorld()).getWorldData(); Clipboard clipboard = reader.read(worldData); WorldEdit.getInstance().getSession(p.getName()).setClipboard(new ClipboardHolder(clipboard, worldData)); success(p, "Schematic loaded - you can now paste it using //paste."); } catch (IOException | NullPointerException e) { error(p, "The schematic could not be read - please contact a developer!"); } finally { try { closer.close(); } catch (IOException ignored) { } } } @Endpoint(target = {PLAYER}) public void list(Player p, @LiteralArg(value = "list") String l) { if (!checkEnabled(p)) { return; } File schematicLocation = new File(File.separator + "home" + File.separator + "schematics" + File.separator); if (!schematicLocation.exists() || !schematicLocation.isDirectory() || schematicLocation.listFiles().length == 0) { error(p, "No schematics found!"); return; } p.sendMessage(Theme.INFO.buildTheme(true) + "Global schematics:"); p.sendMessage(Theme.INFO.buildTheme(true) + StringUtils.join(schematicLocation.list(), ", ").replace(".schematic", "") + "."); } }
true
f99ecd31c6240c7fae0b016a7a62b49e3e6f13df
Java
abhiy77/LeetCode
/LeetCode 601-700/665.NonDecreasingArray.java
UTF-8
570
2.703125
3
[]
no_license
class Solution { public boolean checkPossibility(int[] nums) { int change = 1; int idx = 0; if(nums.length <= 2)return true; for(int i=0;i<nums.length-1;i++){ if(nums[i] > nums[i+1]){ if(change == 1){ change--; idx = i; } else return false; } } return (idx == 0 || change == 1 || idx == nums.length - 2 || nums[idx-1] <= nums[idx+1] || nums[idx] <= nums[idx+2]); } }
true
99aea3f273aa7bf19cd9eb9bc7ab2c1d863c597d
Java
ForLovelj/v9porn
/app/src/main/java/com/u9porn/ui/splash/SplashPresenter.java
UTF-8
2,584
1.875
2
[ "MIT" ]
permissive
package com.u9porn.ui.splash; import com.hannesdorfmann.mosby3.mvp.MvpBasePresenter; import com.u9porn.data.DataManager; import com.u9porn.data.model.Notice; import com.u9porn.data.model.UpdateVersion; import com.u9porn.ui.notice.NoticePresenter; import com.u9porn.ui.notice.NoticeView; import com.u9porn.ui.update.UpdatePresenter; import com.u9porn.ui.update.UpdateView; import javax.inject.Inject; /** * @author flymegoc * @date 2017/12/21 */ public class SplashPresenter extends MvpBasePresenter<SplashView> implements ISplash { private DataManager dataManager; private final UpdatePresenter updatePresenter; private final NoticePresenter noticePresenter; @Inject public SplashPresenter(DataManager dataManager, UpdatePresenter updatePresenter, NoticePresenter noticePresenter) { this.dataManager = dataManager; this.updatePresenter = updatePresenter; this.noticePresenter = noticePresenter; } @Override public boolean isUserLogin() { return dataManager.isUserLogin(); } @Override public String getVideo9PornAddress() { return dataManager.getPorn9VideoAddress(); } @Override public void checkUpdate(int versionCode) { updatePresenter.checkUpdate(versionCode, new UpdatePresenter.UpdateListener() { @Override public void needUpdate(final UpdateVersion updateVersion) { ifViewAttached(view -> view.needUpdate(updateVersion)); } @Override public void noNeedUpdate() { ifViewAttached(UpdateView::noNeedUpdate); } @Override public void checkUpdateError(final String message) { ifViewAttached(view -> view.checkUpdateError(message)); } }); } @Override public void checkNewNotice() { noticePresenter.checkNewNotice(new NoticePresenter.CheckNewNoticeListener() { @Override public void haveNewNotice(final Notice notice) { ifViewAttached(view -> view.haveNewNotice(notice)); } @Override public void noNewNotice() { ifViewAttached(NoticeView::noNewNotice); } @Override public void checkNewNoticeError(final String message) { ifViewAttached(view -> view.checkNewNoticeError(message)); } }); } @Override public int getIgnoreUpdateVersionCode() { return dataManager.getIgnoreUpdateVersionCode(); } }
true
b0deed3aaa26c93f4d233fe315b08bb6484372a3
Java
zhiyanglu/LeetCode-Java
/SummaryRange.java
UTF-8
925
3.6875
4
[]
no_license
import java.util.ArrayList; import java.util.List; /** * Given a sorted integer array without duplicates, return the summary of its ranges. * For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"]. * @author Lu * */ public class SummaryRange { public static void main(String[] args) { // TODO Auto-generated method stub int[] nums = {0,1,2,4,5,7}; System.out.println(new SummaryRange().summaryRanges(nums)); } public List<String> summaryRanges(int[] nums) { List<String> result = new ArrayList<String>(); for(int i = 0; i < nums.length; i++){ StringBuilder sb = new StringBuilder(); int start = nums[i]; sb.append(start); while(i + 1 < nums.length && nums[i + 1] == nums[i] + 1){ i++; } if(start != nums[i]){ sb.append("->"); sb.append(nums[i]); } result.add(sb.toString()); } return result; } }
true
0843bc3e0b26789ad76aba8de82b08c807636d0b
Java
bussayakaew/ChatSaa
/app/src/main/java/bussaya/chatsaa/chat/viewholder/MessageViewHolder.java
UTF-8
860
2.09375
2
[]
no_license
package bussaya.chatsaa.chat.viewholder; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import bussaya.chatsaa.R; import de.hdodenhof.circleimageview.CircleImageView; /** * Created by admin on 10/3/2560. */ public class MessageViewHolder extends RecyclerView.ViewHolder { public TextView tvMessage; public TextView tvName; public CircleImageView ivProfile; public ImageView ivMessage; public MessageViewHolder(View itemView) { super(itemView); tvMessage = (TextView) itemView.findViewById(R.id.tv_message); tvName = (TextView) itemView.findViewById(R.id.tv_name); ivProfile = (CircleImageView) itemView.findViewById(R.id.iv_profile); ivMessage = (ImageView) itemView.findViewById(R.id.iv_message); } }
true
3243dd0d881c6d1bca491e829749be081e59a12a
Java
Vughalla/ORT-TPI
/src/socio/Club.java
WINDOWS-1250
1,432
3.203125
3
[]
no_license
package socio; import java.util.ArrayList; public class Club { private String nombre; private ArrayList<Socio> socios; private int INSCRIPCION_ANUAL = 12; Club(String nombre) { setNombre(nombre); socios = new ArrayList<Socio>(); } private void setNombre(String nombre) { this.nombre = nombre; System.out.println("Bienvenido al club "+this.nombre); } public void agregarSocio(String nombreSocio, double valorCuota) { if (buscarSocio(nombreSocio) == null) { socios.add(new Socio(nombreSocio, valorCuota, INSCRIPCION_ANUAL)); } else { System.out.println("Ya existe el socio " +nombreSocio+"."); } } private Socio buscarSocio(String nombreSocio) { Socio socio = null; int i = 0; while(socio == null && i<socios.size()) { if(socios.get(i).getNombre().matches(nombreSocio)) { socio = socios.get(i); } else { i++; } } return socio; } public void verDetalleDeuda(String nombreSocio) { Socio socio = buscarSocio(nombreSocio); if(socio != null) { socio.mostrarDeuda(); } else { System.out.println("No se encontr el socio."); } } public void cargarPago(String nombreSocio, double importe) { Socio socio = buscarSocio(nombreSocio); if(socio != null) { System.out.println("Ingresando pago del socio "+nombreSocio+ " por un monto de $"+importe); socio.pagarCuotas(importe); } else { System.out.println("No se encontr el socio."); } } }
true
22a95ff92128c55a6070491d6b16a634d3df9d8c
Java
TalTech-Testing/java-tester
/src/test/resources/tests/jar/JarHelloInvoker.java
UTF-8
122
1.890625
2
[]
no_license
import jarhello.JarHello; public class JarHelloInvoker { public String invoke() { return new JarHello().hello(); } }
true
45abc29c7ce9be61f4214ce8a12fdc55db541b8a
Java
CullMay/TipTopBakery
/SandwichFilling.java
UTF-8
815
2.875
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 breadtester; /** * * @author cm0850068 */ public class SandwichFilling { private String fillingType; private double calPerServ; public String getFillingType() { return fillingType; } public double getCalPerServ() { return calPerServ; } public SandwichFilling(String fType, double CaPS){ this.fillingType=fType; this.calPerServ=CaPS; //System.out.printf("Bread filling: %s\n ", fillingType); // System.out.printf("Calories per Serving: %s\n", calPerServ); } }
true
d1920803e350c143d662054e92c6e7da21eccea0
Java
ludoviko/mathLibrary
/src/test/java/com/lam/mathematics/ChampernownesConstantTest.java
UTF-8
990
2.734375
3
[]
no_license
package com.lam.mathematics; import junit.framework.Assert; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.lam.mathematics.ChampernownesConstant; public class ChampernownesConstantTest { ChampernownesConstant champer; int size; @Before public void setUp() throws Exception { champer = new ChampernownesConstant(); } @After public void tearDown() throws Exception { champer = null; size = 0; } @Test public void testGetChampernownes() { int size = 10; champer.setUpToFractionalPosition(10); champer.setChampernownes(); Assert.assertEquals(size + 2, champer.getChampernownes().length()); Assert.assertEquals("0.1234567891", champer.getChampernownes().toString()); size = 25; champer.setUpToFractionalPosition(size); champer.setChampernownes(); Assert.assertEquals(size + 2, champer.getChampernownes().length()); Assert.assertEquals("0.1234567891011121314151617", champer.getChampernownes().toString()); } }
true