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
fbc225d438d409250efcd8cd42e9045e6d590f16
Java
itcolombia/gws-integraciones
/gws-solicitudes-salidas-dto/src/main/java/com/gws/integraciones/solicitudes/salidas/dto/ConfirmacionDespachoMercanciaDto.java
UTF-8
1,091
1.773438
2
[]
no_license
package com.gws.integraciones.solicitudes.salidas.dto; import java.time.LocalDateTime; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; @Getter @Setter @ToString @NoArgsConstructor @AllArgsConstructor public class ConfirmacionDespachoMercanciaDto { private Integer id; @NotNull @Size(max = 50) private Integer idSolicitud; @NotNull private Integer IdOrdenAlistamiento; @NotNull @Size(max = 10) private String placasVehiculo; @NotNull @Size(max = 50) private String remesa; @NotNull @Size(max = 50) private String transportadora; @Size(max = 50) private String novedades; @NotNull @Size(max = 20) private String itemCode; private int lineNum; private int cantidadDespachada; private int cantidadNoDespachada; private int despachado; @NotNull private LocalDateTime fechaDespacho; @NotNull private LocalDateTime fechaRecibida; @NotNull @Size(max = 20) private String estadoDespacho; }
true
fb5c4df786abcc2b2a7a8b247def676b10eebbeb
Java
KStringer86/BFG
/app/src/main/java/com/example/kentstringer/bfg/FragmentProfile.java
UTF-8
4,064
2.375
2
[]
no_license
package com.example.kentstringer.bfg; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import com.example.kentstringer.bfg.models.User; import java.text.DecimalFormat; public class FragmentProfile extends Fragment { private Button btnNavSecondActivity; private User user; private Handler handler = new Handler(); @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_profile, container, false); user = ((MainActivity)getActivity()).user; btnNavSecondActivity = view.findViewById(R.id.btnNavSecondActivity); btnNavSecondActivity.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view){ Intent intent = new Intent(getActivity(), CharactersActivity.class); Bundle bundle = new Bundle(); //Add your data from getFactualResults method to bundle bundle.putSerializable("user", user); //Add the bundle to the intent intent.putExtras(bundle); startActivity(intent); } }); Button nextButtonActivity = view.findViewById(R.id.nextButton); nextButtonActivity.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view){ Intent intent = new Intent(getActivity(), FutureActivity.class); startActivity(intent); } }); Button moveArenaButton = view.findViewById(R.id.profileMove); moveArenaButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ((MainActivity)getActivity()).changeViewPager(1); } }); Runnable runnable = new Runnable() { @Override public void run() { /* do what you need to do */ updatePage(); /* and here comes the "trick" */ handler.postDelayed(this, 2000); } }; handler.postDelayed(runnable, 500); return view; } public void updatePage() { try { TextView nameInput = getView().findViewById(R.id.nameSelect); nameInput.setText("User profile"); TextView levelInput = getView().findViewById(R.id.levelInput); levelInput.setText("User level: " + user.getLevel() + ""); TextView xpInput = getView().findViewById(R.id.xpInput); xpInput.setText("User XP: " + user.getExperience() + ""); TextView xpNeededInput = getView().findViewById(R.id.xpNeededInput); xpNeededInput.setText("XP to next level: " + (user.getLevel() * 2500) + ""); TextView runInput = getView().findViewById(R.id.runInput); int miles = (int)+user.getTotalDistanceRun()/5280; double subMile = (+user.getTotalDistanceRun()%5280)/5280; DecimalFormat df = new DecimalFormat(".##"); String subMileFormatted = df.format(subMile); runInput.setText("Total distance run: " + miles + "" + subMileFormatted + " Miles"); TextView killsInput = getView().findViewById(R.id.killsInput); killsInput.setText("Total monsters killed: " + user.getTotalMonsterKilled() + ""); TextView activeInput = getView().findViewById(R.id.activeInput); activeInput.setText("Active character: " + user.getActivePlayerCharacter().getPcName() + ""); }catch(NullPointerException npe){ } } }
true
ed18b530bd90ff6d75aad982b91a3226073466e0
Java
Mr-Pineapple/Dynasty
/src/main/java/co/uk/mrpineapple/dynasty/client/ClientEvents.java
UTF-8
549
1.820313
2
[]
no_license
package co.uk.mrpineapple.dynasty.client; import co.uk.mrpineapple.dynasty.client.tileentity.renderer.CoinPressTileEntityRenderer; import co.uk.mrpineapple.dynasty.core.registry.TileEntityRegistry; import net.minecraftforge.fml.client.registry.ClientRegistry; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; public class ClientEvents { public static void onClientSetup(FMLClientSetupEvent event) { ClientRegistry.bindTileEntityRenderer(TileEntityRegistry.COIN_PRESS.get(), CoinPressTileEntityRenderer::new); } }
true
04ce06cd861995281b55f9c76e5135a0e36d8c57
Java
dhjacobson/davidj-stuff
/src/main/java/com/hgdata/davidj/models/FatalException.java
UTF-8
828
2.6875
3
[]
no_license
/* * Author: Alex Flury * Date: 10/09/2015 * Copyright HG Data 2015 * www.hgdata.com */ package com.hgdata.davidj.models; /** * An exception for fatal errors that should cause the application to terminate. */ public class FatalException extends Exception { /** * @param cause the cause of the fatal error */ public FatalException(Throwable cause) { super(cause); } /** * @param message a string explaning the cause of the fatal error */ public FatalException(String message) { super(message); } /** * @param message a string explaining the cause of the fatal error * @param cause a {@code Throwable} object that caused the fatal error */ public FatalException(String message, Throwable cause) { super(message, cause); } }
true
3a1c4c83d599ba6851d487de0b67e028cfae27b0
Java
Harshil74/brizingr
/app/src/main/java/com/gec/brizingr2k19/expantable/ExpantableICNon.java
UTF-8
2,426
2.9375
3
[]
no_license
package com.gec.brizingr2k19.expantable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class ExpantableICNon { public static HashMap<String, List<String>> getData() { HashMap<String, List<String>> expandableListDetail = new HashMap<String, List<String>>(); List<String> almidon = new ArrayList<String>(); almidon.add("This event is only related with the fun. In this game this mixture is made up of starch, corn and water. If the participant will Walk smoothly they will get stuck into mixture. If they jump and walk they will not get stuck and can walk on the mixture. This is how they will finish the game."); List<String> roboSoccer = new ArrayList<String>(); roboSoccer.add("1st round there will be 4 robo match winners 2 will be going in the next round.\n" + "2nd round match of the 2 robos winner 1 goes to the last round.\n" + "3rd match between the 2nd round winners and final winner comes from this round.\n" + " \n" + "Robo will be provided by the event coordinator.\n" + "Coordinator have authority to take Final decision \n"); List<String> think = new ArrayList<String>(); think.add("1)Group discussion:- All the participants will be divided into groups. Each group contain 8-10 members. On the spot topic will be given to each group. Individual selection will be done.\n" + "2)Debet:- Selected candidate will move towards the second round. Again topic will be given to each group and participants have to put their points of view in favour or against the topic.\n" + "3)Elocution:- Final round. Each selected candidates have to select the topic from the bowl, 2-3 minutes will be given to recall the point, then they have to speak up for 2 minutes.\n"); List<String> mini = new ArrayList<String>(); mini.add("1st round kotala kud ane picking the blocks.\n" + "2nd round time round in this player have to fail the glasses in minimum time and go ahead eat cucumber by using leg."); expandableListDetail.put("Almidon", almidon); expandableListDetail.put("Robo Soccer", roboSoccer); expandableListDetail.put("Thinking Out Loud", think); expandableListDetail.put("Mini Olympia", mini); return expandableListDetail; } }
true
594ddd6927d1c7b42cb313da829e15ece714cde2
Java
timingsniper/APCS-Elevens-Lab
/DeckTester.java
UTF-8
1,613
3.5625
4
[]
no_license
import java.util.ArrayList; /** * This is a class that tests the Deck class. */ public class DeckTester { /** * The main method in this class checks the Deck operations for consistency. * @param args is not used. */ public static void main(String[] args) { /* *** TO BE IMPLEMENTED IN ACTIVITY 2 *** */ String[]ranks = {"A" , "B" , "C" , "D"}; String[]suits = {"Heart" , "Clover" , "Spade" , "Diamond"}; int[]values = {4 , 6, 7 , 9}; String[]ranks1 = {}; String[]suits1 = {}; int[]values1 = {}; String[]ranks2 = {"J" , "Q" , "K"}; String[]suits2 = {"Diamond"}; int[]values2 = {1, 3, 5}; Deck d1 = new Deck(ranks, suits, values); Deck d2 = new Deck(ranks1, suits1, values1); Deck d3 = new Deck(ranks2, suits2, values2); //d1 test System.out.println("d1: " + d1); d1.deal(); System.out.println("\nAfter dealing d1: " + d1); System.out.println("Is d1 empty?: " + d1.isEmpty()); System.out.println("Current size of d1?: " + d1.size()); //d2 test System.out.println("\nd2: " + d2); d2.deal(); System.out.println("\nAfter dealing d2: " + d2); System.out.println("Is d2 empty?: " + d2.isEmpty()); System.out.println("Current size of d1?: " + d2.size()); //d3 test System.out.println("\nd3: " + d3); d3.deal(); System.out.println("\nAfter dealing d3: " + d3); System.out.println("Is d3 empty?: " + d3.isEmpty()); System.out.println("Current size of d3?: " + d3.size()); int randomnum = (int)(Math.random()*5); System.out.println(randomnum); } }
true
7ebff8094e912bda580b8d8f6d45e79bfac5c0db
Java
slawekpaciorek/UserEngine
/usersengine/src/main/java/com/isa/usersengine/servlets/AddUserServlet.java
UTF-8
2,105
2.4375
2
[]
no_license
package com.isa.usersengine.servlets; import com.isa.usersengine.dao.UserDBDao; import com.isa.usersengine.dao.UsersRepositoryDao; import com.isa.usersengine.domain.User; import javax.inject.Inject; import javax.servlet.RequestDispatcher; 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 java.io.IOException; import java.util.List; import java.util.stream.Collectors; @WebServlet("add-user") public class AddUserServlet extends HttpServlet { @Inject UserDBDao userDBDao; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html;charset=UTF-8"); RequestDispatcher requestDispatcher = req.getRequestDispatcher("add-user.jsp"); requestDispatcher.forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html;charset=UTF-8"); List<String> usersLogins = userDBDao.getUsersFromDataBase().stream().map(x->x.getLogin()).collect(Collectors.toList()); String name = req.getParameter("name"); String surname = req.getParameter("surname"); String login = req.getParameter("login"); String password = req.getParameter("password"); String age = req.getParameter("age"); User user = new User(); user.setAge(Integer.parseInt(age)); user.setLogin(login); user.setName(name); user.setSurname(surname); user.setPassword(password); if(!usersLogins.contains(login)) userDBDao.putUserToDataBase(user); else{ String message = "This login is aleready registered"; req.setAttribute("message", message); } RequestDispatcher rq = req.getRequestDispatcher("add-user.jsp"); rq.forward(req, resp); } }
true
df0c61d70cddad87c3512dea0d75d1e8d5c449d5
Java
typowy1/bootcamp-javastart-cwiczenia
/src/test/java/cwiczenia/lekcja18/cwiczenie4/MealNameProviderRozwiązanieJavaStartTest.java
UTF-8
3,396
2.328125
2
[]
no_license
package cwiczenia.lekcja18.cwiczenie4; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.time.LocalTime; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; class MealNameProviderRozwiązanieJavaStartTest { @Mock private DateTimeProvider dateTimeProvider; private MealNameProvider mealNameProvider; @BeforeEach void init() { MockitoAnnotations.openMocks(this); mealNameProvider = new MealNameProvider(dateTimeProvider); } @Test void shouldReturnBreakfastStart() { // given when(dateTimeProvider.localTimeNow()).thenReturn(LocalTime.of(5, 0)); // when String mealName = mealNameProvider.provideMealName(); // then assertThat(mealName).isEqualToIgnoringCase("śniadanie"); } @Test void shouldReturnBreakfastEnd() { // given when(dateTimeProvider.localTimeNow()).thenReturn(LocalTime.of(8, 59)); // when String mealName = mealNameProvider.provideMealName(); // then assertThat(mealName).isEqualToIgnoringCase("śniadanie"); } @Test void shouldReturn2ndBreakfastStart() { // given when(dateTimeProvider.localTimeNow()).thenReturn(LocalTime.of(9, 0)); // when String mealName = mealNameProvider.provideMealName(); // then assertThat(mealName).isEqualToIgnoringCase("drugie śniadanie"); } @Test void shouldReturn2ndBreakfastEnd() { // given when(dateTimeProvider.localTimeNow()).thenReturn(LocalTime.of(11, 59)); // when String mealName = mealNameProvider.provideMealName(); // then assertThat(mealName).isEqualToIgnoringCase("drugie śniadanie"); } @Test void shouldReturnDinner() { // given when(dateTimeProvider.localTimeNow()).thenReturn(LocalTime.of(13, 5)); // when String mealName = mealNameProvider.provideMealName(); // then assertThat(mealName).isEqualToIgnoringCase("obiad"); } @Test void shouldReturnSupper() { // given when(dateTimeProvider.localTimeNow()).thenReturn(LocalTime.of(19, 59)); MealNameProvider mealNameProvider = new MealNameProvider(dateTimeProvider); // when String mealName = mealNameProvider.provideMealName(); // then assertThat(mealName).isEqualToIgnoringCase("podwieczorek"); } @Test void shouldReturnNightMeal() { // given when(dateTimeProvider.localTimeNow()).thenReturn(LocalTime.of(1, 50)); MealNameProvider mealNameProvider = new MealNameProvider(dateTimeProvider); // when String mealName = mealNameProvider.provideMealName(); // then assertThat(mealName).isEqualToIgnoringCase("przekąska nocna"); } @Test void shouldReturnNightMeal2() { // given when(dateTimeProvider.localTimeNow()).thenReturn(LocalTime.of(23, 55)); MealNameProvider mealNameProvider = new MealNameProvider(dateTimeProvider); // when String mealName = mealNameProvider.provideMealName(); // then assertThat(mealName).isEqualToIgnoringCase("przekąska nocna"); } }
true
81e9cd46ec405eacfc2de8012be440418061b377
Java
lucaovk/oractech
/crudificador/src/main/java/br/com/axxiom/core/web/controller/AbstractCustomSimpleCrudController.java
UTF-8
836
2.09375
2
[]
no_license
package br.com.axxiom.core.web.controller; import java.io.Serializable; import br.com.axxiom.core.db.CustomIdentifiable; public abstract class AbstractCustomSimpleCrudController<T extends CustomIdentifiable<D>, D extends Serializable> extends AbstractCustomCrudController<T, T, D> { protected AbstractCustomSimpleCrudController(String viewPath, String formView, String listView, Class<T> entityClass) { super(viewPath, formView, listView, entityClass, entityClass); } protected AbstractCustomSimpleCrudController(String viewPath, Class<T> entityClass) { this(viewPath, "form", "list", entityClass); } @Override protected void entityPreSaveFillerHook(T entity, T searchEntity) { entityPreSaveFillerHook(entity); } protected void entityPreSaveFillerHook(T entity) { } }
true
02fcff9482c133c0f7d5656c7f9736c7b0be1cc6
Java
matndev/shellx
/src/main/java/app/shellx/security/JwtTokenProvider.java
UTF-8
4,209
2.28125
2
[]
no_license
package app.shellx.security; import java.security.Key; import java.util.Base64; import java.util.Date; import java.util.List; import javax.annotation.PostConstruct; import javax.servlet.ServletRequest; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.stereotype.Component; import app.shellx.model.User; import io.jsonwebtoken.Claims; import io.jsonwebtoken.ExpiredJwtException; import io.jsonwebtoken.Jws; import io.jsonwebtoken.JwtException; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.io.Decoders; import io.jsonwebtoken.security.Keys; @Component public class JwtTokenProvider { @Value("${security.jwt.token.secret.key}") private String secretKey; @Value("${security.jwt.token.expire-length}") // length:300000 private long validityInMilliseconds; // 5min = 300000, 1h = 3600000 @Autowired private UserDetailsService userDetailsService; @PostConstruct protected void init() { secretKey = Base64.getEncoder().encodeToString(secretKey.getBytes()); } private Key getSigningKey() { byte[] keyBytes = Decoders.BASE64.decode(this.secretKey); return Keys.hmacShaKeyFor(keyBytes); // Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256); } public String createToken(String username, List<String> roles) { Claims claims = Jwts.claims().setSubject(username); claims.put("roles", roles); Date now = new Date(); Date validity = new Date(now.getTime() + validityInMilliseconds); return Jwts.builder() .setClaims(claims) .setIssuedAt(now) .setExpiration(validity) .signWith(getSigningKey()) .compact(); } public Authentication getAuthentication(String token) { User userDetails = (User) this.userDetailsService.loadUserByUsername(getUsername(token)); return new UsernamePasswordAuthenticationToken(userDetails, "", userDetails.getAuthorities()); } public String getUsername(String token) { return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody().getSubject(); } public Date getExpirationDate(String token) { return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody().getExpiration(); } public String resolveToken(HttpServletRequest req) { // String accessToken = req.getHeader("Cookie"); // if (accessToken != null && accessToken.startsWith("access_token")) { // return accessToken.substring(13, accessToken.length()); // } // return null; Cookie cookies[] = req.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals("access_token")) { System.out.println("### DEBUG : ResolveToken: cookie value: "+cookie.getValue()); return cookie.getValue(); } } } return null; } public boolean validateToken(String token) { try { Jws<Claims> claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token); // System.out.println("Timestamp token : "+claims.getBody().getExpiration()+", timestamp: new date : "+new Date()); // if (claims.getBody().getExpiration().before(new Date())) { // return false; // } return true; } catch (ExpiredJwtException e) { boolean isTokenDeleted = invalidate(token); throw new ExpiredJwtException(null, null, "Token expired"); } catch (JwtException | IllegalArgumentException e) { throw new InvalidJwtAuthenticationException("Expired or invalid JWT token"); } } public boolean invalidate(String token) { if (token != null) { if (RedisUtil.INSTANCE.sismember("validjwt", token)) { RedisUtil.INSTANCE.srem("validjwt", token); return true; } } return false; } }
true
02003a48f16dd32f913af3888f128916076b989c
Java
Kiddie22/footballManager
/app/models/MatchData.java
UTF-8
1,273
2.75
3
[]
no_license
package models; import java.io.Serializable; public class MatchData implements Serializable { String teamOne; String teamTwo; int teamOneGoals; int teamTwoGoals; Date date; public MatchData(){}; public MatchData(String teamOne, String teamTwo, int teamOneGoals, int teamTwoGoals, Date date) { this.teamOne = teamOne; this.teamTwo = teamTwo; this.teamOneGoals = teamOneGoals; this.teamTwoGoals = teamTwoGoals; this.date = date; } public String getTeamOne() { return teamOne; } public void setTeamOne(String teamOne) { this.teamOne = teamOne; } public String getTeamTwo() { return teamTwo; } public void setTeamTwo(String teamTwo) { this.teamTwo = teamTwo; } public int getTeamOneGoals() { return teamOneGoals; } public void setTeamOneGoals(int teamOneGoals) { this.teamOneGoals = teamOneGoals; } public int getTeamTwoGoals() { return teamTwoGoals; } public void setTeamTwoGoals(int teamTwoGoals) { this.teamTwoGoals = teamTwoGoals; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } }
true
4cf6ded6714db81bf78ffb7aab5162aeb2f736d6
Java
Gunny576/448_Final
/VATM/src/DisplayDriver.java
UTF-8
6,140
3.296875
3
[]
no_license
import javax.swing.JFrame; /** Digital Automated Teller Machine. */ public class DisplayDriver { // Private internal variables private int state; private int prevState; private int accountNumber; private int newAccountNumber; private int accountPin; private Control theBank; // State constants public static final int START = 1; public static final int ACCTFAIL = 2; public static final int PIN = 3; public static final int PINFAIL = 4; public static final int CREATEACCT = 5; public static final int CREATEPIN = 6; public static final int TRANSACT = 7; public static final int WITHDRAW = 8; public static final int DEPOSIT = 9; public static final int CLOSED = 10; /** Constructor for the DisplayDriver class @param aBank the bank where all accounts reside */ public DisplayDriver(Control aBank) { theBank = aBank; init(); } /** Initialization method to keep the constructor clean */ private void init() { // Initialize internal variables accountNumber = -1; newAccountNumber = -1; accountPin = -1; state = START; prevState = 0; // Create the ATMFrame object JFrame frame = new ATMFrame(this); frame.setTitle("Virtual ATM - First Bank of Group 8"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } /** Sets the current account number and sets state to PIN. (Precondition: state is START or ACCTFAIL) @param number the account number. */ public void setAccountNumber(int number) { //assert state == START || state == ACCTFAIL; prevState = state; if (theBank.findAccount(number)) { accountNumber = number; state = PIN; } else state = ACCTFAIL; } /** Gets the current account number. (Precondition: state is TRANSACT) @return the account number */ public int getAccountNumber() { //assert state == TRANSACT; return accountNumber; } /** Tries a PIN for the current account. If found sets state to TRANSACT, else to PINFAIL. (Precondition: state is PIN) @param pin the PIN to attempt */ public void attemptPin(int pin) { //assert state == PIN; prevState = state; if (theBank.tryPin(accountNumber, pin)) { accountPin = pin; state = TRANSACT; } else state = PINFAIL; } public void createAccount() { //assert state == START || state == ACCTFAIL; prevState = state; state = CREATEACCT; } /** Sets the account number for the new account (Precondition: state is CREATEACCT) @param accountNumber the number of the new account */ public boolean createAccountNumber(int aNumber) { //assert state == CREATEACCT; if (theBank.findAccount(aNumber)) { back(); return false; } else { newAccountNumber = aNumber; prevState = state; state = CREATEPIN; return true; } } /** Sets the PIN for the new account. (Precondition: state is CREATEPIN) @param accountPin the new PIN */ public boolean createPin(int aPin) { //assert state == CREATEPIN; if (aPin >= 1000 && aPin <= 9999) { accountNumber = newAccountNumber; accountPin = aPin; theBank.createAccount(accountNumber, accountPin); back(); return true; } else { return false; } } /** Changes the state to WITHDRAW. (Precondition: state is TRANSACT) */ public void selectWithdraw() { //assert state == TRANSACT; prevState = state; state = WITHDRAW; } /** Withdraws amount from current account. (Precondition: state is TRANSACT) @param value the amount to withdraw */ public double withdraw(double value) { //assert state == TRANSACT; double result = theBank.withdraw(accountNumber, accountPin, value); back(); if (result >= 0) { return value; } else { return -1.0; } } /** Changes the state to DEPOSIT. (Precondition: state is TRANSACT) */ public void selectDeposit() { //assert state == TRANSACT; prevState = state; state = DEPOSIT; } /** Deposits amount to current account. (Precondition: state is TRANSACT) @param value the amount to deposit */ public double deposit(double value) { //assert state == TRANSACT; double result = theBank.deposit(accountNumber, accountPin, value); back(); if (result >= 0) { return value; } else { return -1.0; } } /** Gets the balance of the current account. (Precondition: state is TRANSACT) @return the balance */ public double getBalance() { //assert state == TRANSACT; return theBank.getBalance(accountNumber, accountPin); } /** Closes the bank account. */ public void closeAccount() { //assert state == TRANSACT; state = CLOSED; theBank.closeAccount(); } /** Moves back to the initial state. */ public void back() { prevState = state; if (state == CLOSED) { state = START; } else if (state > TRANSACT) { state = TRANSACT; } else { state = START; } } /** Gets the current state of the ATM display. @return the current state */ public int getState() { return state; } /** Gets the previous state of the ATM display. @return the previous state */ public int getPrevState() { return prevState; } }
true
0054249ebd70bbca88b82329ce5720c3b6893adf
Java
975zsk/AlgorithmLearning
/src/LeetCode/LinkedList/LeetCode21.java
UTF-8
991
3.25
3
[]
no_license
package LeetCode.LinkedList; /** * Created by Administrator on 2018/1/22. */ public class LeetCode21 { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if(l1 == null || l2 == null) return l1 == null ? l2 : l1; ListNode preNewHead = new ListNode(0); ListNode cur = preNewHead; while(l1 != null && l2 != null) { if(l1.val < l2.val) { cur.next = l1; l1 = l1.next; } else { cur.next = l2; l2 = l2.next; } cur = cur.next; } cur.next = l1 != null ? l1 : l2; return preNewHead.next; // if(l1 == null) return l2; // if(l2 == null) return l1; // if(l1.val < l2.val) { // l1.next = mergeTwoLists(l1.next, l2); // return l1; // } // else { // l2.next = mergeTwoLists(l1, l2.next); // return l2; // } } }
true
0ce230336ba0f90dd791417684b0a060ffdbc2ff
Java
Masebeni/Assignment6.3
/mobileBanking/app/src/androidTest/java/com/atm/services/RetrieveAccountInfoTest.java
UTF-8
2,567
2.125
2
[]
no_license
package com.atm.services; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; import android.test.AndroidTestCase; import com.atm.domain.account.impl.Credit; import com.atm.domain.client.Client; import com.atm.domain.client.impl.Business; import com.atm.factories.client.BusinessFactory; import com.atm.repository.account.CreditRepository; import com.atm.repository.account.impl.CreditRepositoryImpl; import com.atm.services.account.RetrieveAccountInfo; import com.atm.services.account.impl.RetrieveAccountInfoImpl; import junit.framework.Assert; /** * Created by Axe on 2016-05-13. */ public class RetrieveAccountInfoTest extends AndroidTestCase{ private RetrieveAccountInfo retrieveAccountInfo; private boolean isBound; @Override public void setUp() throws Exception { super.setUp(); Intent intent = new Intent(this.getContext(), RetrieveAccountInfoImpl.class); this.getContext().bindService(intent, connection, Context.BIND_AUTO_CREATE); } public ServiceConnection connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { RetrieveAccountInfoImpl.RetrieveAccountInfoLocalBinder binder = (RetrieveAccountInfoImpl.RetrieveAccountInfoLocalBinder) service; retrieveAccountInfo = binder.getService(); isBound = true; } @Override public void onServiceDisconnected(ComponentName name) { isBound = false; } }; public void testRetrieveAccountInfo() throws Exception { Long id; Business client = BusinessFactory.createBusinessClient("456", "ferin", "ferin@abc"); CreditRepository creditRepository = new CreditRepositoryImpl(this.getContext()); // CREATE Credit credit = new Credit.Builder() .accountNumber("1234") .balance(300) .limit(100) .pin("123") .client(client) .build(); Credit insertedEntity = creditRepository.save(credit); id = insertedEntity.getId(); Assert.assertNotNull(insertedEntity); Credit newEntity = new Credit.Builder() .copy(credit) .id(id) .build(); Credit credit1 = retrieveAccountInfo.getAccountInfo(newEntity); Assert.assertNotNull(credit1); } }
true
d4d6cd038627b70cc1d12ea41991c54392e71b42
Java
acjensen/CS196
/RubixCubeTest1/src/Algorithms.java
UTF-8
4,249
3.34375
3
[]
no_license
/** * Algorithms class contains algorithms: sets of permutations DONT FORGET TO SET * CUBE ORIENTATION BEFORE DOING ALGS */ public class Algorithms extends Permutation { // an algorithm - see ryanheise.com/cube/beginner.html -> // "Swap the incorrect cross pieces" public static void swapCrossPieces(int caseNum) { if (caseNum < 1 || caseNum > 3) throw new RuntimeException("Invalid case number " + caseNum); switch (caseNum) { case 1: // adjacent faced pairs rotate180(RIGHT); rotateCW(UP); rotate180(FRONT); rotateCCW(UP); rotate180(RIGHT); break; case 2: // opposite faced pairs rotate180(RIGHT); rotate180(UP); rotate180(LEFT); rotate180(UP); rotate180(RIGHT); break; case 3: // rotate bottom face to match pairs initially rotateCW(DOWN); break; } } public static void insertBottomCorners(int caseNum) { if (caseNum < 1 || caseNum > 5) { throw new RuntimeException("Invalid case number " + caseNum); } switch (caseNum) { case 1: // yellow piece is in bottom layer, bring it up top rotateCW(RIGHT); rotateCCW(UP); rotateCCW(RIGHT); break; case 2: // rotates top face once rotateCCW(UP); break; case 3: rotateCW(RIGHT); rotateCW(UP); rotateCCW(RIGHT); break; case 4: rotateCCW(FRONT); rotateCCW(UP); rotateCW(FRONT); break; case 5: rotateCW(RIGHT); rotateCCW(UP); rotateCCW(RIGHT); rotate180(UP); break; } } public static void secondLayer(int caseNum) { if (caseNum < 1 || caseNum > 4) throw new RuntimeException("Invalid case number " + caseNum); switch (caseNum) { case 1: // ryanheise case 1 rotateCW(UP); rotateCW(RIGHT); rotateCCW(UP); rotateCCW(RIGHT); rotateCCW(UP); rotateCCW(FRONT); rotateCW(UP); rotateCW(FRONT); break; case 2: // mirror case of 1 rotateCCW(UP); rotateCCW(LEFT); rotateCW(UP); rotateCW(LEFT); rotateCW(UP); rotateCW(FRONT); rotateCCW(UP); rotateCCW(FRONT); break; case 3: // "force out" the piece // this is equal to case 1 OR 2, doesn't need to be called rotateCCW(UP); rotateCCW(FRONT); rotateCW(UP); rotateCW(FRONT); rotateCW(UP); rotateCW(RIGHT); rotateCCW(UP); rotateCCW(RIGHT); break; case 4: //rotates top till matches rotateCW(UP); } } public static void makeEdgesFaceUp(int caseNum) { if (caseNum < 1 || caseNum > 2) throw new RuntimeException("Invalid case number " + caseNum); switch (caseNum) { case 1: // used to rotate top to get ryanheise case 1, 2, or 3 rotateCW(UP); break; // all ryanheise cases use this same alg on front face case 2: rotateCCW(RIGHT); rotateCCW(UP); rotateCCW(FRONT); rotateCW(UP); rotateCW(FRONT); rotateCW(RIGHT); break; } } public static void makeCornersFaceUp(int caseNum) { if (caseNum < 1 || caseNum > 2) throw new RuntimeException("Invalid case number " + caseNum); switch (caseNum) { case 1: // used in ryanheise cases 3-7 rotateCW(RIGHT); rotateCW(UP); rotateCCW(RIGHT); rotateCW(UP); rotateCW(RIGHT); rotate180(UP); rotateCCW(RIGHT); break; case 2: // mirror of case 1 (FRONT IS GREEN) rotateCCW(LEFT); rotateCCW(UP); rotateCW(LEFT); rotateCCW(UP); rotateCCW(LEFT); rotate180(UP); rotateCW(LEFT); break; } } public static void positionCorners(int caseNum) { if (caseNum < 1 || caseNum > 3) throw new RuntimeException("Invalid case number " + caseNum); switch (caseNum) { case 1: // used in ryanheise cases 1,4 rotateCCW(RIGHT); rotateCW(FRONT); rotateCCW(RIGHT); rotate180(BACK); rotateCW(RIGHT); rotateCCW(FRONT); rotateCCW(RIGHT); rotate180(BACK); rotate180(RIGHT); break; case 2: // mirror of case 1 (FRONT IS GREEN) rotateCW(LEFT); rotateCCW(FRONT); rotateCW(LEFT); rotate180(BACK); rotateCCW(LEFT); rotateCW(FRONT); rotateCW(LEFT); rotate180(BACK); rotate180(LEFT); break; case 3: // ryanheise case 3 rotates top rotateCW(UP); break; } } }
true
529099f01dadfc3b391f54772be61fb46160b9d7
Java
trust-freedom/rocketmq-spring-boot-starter
/src/main/java/com/freedom/starter/rocketmq/config/RocketMQProperties.java
UTF-8
4,226
2.421875
2
[]
no_license
package com.freedom.starter.rocketmq.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties( prefix = "spring.rocketmq") public class RocketMQProperties { /** * name server for rocketmq * formats: `host:port;host:port` */ private String nameServer; /** * producer group 生产组 */ private Producer producer = new Producer(); //默认为空的Producer,否则application.yml中没有相关配置producer为null /** * Producer参数 */ public static class Producer { /** 生产组 */ private String group; /** 是否vip通道,默认值false */ private boolean vipChannelEnabled = false; /** * 发送消息超时时间,单位毫秒,默认值3000 */ private int sendMsgTimeout = 3000; /** * 压缩消息体的阀值,默认1024 * 4,4k,即默认大于4k的消息体将开启压缩 */ private int compressMsgBodyOverHowmuch = 1024 * 4; /** * 在同步模式下,声明发送失败之前内部执行的最大重试次数 * 这可能会导致消息重复,应用程序开发人员需要解决此问题 */ private int retryTimesWhenSendFailed = 2; /** * 在异步模式下,声明发送失败之前内部执行的最大重试次数 * 这可能会导致消息重复,应用程序开发人员需要解决此问题 */ private int retryTimesWhenSendAsyncFailed = 2; /** * 内部发送失败时是否重试另一个broker */ private boolean retryAnotherBrokerWhenNotStoreOk = false; /** * 消息体最大值,单位byte,默认4Mb */ private int maxMessageSize = 1024 * 1024 * 4; // 4M public String getGroup() { return group; } public void setGroup(String group) { this.group = group; } public boolean isVipChannelEnabled() { return vipChannelEnabled; } public void setVipChannelEnabled(boolean vipChannelEnabled) { this.vipChannelEnabled = vipChannelEnabled; } public int getSendMsgTimeout() { return sendMsgTimeout; } public void setSendMsgTimeout(int sendMsgTimeout) { this.sendMsgTimeout = sendMsgTimeout; } public int getCompressMsgBodyOverHowmuch() { return compressMsgBodyOverHowmuch; } public void setCompressMsgBodyOverHowmuch(int compressMsgBodyOverHowmuch) { this.compressMsgBodyOverHowmuch = compressMsgBodyOverHowmuch; } public int getRetryTimesWhenSendFailed() { return retryTimesWhenSendFailed; } public void setRetryTimesWhenSendFailed(int retryTimesWhenSendFailed) { this.retryTimesWhenSendFailed = retryTimesWhenSendFailed; } public int getRetryTimesWhenSendAsyncFailed() { return retryTimesWhenSendAsyncFailed; } public void setRetryTimesWhenSendAsyncFailed(int retryTimesWhenSendAsyncFailed) { this.retryTimesWhenSendAsyncFailed = retryTimesWhenSendAsyncFailed; } public boolean isRetryAnotherBrokerWhenNotStoreOk() { return retryAnotherBrokerWhenNotStoreOk; } public void setRetryAnotherBrokerWhenNotStoreOk(boolean retryAnotherBrokerWhenNotStoreOk) { this.retryAnotherBrokerWhenNotStoreOk = retryAnotherBrokerWhenNotStoreOk; } public int getMaxMessageSize() { return maxMessageSize; } public void setMaxMessageSize(int maxMessageSize) { this.maxMessageSize = maxMessageSize; } } public String getNameServer() { return nameServer; } public void setNameServer(String nameServer) { this.nameServer = nameServer; } public Producer getProducer() { return producer; } public void setProducer(Producer producer) { this.producer = producer; } }
true
61fb9b833d63201c2597d6a82ea8cba7726e121e
Java
Phongdh1997/StackOverflow-User
/app/src/main/java/com/example/stackoverflowuser/common/UserPagedListConfig.java
UTF-8
242
1.515625
2
[]
no_license
package com.example.stackoverflowuser.common; public class UserPagedListConfig { public static final int DATABASE_PAGE_SIZE = 50; public static final int NETWORK_PAGE_SIZE = 120; public static final int PREFETCH_DISTANCE = 25; }
true
70ff1e1e2c6d0b33c94ce20af028237f9f7498ab
Java
Padepokan79/BootcampG8
/Iqbal/Agustus-29-2018/src/MainPerson.java
UTF-8
574
2.859375
3
[]
no_license
import java.util.ArrayList; public class MainPerson { public static void main(String[] args) { ArrayList<Person> orang = new ArrayList<Person>(); Person iqbal = new Person("Iqbal" , "FM"); iqbal.setAge(18); iqbal.setInterests("Bermain Game"); Person bayu = new Person("Bayu" , "Doang"); bayu.setAge(24); bayu.setInterests("Bernyanyi"); Person tony = new Person("tony" , "Sul"); tony.setAge(18); tony.setInterests("Berdansa"); orang.add(iqbal); orang.add(bayu); orang.add(tony); for (Person person : orang) { person.tampil(); } } }
true
f9e2665942ee838797260839407e8adedcb3ae10
Java
qqgirllianxin/hell
/hell-ml/src/main/java/ps/hell/ml/nlp/tool/hanlp/hankcs/test/corpus/TestStopWordDictionary.java
UTF-8
1,644
2.1875
2
[]
no_license
/* * <summary></summary> * <author>He Han</author> * <email>[email protected]</email> * <create-date>2014/12/24 20:01</create-date> * * <copyright file="TestStopWordDictionary.java" company="上海林原信息科技有限公司"> * Copyright (c) 2003-2014, 上海林原信息科技有限公司. All Right Reserved, http://www.linrunsoft.com/ * This source is subject to the LinrunSpace License. Please contact 上海林原信息科技有限公司 to get more information. * </copyright> */ package ps.hell.ml.nlp.tool.hanlp.hankcs.test.corpus; import ps.hell.ml.nlp.tool.hanlp.hankcs.hanlp.HanLP; import ps.hell.ml.nlp.tool.hanlp.hankcs.hanlp.collection.MDAG.MDAGSet; import ps.hell.ml.nlp.tool.hanlp.hankcs.hanlp.dictionary.stopword.CoreStopWordDictionary; import junit.framework.TestCase; import java.util.LinkedList; import java.util.List; /** * @author hankcs */ public class TestStopWordDictionary extends TestCase { public void testContains() throws Exception { HanLP.Config.enableDebug(); System.out.println(CoreStopWordDictionary.contains("这就是说")); } public void testContainsSomeWords() throws Exception { assertEquals(true, CoreStopWordDictionary.contains("可以")); } public void testMDAG() throws Exception { List<String> wordList = new LinkedList<String>(); wordList.add("zoo"); wordList.add("hello"); wordList.add("world"); MDAGSet set = new MDAGSet(wordList); set.add("bee"); assertEquals(true, set.contains("bee")); set.remove("bee"); assertEquals(false, set.contains("bee")); } }
true
8a63d5bc1f1835227c51b4c36505387bb4dcfe6e
Java
tuliocastro/node-keyboard-hook
/java/src/main/java/br/com/tlabs/kbhook/Main.java
UTF-8
1,712
2.46875
2
[ "MIT" ]
permissive
package br.com.tlabs.kbhook; import br.com.tlabs.kbhook.util.SystemUtil; import org.jnativehook.GlobalScreen; import org.jnativehook.NativeHookException; import java.io.File; import java.io.FilenameFilter; import java.util.Arrays; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.Logger; public class Main { public static void main(String[] args) throws NativeHookException { KeyboardListener listener = new KeyboardListener(System.out); clearTemporaryFiles(); disableLogs(); GlobalScreen.unregisterNativeHook(); GlobalScreen.registerNativeHook(); GlobalScreen.addNativeKeyListener(listener); } private static void disableLogs() { System.setOut(null); Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName()); logger.setLevel(Level.OFF); // Change the level for all handlers attached to the default logger. Handler[] handlers = Logger.getLogger("").getHandlers(); for (int i = 0; i < handlers.length; i++) { handlers[i].setLevel(Level.OFF); } } private static void clearTemporaryFiles() { switch (SystemUtil.getOS()) { case WINDOWS: removeTemporaryFiles(); break; } } private static void removeTemporaryFiles() { String tempDir = System.getProperty("java.io.tmpdir"); FilenameFilter filterNativeHook = (dir, name) -> name.startsWith("JNativeHook-") && name.endsWith(".dll"); File[] list = new File(tempDir).listFiles(filterNativeHook); Arrays.stream(list).forEach(f -> f.delete()); } }
true
3765b8da77d08a0a07fe676036d1880e14c098d5
Java
rubasace/bias-fx-preset-manager
/bias-fx-preset-manager-app/src/main/java/com/rubasace/bias/preset/manager/app/util/ResourceManager.java
UTF-8
616
2.28125
2
[]
no_license
package com.rubasace.bias.preset.manager.app.util; import org.springframework.stereotype.Component; import java.io.InputStream; import java.net.URL; @Component public class ResourceManager { private final ClassLoader classLoader; public ResourceManager() { this.classLoader = this.getClass().getClassLoader(); } public URL get(String name) { return this.classLoader.getResource(name); } public String getAsString(String name) { return this.classLoader.getResource(name).toExternalForm(); } public InputStream getAsStream(String name) { return this.classLoader.getResourceAsStream(name); } }
true
1ea87b9187ff3d2ba4984578c1809404acea15b2
Java
balkrishnaValvoline/hr_cf_w4
/service_layer/src/main/java/valv/hr/connectivity/rfc/importParams/models/NEW_P0210_US.java
UTF-8
951
1.820313
2
[]
no_license
package valv.hr.connectivity.rfc.importParams.models; import java.util.Date; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonProperty; @JsonAutoDetect(setterVisibility = Visibility.NONE, getterVisibility = Visibility.NONE, creatorVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) public class NEW_P0210_US { @JsonProperty String PI_PERNR; @JsonProperty String PI_SUBTY = "FED"; @JsonProperty Date PI_EFF_DATE; public String getPI_PERNR() { return PI_PERNR; } public void setPI_PERNR(String pI_PERNR) { PI_PERNR = pI_PERNR; } public String getPI_SUBTY() { return PI_SUBTY; } public void setPI_SUBTY(String pI_SUBTY) { PI_SUBTY = pI_SUBTY; } public Date getPI_EFF_DATE() { return PI_EFF_DATE; } public void setPI_EFF_DATE(Date pI_EFF_DATE) { PI_EFF_DATE = pI_EFF_DATE; } }
true
3c898fa8a01ce14b5d85009dea0de07af5874928
Java
a542120974/MVVM-Demo
/app/src/main/java/com/example/databindingdemo/viewmodel/ListBeanViewModel.java
UTF-8
550
1.726563
2
[]
no_license
package com.example.databindingdemo.viewmodel; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; import com.example.databindingdemo.model.bean.ListBean; import com.example.databindingdemo.model.repository.ListBeanRepository; import java.util.List; public class ListBeanViewModel extends ViewModel { public MutableLiveData<Boolean> notify = new MutableLiveData<>(); public MutableLiveData<List<ListBean>> data = new MutableLiveData<>(); public ListBeanRepository request = new ListBeanRepository(); }
true
5cad7bb75e850716909489dfffc57fc4304040af
Java
Create-your-name/lan-qiao-bei
/_1_t1.java
GB18030
492
2.78125
3
[]
no_license
package _2_4; import java.util.Scanner; public class t1 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner input =new Scanner(System.in); int n=input.nextInt(); // int m=input.nextInt(); // int duo;//ճ int lie; int max=m*n; if(n%3==0) { duo=n/3; }else{ duo=n/3+1; } lie=m/6; int sum=0; sum=max-( (duo*m) + (lie*n) - (duo*lie) ); System.out.print(sum); } }
true
6e22d2060273f6f2c435b5d4ca1fe5ef0d686f89
Java
adament67/FinalBoost
/Boost/app/src/main/java/com/trivialworks/boost/NoteActivity.java
UTF-8
850
1.882813
2
[]
no_license
package com.trivialworks.boost; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import constant.BaseActivity; public class NoteActivity extends BaseActivity { Button scheduleNowButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_note); setHeading("Note"); backClick(); scheduleNowButton=(Button)findViewById(R.id.scheduleNowButton); scheduleNowButton.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.scheduleNowButton: goToActivity(PaymentInfoActivity.class, null); break; } } }
true
181c4b10fc74140aba6130dfa7715d1281811f03
Java
mireiamorales/spring-boot-demo
/src/test/java/com/concretepage/dao/integration/test/ArticleDAOIntegrationTest.java
UTF-8
2,217
2.328125
2
[]
no_license
package com.concretepage.dao.integration.test; import static org.junit.Assert.*; import java.util.List; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.junit.runners.MethodSorters; import com.concretepage.dao.IArticleDAO; import com.concretepage.entity.Article; @RunWith(SpringRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @SpringBootTest public class ArticleDAOIntegrationTest { static int articleId; @Autowired private IArticleDAO articleDAO; @Test public void test1AddArticle() { Article article = new Article(); article.setTitle("Article title 1"); article.setCategory("Article category 1"); articleDAO.addArticle(article); assertTrue(article.getArticleId() > 0); articleId = article.getArticleId(); } @Test public void test2GetArticleById() { Article article = articleDAO.getArticleById(articleId); assertEquals(articleId, article.getArticleId()); assertEquals("Article title 1", article.getTitle()); assertEquals("Article category 1", article.getCategory()); } @Test public void test3ArticlesExists() { assertTrue(articleDAO.articleExists("Article title 1", "Article category 1")); } @Test public void test4GetAllArticles() throws Exception { List<Article> articleList = articleDAO.getAllArticles(); assertTrue(articleList.size() > 0); } @Test public void test5UpdateArticle() throws Exception { Article article = articleDAO.getArticleById(articleId); article.setTitle("New article title"); article.setCategory("New article category"); articleDAO.updateArticle(article); Article articleUpdated = articleDAO.getArticleById(articleId); assertEquals(articleId, articleUpdated.getArticleId()); assertEquals("New article title", articleUpdated.getTitle()); assertEquals("New article category", articleUpdated.getCategory()); } @Test public void test6DeleteArticle() throws Exception { articleDAO.deleteArticle(articleId); assertNull(articleDAO.getArticleById(articleId)); } }
true
0bacc58513d8fad56a943775f5efe3a12cc3de1a
Java
K-OverCloud/Composable-UnderCloud-DTN
/NSI WebPortal/WEB-INF/classes/com/netmng/dto/twt/SearchResultM11DTO.java
UTF-8
356
1.765625
2
[]
no_license
package com.netmng.dto.twt; import com.netmng.vo.twt.SearchResultM; public class SearchResultM11DTO extends SearchResultM { private SearchListD11DTO search_list_d; public SearchListD11DTO getSearch_list_d() { return this.search_list_d; } public void setSearch_list_d(SearchListD11DTO search_list_d) { this.search_list_d = search_list_d; } }
true
8bfe13c1acff0b8a464ef3b5b4d6d0e314972a56
Java
dilyanrusev/foopaint
/src/uk/ac/standrews/cs5001/foopaint/data/ImageData.java
UTF-8
2,438
3.359375
3
[]
no_license
package uk.ac.standrews.cs5001.foopaint.data; /** * Class for storing data needed to draw an image on screen * @author <110017972> * */ public class ImageData extends ExternalResource { /** Increased when new fields are added */ private static final long serialVersionUID = 2L; /** Horizontal component of the top left point defining the position of the image on screen */ private int x; /** Vertical component of the top left point defining the position of the image on screen */ private int y; /** Brush to use if there is an error */ private BrushData errorBrush; /** * Create empty image data */ public ImageData() { this((String)null); } /** * Create an external resource * @param path Path on the file system to the file containing the external resource */ public ImageData(String path) { super(path); this.x = 0; this.y = 0; this.errorBrush = new BrushData(); } /** * Create a copy of another external resource * @param other Resource to copy */ public ImageData(ImageData other) { super(other); this.x = other.x; this.y = other.y; this.errorBrush = new BrushData(other.errorBrush); } /** * Set the position of the image on screen * @param x Horizontal component * @param y Vertical component */ public void setPosition(int x, int y) { this.x = x; this.y = y; } /** * Set position coordinate's horizontal component * @param x Position coordinate's horizontal component */ public void setX(int x) { this.x = x; } /** * Set position coordinate's vertical component * @param y Position coordinate's horizontal component */ public void setY(int y) { this.y = y; } /** * Get image position coordinate's horizontal component * @return Position coordinate's horizontal component */ public int getX() { return this.x; } /** * Get image position coordinate's vertical component * @return Position coordinate's vertical component */ public int getY() { return this.y; } /** * Set brush to use when indicating error * @param brush Brush used for drawing an error message */ public void setErrorBrush(BrushData brush) { this.errorBrush = brush; } /** * Get brush to use when drawing error message * @return Brush */ public BrushData getErrorBrush() { return this.errorBrush; } }
true
e43d0179d5253ab6c38b6b3ed130dbfe9be0c6b3
Java
AndreiSuprun/task2_3
/java/com/suprun/periodicals/service/SubscriptionService.java
UTF-8
5,514
2.25
2
[]
no_license
package com.suprun.periodicals.service; import com.suprun.periodicals.dao.DaoException; import com.suprun.periodicals.dao.DaoFactory; import com.suprun.periodicals.dao.SubscriptionDao; import com.suprun.periodicals.dao.SubscriptionPeriodDao; import com.suprun.periodicals.entity.*; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.math.BigDecimal; import java.time.LocalDate; import java.util.List; import java.util.Optional; public class SubscriptionService { private static final Logger LOGGER = LogManager.getLogger(SubscriptionService.class); private SubscriptionDao subscriptionDao = DaoFactory.getInstance().getSubscriptionDao(); private SubscriptionPeriodDao subscriptionPeriodDao = DaoFactory.getInstance().getSubscriptionPlanDao(); private PaymentService paymentService = ServiceFactory.getPaymentService(); private PeriodicalService periodicalService = ServiceFactory.getPeriodicalService(); private SubscriptionService() { } private static class Singleton { private final static SubscriptionService INSTANCE = new SubscriptionService(); } public static SubscriptionService getInstance() { return SubscriptionService.Singleton.INSTANCE; } public List<Subscription> findAllSubscriptionsByUserAndStatus(User user, boolean isExpired, long skip, long limit) throws ServiceException { LOGGER.debug("Attempt to find all subscriptions by user and status"); try { return subscriptionDao.findByUserAndStatus(user, isExpired, skip, limit); } catch (DaoException e) { throw new ServiceException(e); } } public List<Subscription> findAllSubscriptionsByPayment(Payment payment) throws ServiceException { LOGGER.debug("Attempt to find all subscriptions by payment"); List<Subscription> subscriptions; try { subscriptions = subscriptionDao.findByPayment(payment); } catch (DaoException e) { throw new ServiceException(e); } if (subscriptions.size() > 0) { return subscriptions; } else { LOGGER.error("Payment cannot exist without subscription: {}", payment); throw new ServiceException("Payment cannot exist without subscription!"); } } public long getSubscriptionsCountByUserAndStatus(User user, boolean isExpired) throws ServiceException { LOGGER.debug("Attempt to get active subscriptions count by user"); try { return subscriptionDao.getCountByUserAndStatus(user, isExpired); } catch (DaoException e) { throw new ServiceException(e); } } public void processSubscriptions(User user, List<Subscription> subscriptions, BigDecimal totalPrice) throws ServiceException { LOGGER.debug("Attempt to process subscriptions"); if (subscriptions.size() != 0) { for (Subscription subscription : subscriptions) { Periodical periodical = periodicalService.findPeriodicalById(subscription.getPeriodical().getId()) .orElseThrow(() -> new ServiceException( "Subscription cannot refer to a non-existent periodical")); if (!periodical.getAvailability()) { throw new ServiceException("Can't subscribe to periodical with SUSPEND status"); } LocalDate startDate = LocalDate.now().plusMonths(1).withDayOfMonth(1); subscription.setStartDate(startDate); BigDecimal price = (periodical.getPrice()).multiply(subscription.getSubscriptionPeriod().getRate()); try { paymentService.createPayment(subscription, price); subscriptionDao.insert(subscription); } catch (DaoException e) { throw new ServiceException(e); } } } } public boolean isAlreadySubscribed(User user, Periodical periodical) throws ServiceException { LOGGER.debug("Attempt to check that user is already subscribed"); try { return subscriptionDao.isUserAlreadySubscribed(user, periodical); } catch (DaoException e) { throw new ServiceException(e); } } public List<SubscriptionPeriod> findAllSubscriptionPeriods() throws ServiceException { LOGGER.debug("Attempt to find all subscription plans"); try { return subscriptionPeriodDao.findAll(); } catch (DaoException e) { throw new ServiceException(e); } } public Optional<SubscriptionPeriod> findSubscriptionPeriodById(Integer id) throws ServiceException { LOGGER.debug("Attempt to find subscription plan by id"); try { return subscriptionPeriodDao.findOne(id); } catch (DaoException e) { throw new ServiceException(e); } } }
true
41e89063e66419c841125ad97b63cbb15fefa86d
Java
a497556016/demo
/src/main/java/com/weishop/service/impl/ProductServiceImpl.java
UTF-8
471
1.578125
2
[]
no_license
package com.weishop.service.impl; import com.weishop.pojo.Product; import com.weishop.mapper.ProductMapper; import com.weishop.service.IProductService; import com.baomidou.mybatisplus.service.impl.ServiceImpl; import org.springframework.stereotype.Service; /** * <p> * 商品 服务实现类 * </p> * * @author HeShaowei * @since 2017-10-27 */ @Service public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService { }
true
1902786c5ed6d74f9665ceda682086f6dd590fa6
Java
wiktorjezierski/mortgageCalculator
/MortgageCalculator/src/main/java/MortgageCalculator/MortgageCalculator/logic/Request.java
UTF-8
3,483
2.703125
3
[]
no_license
package MortgageCalculator.MortgageCalculator.logic; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; public class Request { private double kwota; private int okres; private double marza; private double wibor; private double commission; private double nadplata; private KindOfOverpayment kindOfOverpayment; private int opoznienieNadplaty; private CzestotliwoscNadplat czestotliwoscNadplat; private Map<Integer, Double> zmianaMarzy; private Map<Integer, Double> zmianaWiboru; public Request() { zmianaMarzy = new HashMap<>(); zmianaWiboru = new HashMap<>(); } public double getKwota() { return kwota; } public void setKwota(double kwota) { this.kwota = kwota; } public int getOkres() { return okres; } public void setOkres(int okres) { this.okres = okres; } public double getMarza() { return marza; } public void setMarza(double marza) { this.marza = marza; } public double getWibor() { return wibor; } public void setWibor(double wibor) { this.wibor = wibor; } public double getCommission() { return commission; } public double getAmountOfCommission() { return (commission / 100) * kwota; } public void setProwizja(double prowizja) { this.commission = prowizja; } public double getNadplata() { return nadplata; } public void setNadplata(double nadplata) { this.nadplata = nadplata; } public KindOfOverpayment getKindOfOverpayment() { return kindOfOverpayment; } public void setKindOfOverpayment(KindOfOverpayment kindOfOverpayment) { this.kindOfOverpayment = kindOfOverpayment; } public int getOpoznienieNadplaty() { return opoznienieNadplaty; } public void setOpoznienieNadplaty(int opoznienieNadplaty) { this.opoznienieNadplaty = opoznienieNadplaty; } public CzestotliwoscNadplat getCzestotliwoscNadplat() { return czestotliwoscNadplat; } public void setCzestotliwoscNadplat(CzestotliwoscNadplat czestotliwoscNadplat) { this.czestotliwoscNadplat = czestotliwoscNadplat; } public Map<Integer, Double> getZmianaMarzy() { return zmianaMarzy; } public void setZmianaMarzy(Map<Integer, Double> zmianaMarzy) { this.zmianaMarzy = zmianaMarzy; } public Map<Integer, Double> getZmianaWiboru() { return zmianaWiboru; } public void setZmianaWiboru(Map<Integer, Double> zmianaWiboru) { this.zmianaWiboru = zmianaWiboru; } public double getOprocentowanie(int yearLength) { return (marza + wibor) / (100.0 * (double) yearLength); } public double getOprocentowanie(int rata, double obecneOprocentowanie, int yearLength) { Double nowaMarza = zmianaMarzy.get(rata); Double nowyWibor = zmianaWiboru.get(rata); if (nowaMarza == null && nowyWibor == null) { return obecneOprocentowanie; } if (nowaMarza == null) { nowaMarza = findValidValue(rata, zmianaMarzy, marza); } if (nowyWibor == null) { nowyWibor = findValidValue(rata, zmianaWiboru, wibor); } return (nowaMarza + nowyWibor) / (100 * (double) yearLength); } private double findValidValue(int range, Map<Integer, Double> values, double defaultValue) { int lastKey = 0; for (Entry<Integer, Double> entry : values.entrySet()) { if(entry.getKey() < range) { lastKey = entry.getKey(); } else { return values.get(lastKey); } } return defaultValue; } }
true
c208aa4601a22d831a059d7ce3ae6d33b10e8e90
Java
andrewglowacki/nifi-hdfs-repository
/nifi-hdfs-content-repository/src/main/java/org/apache/nifi/hdfs/repository/ClaimOutputStream.java
UTF-8
2,824
2.5
2
[ "Apache-2.0" ]
permissive
package org.apache.nifi.hdfs.repository; import java.io.IOException; import java.io.OutputStream; import org.apache.nifi.controller.repository.claim.StandardContentClaim; import org.apache.nifi.stream.io.ByteCountingOutputStream; public class ClaimOutputStream extends OutputStream { protected final StandardContentClaim claim; protected final ByteCountingOutputStream outStream; protected final ClaimClosedHandler handler; protected long bytesWritten = 0; protected boolean recycle = true; protected boolean closed = false; public ClaimOutputStream(ClaimClosedHandler handler, StandardContentClaim claim, ByteCountingOutputStream outStream) { this.handler = handler; this.claim = claim; this.outStream = outStream; } @Override public String toString() { return "ContentRepository Stream [" + claim + "]"; } public boolean canRecycle() { return recycle; } public StandardContentClaim getClaim() { return claim; } public ByteCountingOutputStream getOutStream() { return outStream; } @Override public synchronized void write(final int b) throws IOException { if (closed) { throw new IOException("Stream is closed"); } try { outStream.write(b); } catch (final IOException ioe) { recycle = false; throw new IOException("Failed to write to " + this, ioe); } bytesWritten++; claim.setLength(bytesWritten); } @Override public synchronized void write(final byte[] b) throws IOException { if (closed) { throw new IOException("Stream is closed"); } try { outStream.write(b); } catch (final IOException ioe) { recycle = false; throw new IOException("Failed to write to " + this, ioe); } bytesWritten += b.length; claim.setLength(bytesWritten); } @Override public synchronized void write(final byte[] b, final int off, final int len) throws IOException { if (closed) { throw new IOException("Stream is closed"); } try { outStream.write(b, off, len); } catch (final IOException ioe) { recycle = false; throw new IOException("Failed to write to " + this, ioe); } bytesWritten += len; claim.setLength(bytesWritten); } @Override public synchronized void flush() throws IOException { if (closed) { throw new IOException("Stream is closed"); } outStream.flush(); } @Override public synchronized void close() throws IOException { closed = true; handler.claimClosed(this); } }
true
fe1ff71782d93b447b6c344d664d4a0bb08667eb
Java
corkili/learningserver
/learningserver-scorm/src/main/java/com/corkili/learningserver/scorm/sn/model/tracking/ObjectiveProgressInformation.java
UTF-8
16,831
2.34375
2
[]
no_license
package com.corkili.learningserver.scorm.sn.model.tracking; import com.corkili.learningserver.scorm.sn.model.datatype.DecimalWithRange; import com.corkili.learningserver.scorm.sn.model.definition.ObjectiveDescription; import com.corkili.learningserver.scorm.sn.model.definition.ObjectiveMap; import com.corkili.learningserver.scorm.sn.model.global.GlobalObjectiveDescription; /** * For each attempt on an activity, a learner gets one set of objective progress information for * each objective associated with the activity. */ public class ObjectiveProgressInformation { private final Object context; private boolean objectiveProgressStatus; private boolean objectiveSatisfiedStatus; private boolean objectiveMeasureStatus; private final DecimalWithRange objectiveNormalizedMeasure; private boolean objectiveCompletionProgressStatus; private boolean objectiveCompletionStatus; private boolean objectiveCompletionAmountStatus; private final DecimalWithRange objectiveCompletionAmount; public ObjectiveProgressInformation(Object context) { this.context = context; objectiveProgressStatus = false; objectiveSatisfiedStatus = false; objectiveMeasureStatus = false; objectiveNormalizedMeasure = new DecimalWithRange(0, -1, 1, 4); objectiveCompletionStatus = false; objectiveCompletionAmountStatus = false; objectiveCompletionAmount = new DecimalWithRange(0, 0, 1, 4); } public void reinit() { objectiveProgressStatus = false; objectiveSatisfiedStatus = false; objectiveMeasureStatus = false; objectiveNormalizedMeasure.setValue(0); objectiveCompletionStatus = false; objectiveCompletionAmountStatus = false; objectiveCompletionAmount.setValue(0); } public Object getContext() { return context; } public boolean isObjectiveProgressStatus() { if (context instanceof ObjectiveDescription) { ObjectiveDescription objectiveDescription = (ObjectiveDescription) context; for (ObjectiveMap objectiveMap : objectiveDescription.getObjectiveMaps()) { GlobalObjectiveDescription globalObjectiveDescription = objectiveDescription.getContext().getContext() .findGlobalObjectiveDescription(objectiveMap.getTargetObjectiveID()); if (objectiveMap.isReadObjectiveSatisfiedStatus()) { if (globalObjectiveDescription.getObjectiveProgressInformation().isObjectiveProgressStatus()) { return globalObjectiveDescription.getObjectiveProgressInformation().isObjectiveProgressStatus(); } else { return objectiveProgressStatus; } } } } return objectiveProgressStatus; } public void setObjectiveProgressStatus(boolean objectiveProgressStatus) { this.objectiveProgressStatus = objectiveProgressStatus; if (context instanceof ObjectiveDescription) { ObjectiveDescription objectiveDescription = (ObjectiveDescription) context; for (ObjectiveMap objectiveMap : objectiveDescription.getObjectiveMaps()) { GlobalObjectiveDescription globalObjectiveDescription = objectiveDescription.getContext().getContext() .findGlobalObjectiveDescription(objectiveMap.getTargetObjectiveID()); if (objectiveMap.isWriteObjectiveSatisfiedStatus()) { globalObjectiveDescription.getObjectiveProgressInformation().setObjectiveProgressStatus(objectiveProgressStatus); } } } } public boolean isObjectiveSatisfiedStatus() { if (context instanceof ObjectiveDescription) { ObjectiveDescription objectiveDescription = (ObjectiveDescription) context; for (ObjectiveMap objectiveMap : objectiveDescription.getObjectiveMaps()) { GlobalObjectiveDescription globalObjectiveDescription = objectiveDescription.getContext().getContext() .findGlobalObjectiveDescription(objectiveMap.getTargetObjectiveID()); if (objectiveMap.isReadObjectiveSatisfiedStatus()) { if (globalObjectiveDescription.getObjectiveProgressInformation().isObjectiveProgressStatus()) { return globalObjectiveDescription.getObjectiveProgressInformation().isObjectiveSatisfiedStatus(); } else { return objectiveSatisfiedStatus; } } } } return objectiveSatisfiedStatus; } public void setObjectiveSatisfiedStatus(boolean objectiveSatisfiedStatus) { this.objectiveSatisfiedStatus = objectiveSatisfiedStatus; if (context instanceof ObjectiveDescription) { ObjectiveDescription objectiveDescription = (ObjectiveDescription) context; for (ObjectiveMap objectiveMap : objectiveDescription.getObjectiveMaps()) { GlobalObjectiveDescription globalObjectiveDescription = objectiveDescription.getContext().getContext() .findGlobalObjectiveDescription(objectiveMap.getTargetObjectiveID()); if (objectiveMap.isWriteObjectiveSatisfiedStatus()) { globalObjectiveDescription.getObjectiveProgressInformation().setObjectiveSatisfiedStatus(objectiveSatisfiedStatus); } } } } public boolean isObjectiveMeasureStatus() { if (context instanceof ObjectiveDescription) { ObjectiveDescription objectiveDescription = (ObjectiveDescription) context; for (ObjectiveMap objectiveMap : objectiveDescription.getObjectiveMaps()) { GlobalObjectiveDescription globalObjectiveDescription = objectiveDescription.getContext().getContext() .findGlobalObjectiveDescription(objectiveMap.getTargetObjectiveID()); if (objectiveMap.isReadObjectiveNormalizedMeasure()) { if (globalObjectiveDescription.getObjectiveProgressInformation().isObjectiveMeasureStatus()) { return globalObjectiveDescription.getObjectiveProgressInformation().isObjectiveMeasureStatus(); } else { return objectiveMeasureStatus; } } } } return objectiveMeasureStatus; } public void setObjectiveMeasureStatus(boolean objectiveMeasureStatus) { this.objectiveMeasureStatus = objectiveMeasureStatus; if (context instanceof ObjectiveDescription) { ObjectiveDescription objectiveDescription = (ObjectiveDescription) context; for (ObjectiveMap objectiveMap : objectiveDescription.getObjectiveMaps()) { GlobalObjectiveDescription globalObjectiveDescription = objectiveDescription.getContext().getContext() .findGlobalObjectiveDescription(objectiveMap.getTargetObjectiveID()); if (objectiveMap.isWriteObjectiveNormalizedMeasure()) { globalObjectiveDescription.getObjectiveProgressInformation().setObjectiveMeasureStatus(objectiveMeasureStatus); } } } } public DecimalWithRange getObjectiveNormalizedMeasure() { if (context instanceof ObjectiveDescription) { ObjectiveDescription objectiveDescription = (ObjectiveDescription) context; for (ObjectiveMap objectiveMap : objectiveDescription.getObjectiveMaps()) { GlobalObjectiveDescription globalObjectiveDescription = objectiveDescription.getContext().getContext() .findGlobalObjectiveDescription(objectiveMap.getTargetObjectiveID()); if (objectiveMap.isReadObjectiveNormalizedMeasure()) { if (globalObjectiveDescription.getObjectiveProgressInformation().isObjectiveMeasureStatus()) { return globalObjectiveDescription.getObjectiveProgressInformation().getObjectiveNormalizedMeasure(); } else { return objectiveNormalizedMeasure; } } } } return objectiveNormalizedMeasure; } public void setObjectiveNormalizedMeasure(double objectiveNormalizedMeasure) { this.objectiveNormalizedMeasure.setValue(objectiveNormalizedMeasure); if (context instanceof ObjectiveDescription) { ObjectiveDescription objectiveDescription = (ObjectiveDescription) context; for (ObjectiveMap objectiveMap : objectiveDescription.getObjectiveMaps()) { GlobalObjectiveDescription globalObjectiveDescription = objectiveDescription.getContext().getContext() .findGlobalObjectiveDescription(objectiveMap.getTargetObjectiveID()); if (objectiveMap.isWriteObjectiveNormalizedMeasure()) { globalObjectiveDescription.getObjectiveProgressInformation().setObjectiveNormalizedMeasure(objectiveNormalizedMeasure); } } } } public boolean isObjectiveCompletionProgressStatus() { if (context instanceof ObjectiveDescription) { ObjectiveDescription objectiveDescription = (ObjectiveDescription) context; for (ObjectiveMap objectiveMap : objectiveDescription.getObjectiveMaps()) { GlobalObjectiveDescription globalObjectiveDescription = objectiveDescription.getContext().getContext() .findGlobalObjectiveDescription(objectiveMap.getTargetObjectiveID()); if (objectiveMap.isReadCompletionStatus()) { if (globalObjectiveDescription.getObjectiveProgressInformation().isObjectiveCompletionProgressStatus()) { return globalObjectiveDescription.getObjectiveProgressInformation().isObjectiveCompletionProgressStatus(); } else { return objectiveCompletionProgressStatus; } } } } return objectiveCompletionProgressStatus; } public void setObjectiveCompletionProgressStatus(boolean objectiveCompletionProgressStatus) { this.objectiveCompletionProgressStatus = objectiveCompletionProgressStatus; if (context instanceof ObjectiveDescription) { ObjectiveDescription objectiveDescription = (ObjectiveDescription) context; for (ObjectiveMap objectiveMap : objectiveDescription.getObjectiveMaps()) { GlobalObjectiveDescription globalObjectiveDescription = objectiveDescription.getContext().getContext() .findGlobalObjectiveDescription(objectiveMap.getTargetObjectiveID()); if (objectiveMap.isWriteCompletionStatus()) { globalObjectiveDescription.getObjectiveProgressInformation().setObjectiveCompletionProgressStatus(objectiveCompletionProgressStatus); } } } } public boolean isObjectiveCompletionStatus() { if (context instanceof ObjectiveDescription) { ObjectiveDescription objectiveDescription = (ObjectiveDescription) context; for (ObjectiveMap objectiveMap : objectiveDescription.getObjectiveMaps()) { GlobalObjectiveDescription globalObjectiveDescription = objectiveDescription.getContext().getContext() .findGlobalObjectiveDescription(objectiveMap.getTargetObjectiveID()); if (objectiveMap.isReadCompletionStatus()) { if (globalObjectiveDescription.getObjectiveProgressInformation().isObjectiveCompletionProgressStatus()) { return globalObjectiveDescription.getObjectiveProgressInformation().isObjectiveCompletionStatus(); } else { return objectiveSatisfiedStatus; } } } } return objectiveCompletionStatus; } public void setObjectiveCompletionStatus(boolean objectiveCompletionStatus) { this.objectiveCompletionStatus = objectiveCompletionStatus; if (context instanceof ObjectiveDescription) { ObjectiveDescription objectiveDescription = (ObjectiveDescription) context; for (ObjectiveMap objectiveMap : objectiveDescription.getObjectiveMaps()) { GlobalObjectiveDescription globalObjectiveDescription = objectiveDescription.getContext().getContext() .findGlobalObjectiveDescription(objectiveMap.getTargetObjectiveID()); if (objectiveMap.isWriteCompletionStatus()) { globalObjectiveDescription.getObjectiveProgressInformation().setObjectiveCompletionStatus(objectiveCompletionStatus); } } } } public boolean isObjectiveCompletionAmountStatus() { if (context instanceof ObjectiveDescription) { ObjectiveDescription objectiveDescription = (ObjectiveDescription) context; for (ObjectiveMap objectiveMap : objectiveDescription.getObjectiveMaps()) { GlobalObjectiveDescription globalObjectiveDescription = objectiveDescription.getContext().getContext() .findGlobalObjectiveDescription(objectiveMap.getTargetObjectiveID()); if (objectiveMap.isReadProgressMeasure()) { if (globalObjectiveDescription.getObjectiveProgressInformation().isObjectiveCompletionAmountStatus()) { return globalObjectiveDescription.getObjectiveProgressInformation().isObjectiveCompletionAmountStatus(); } else { return objectiveCompletionAmountStatus; } } } } return objectiveCompletionAmountStatus; } public void setObjectiveCompletionAmountStatus(boolean objectiveCompletionAmountStatus) { this.objectiveCompletionAmountStatus = objectiveCompletionAmountStatus; if (context instanceof ObjectiveDescription) { ObjectiveDescription objectiveDescription = (ObjectiveDescription) context; for (ObjectiveMap objectiveMap : objectiveDescription.getObjectiveMaps()) { GlobalObjectiveDescription globalObjectiveDescription = objectiveDescription.getContext().getContext() .findGlobalObjectiveDescription(objectiveMap.getTargetObjectiveID()); if (objectiveMap.isWriteProgressMeasure()) { globalObjectiveDescription.getObjectiveProgressInformation().setObjectiveCompletionAmountStatus(objectiveCompletionAmountStatus); } } } } public DecimalWithRange getObjectiveCompletionAmount() { if (context instanceof ObjectiveDescription) { ObjectiveDescription objectiveDescription = (ObjectiveDescription) context; for (ObjectiveMap objectiveMap : objectiveDescription.getObjectiveMaps()) { GlobalObjectiveDescription globalObjectiveDescription = objectiveDescription.getContext().getContext() .findGlobalObjectiveDescription(objectiveMap.getTargetObjectiveID()); if (objectiveMap.isReadProgressMeasure()) { if (globalObjectiveDescription.getObjectiveProgressInformation().isObjectiveCompletionAmountStatus()) { return globalObjectiveDescription.getObjectiveProgressInformation().getObjectiveCompletionAmount(); } else { return objectiveCompletionAmount; } } } } return objectiveCompletionAmount; } public void setObjectiveCompletionAmount(double objectiveCompletionAmount) { this.objectiveCompletionAmount.setValue(objectiveCompletionAmount); if (context instanceof ObjectiveDescription) { ObjectiveDescription objectiveDescription = (ObjectiveDescription) context; for (ObjectiveMap objectiveMap : objectiveDescription.getObjectiveMaps()) { GlobalObjectiveDescription globalObjectiveDescription = objectiveDescription.getContext().getContext() .findGlobalObjectiveDescription(objectiveMap.getTargetObjectiveID()); if (objectiveMap.isWriteProgressMeasure()) { globalObjectiveDescription.getObjectiveProgressInformation().setObjectiveCompletionAmount(objectiveCompletionAmount); } } } } }
true
e6f67b2ddc89d47908a734f9033a89119856ee6a
Java
vishnuys/PidginN
/pidgin-server/src/main/java/OOAD/Entities/UserMessageMapping.java
UTF-8
2,594
2.359375
2
[]
no_license
package OOAD.Entities; import java.util.Date; public class UserMessageMapping { public int SenderUserId; public int RecieverUserId; private Date messageSentTimestamp; private Date messageRecievedTimestamp; private Boolean messageReadByReciever; private Boolean isDirectMessage; public int GroupId; private Boolean isDeleted; public UserMessageMapping(int senderUserId, int recieverUserId) { this.SenderUserId = senderUserId; this.RecieverUserId = recieverUserId; this.GroupId = 0; } public UserMessageMapping(int senderUserId, int recieverUserId, Date messageSentTimestamp, Date messageRecievedTimestamp, Boolean messageReadByReciever, Boolean isDirectMessage, int groupId, Boolean isDeleted) { super(); SenderUserId = senderUserId; RecieverUserId = recieverUserId; this.messageSentTimestamp = messageSentTimestamp; this.messageRecievedTimestamp = messageRecievedTimestamp; this.messageReadByReciever = messageReadByReciever; this.isDirectMessage = isDirectMessage; GroupId = groupId; this.isDeleted = isDeleted; } public int getSenderUserId() { return SenderUserId; } public void setSenderUserId(int senderUserId) { SenderUserId = senderUserId; } public int getRecieverUserId() { return RecieverUserId; } public void setRecieverUserId(int recieverUserId) { RecieverUserId = recieverUserId; } public Date getMessageSentTimestamp() { return messageSentTimestamp; } public void setMessageSentTimestamp(Date messageSentTimestamp) { this.messageSentTimestamp = messageSentTimestamp; } public Date getMessageRecievedTimestamp() { return messageRecievedTimestamp; } public void setMessageRecievedTimestamp(Date messageRecievedTimestamp) { this.messageRecievedTimestamp = messageRecievedTimestamp; } public Boolean getMessageReadByReciever() { return messageReadByReciever; } public void setMessageReadByReciever(Boolean messageReadByReciever) { this.messageReadByReciever = messageReadByReciever; } public Boolean getIsDirectMessage() { return isDirectMessage; } public void setIsDirectMessage(Boolean isDirectMessage) { this.isDirectMessage = isDirectMessage; } public int getGroupId() { return GroupId; } public void setGroupId(int groupId) { GroupId = groupId; } public Boolean getIsDeleted() { return isDeleted; } public void setIsDeleted(Boolean isDeleted) { this.isDeleted = isDeleted; } public UserMessageMapping() { super(); // TODO Auto-generated constructor stub } }
true
44a969a96f6cc3e3cfc197b15877c90976467f8c
Java
PriyabrataNaskar/WeatherApp
/app/src/main/java/tech/hashincludebrain/weatherapp/PlaceHolderInterface.java
UTF-8
323
2.046875
2
[]
no_license
package tech.hashincludebrain.weatherapp; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Query; /** * Created by Priyabrata Naskar on 17-05-2021. */ public interface PlaceHolderInterface { @GET("api/current") Call<ResponseModel> getWeather(@Query("lat") String lat,@Query("lon") String lon); }
true
8771e37f7f478b14b0374079c64477cd4d032a83
Java
bvans/Java_Algorithm
/eclipse/Java_Algorithem/src/towardOffer/HasSubtree.java
UTF-8
882
3.546875
4
[]
no_license
package towardOffer; public class HasSubtree { public boolean hasSubtree(TreeNode root1, TreeNode root2) { if (root1 == null || root2 == null) return false; while (root1 != null) { boolean result = false; if (root1.val == root2.val) { // 处理 result = equal(root1, root2); } if (result) return true; result = hasSubtree(root1.left, root2); if (result) return true; return hasSubtree(root1.right, root2); } return false; } public boolean equal(TreeNode root1, TreeNode root2) { if (root2 == null) { return true; } if (root1 == null) { return false; } if (root1.val != root2.val) return false; return equal(root1.left, root2.left) && equal(root1.right, root2.right); } } class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } }
true
70528fe07220a245bc372e9128083aa685de2fa8
Java
JacobBonefeld/HandInPizza
/HandIn1/PizzaOrder.java
UTF-8
13,923
3.53125
4
[]
no_license
import java.util.Scanner; public class PizzaOrder { public static void main(String[] args) { showMenu(); /*COMMENTS FROM ROBERT only way ive been able to break it was during topping selection if i choose "three" instead of 3 it exits - dont really break just avoid toppings and when a topping is chosen, it outputs topping 2 - might be confusing if u choose topping 1, choose second topping might be better wording. * */ /* Changes after Robert test - Changed message when topping 2 needs to be chosen - Changed message for exiting topping selection to be less confusing - Added extra comments */ } public static void showMenu(){ String pizza1 = "Margherita: Tomato & cheese"; // Declare all pizzas String pizza2 = "Hawaii: Tomato, cheese, ham & pineapple"; String pizza3 = "Italiano: Tomato, cheese & pepperoni"; String pizza4 = "Marinara: Tomato, garlic & basil"; String pizza5 = "Carbonara: Tomato, cheese, eggs & bacon"; String pizza6 = "Americano: Tomato, cheese, sausage & french fries"; String pizza7 = "Tonno: Tomato, cheese, tuna & onions"; String pizza8 = "Pugliese: Tomato, cheese, oregano & onions"; String pizza9 = "Crudo: Tomato, cheese & Parma ham"; String pizza10 = "Tedesca: Tomato, cheese & Vienna sausage"; int pizza1Price = 60; // Declare all pizza prices int pizza2Price = 75; int pizza3Price = 70; int pizza4Price = 65; int pizza5Price = 70; int pizza6Price = 70; int pizza7Price = 75; int pizza8Price = 65; int pizza9Price = 70; int pizza10Price = 70; System.out.printf("--------------------------- PIZZA MENU ---------------------------\n"); // Prints the menu System.out.printf("------------------------------------------------------------------\n"); System.out.printf("1. %-50s Price DKK %d\n",pizza1,pizza1Price); System.out.printf("2. %-50s Price DKK %d\n",pizza2,pizza2Price); System.out.printf("3. %-50s Price DKK %d\n",pizza3,pizza3Price); System.out.printf("4. %-50s Price DKK %d\n",pizza4,pizza4Price); System.out.printf("5. %-50s Price DKK %d\n",pizza5,pizza5Price); System.out.printf("6. %-50s Price DKK %d\n",pizza6,pizza6Price); System.out.printf("7. %-50s Price DKK %d\n",pizza7,pizza7Price); System.out.printf("8. %-50s Price DKK %d\n",pizza8,pizza8Price); System.out.printf("9. %-50s Price DKK %d\n",pizza9,pizza9Price); System.out.printf("10. %-49s Price DKK %d\n",pizza10,pizza10Price); System.out.printf("------------------------------------------------------------------\n"); System.out.printf("------------------------------------------------------------------\n\n"); Scanner in = new Scanner(System.in); int pizzaNumber = 0; // Variable to store the number of the chosen pizza System.out.println("Enter the number of the pizza you want to order: "); while(pizzaNumber<1 || pizzaNumber>10){ // Input validation - Chosen number must be within scope if(in.hasNextInt()){ // Input must be an integer pizzaNumber = in.nextInt(); if(pizzaNumber<1 || pizzaNumber>10){ System.out.println("That pizza does not exist. Please try again: "); } } else{ System.out.println("That pizza does not exist. Please try again: "); in.next(); // Reset input stream to allow new input } } String chosenPizza = ""; // Stores name of chosen pizza to use in receipt int pizzaPrice = 0; // Stores price of chosen pizza to use in receipt if(pizzaNumber == 1){ // Assigning values to the chosenPizza and pizzaPrice chosenPizza = pizza1; pizzaPrice = pizza1Price; } else if(pizzaNumber == 2){ chosenPizza = pizza2; pizzaPrice = pizza2Price; } else if(pizzaNumber == 3){ chosenPizza = pizza3; pizzaPrice = pizza3Price; } else if(pizzaNumber == 4){ chosenPizza = pizza4; pizzaPrice = pizza4Price; } else if(pizzaNumber == 5){ chosenPizza = pizza5; pizzaPrice = pizza5Price; } else if(pizzaNumber == 6){ chosenPizza = pizza6; pizzaPrice = pizza6Price; } else if(pizzaNumber == 7){ chosenPizza = pizza7; pizzaPrice = pizza7Price; } else if(pizzaNumber == 8){ chosenPizza = pizza8; pizzaPrice = pizza8Price; } else if(pizzaNumber == 9){ chosenPizza = pizza9; pizzaPrice = pizza9Price; } else if(pizzaNumber == 10){ chosenPizza = pizza10; pizzaPrice = pizza10Price; } choosePizzaSize(chosenPizza, pizzaPrice); // Move on to pizzaSize method. Passing two variables to be used in receipt } public static void addToppingsPrintReciept(String chosenPizza, double newPrice, String chosenSize){ String topping1 = "Peperoni"; // Declares available toppings String topping2 = "Mozarella"; String topping3 = "Mushroom"; String topping4 = "Sausage"; String topping5 = "Bacon"; String topping6 = "Onion"; String topping7 = "Ranch Dressing"; System.out.println("-------------------- Add Toppings --------------------"); // Prints topping menu System.out.println("-------- Maximum 2 ------------------ 5 DKK each------"); System.out.println("1. "+topping1); System.out.println("2. "+topping2); System.out.println("3. "+topping3); System.out.println("4. "+topping4); System.out.println("5. "+topping5); System.out.println("6. "+topping6); System.out.println("7. "+topping7); System.out.println("------------------------------------------------------\n"); System.out.println("Enter the number of the topping you want to add: "); System.out.println("Enter a non number to order'"); int toppingPrice = 0; // Total price of toppings int toppingCount = 0; // Number of toppings. loop must break if 2 toppings is chosen int chosenToppingNum = 0; // Temporarily store number of chosen topping String chosenTopping1 = ""; // Stores name of toppings, so it can be passed to receipt String chosenTopping2 = ""; Scanner in = new Scanner(System.in); while(toppingCount<2){ while(chosenToppingNum>7 || chosenToppingNum<1){ //Loop continues as long as chosen number is not within scope if(in.hasNextInt()){ //Checks that input is integer chosenToppingNum = in.nextInt(); if(chosenToppingNum == 1){ chosenTopping1 = topping1; //Store topping name to use in receipt toppingCount++; //Increment number of toppings toppingPrice += 5; //Increment total topping price } else if(chosenToppingNum == 2){ chosenTopping1 = topping2; toppingCount++; toppingPrice += 5; } else if(chosenToppingNum == 3){ chosenTopping1 = topping2; toppingCount++; toppingPrice += 5; } else if(chosenToppingNum == 4){ chosenTopping1 = topping4; toppingCount++; toppingPrice += 5; } else if(chosenToppingNum == 5){ chosenTopping1 = topping5; toppingCount++; toppingPrice += 5; } else if(chosenToppingNum == 6){ chosenTopping1 = topping6; toppingCount++; toppingPrice += 5; } else if(chosenToppingNum == 7){ chosenTopping1 = topping7; toppingCount++; toppingPrice += 5; } else System.out.println("That topping does not exist. Please try again"); } else{ toppingCount = 2; break; } } chosenToppingNum = 0; System.out.println("Now choose topping 2"); while(chosenToppingNum>7 || chosenToppingNum<1){ if(in.hasNextInt()){ chosenToppingNum = in.nextInt(); if(chosenToppingNum == 1){ chosenTopping2 = topping1; toppingCount++; toppingPrice += 5; } else if(chosenToppingNum == 2){ chosenTopping2 = topping2; toppingCount++; toppingPrice += 5; } else if(chosenToppingNum == 3){ chosenTopping2 = topping2; toppingCount++; toppingPrice += 5; } else if(chosenToppingNum == 4){ chosenTopping2 = topping4; toppingCount++; toppingPrice += 5; } else if(chosenToppingNum == 5){ chosenTopping2 = topping5; toppingCount++; toppingPrice += 5; } else if(chosenToppingNum == 6){ chosenTopping2 = topping6; toppingCount++; toppingPrice += 5; } else if(chosenToppingNum == 7){ chosenTopping2 = topping7; toppingCount++; toppingPrice += 5; } else System.out.println("That topping does not exist. Please try again"); } else{ toppingCount = 2; break; } } } double totalPrice = toppingPrice + newPrice; System.out.println("-----------------------------Receipt-----------------------------"); // Print out receipt System.out.println("-----------------------------------------------------------------"); System.out.printf("%s\n",chosenPizza); System.out.println("Size:"); System.out.println(chosenSize); System.out.printf("%-55s %.2f DKK\n\n","",newPrice); System.out.println("Topping(s):"); System.out.printf("%s\n",chosenTopping1); System.out.printf("%s\n",chosenTopping2); System.out.printf("%-55s %.2f DKK\n\n","",(double)toppingPrice); System.out.printf("Total price: %48.2f DKK\n",totalPrice); System.out.println("-----------------------------------------------------------------"); System.out.println("-----------------------------------------------------------------"); } public static void choosePizzaSize(String chosenPizza,int pizzaPrice){ int price = pizzaPrice; // Used to calculate the price depending on the size String size1 ="Child", size2 ="Standard", size3 = "Family"; System.out.println("-----------------------------------------"); // Print size menu System.out.println("---------------Choose size---------------"); System.out.printf("1. %-20s Price DKK %.2f\n",size1,price*0.75); System.out.printf("2. %-20s Price DKK %.2f\n",size2,(double)price); System.out.printf("3. %-20s Price DKK %.2f\n",size3,price*1.5); System.out.println("-----------------------------------------"); System.out.println("-----------------------------------------\n"); System.out.println("Enter the number of the size you would like: "); Scanner in = new Scanner(System.in); int size = 0; while(size<1 || size>3){ // Input validation if(in.hasNextInt()){ size = in.nextInt(); if(size<1 || size>3){ System.out.println("That size does not exist. Please try again: "); } } else{ System.out.println("That size does not exist. Please try again: "); in.next(); // Reset input stream to allow new input } } String chosenSize = ""; double newPrice = 0; if(size == 1){ chosenSize = size1; newPrice = price*0.75; } else if(size == 2){ chosenSize = size2; newPrice = price; } else if(size == 3){ chosenSize = size3; newPrice = price*1.5; } addToppingsPrintReciept(chosenPizza,newPrice,chosenSize); // Go to next method and pass variables to be used in receipt } }
true
f222aa1bdd971e483bed9771868a582260042fce
Java
shanshanhub/testproject
/coverage/src/test/java/code/OrderTest.java
UTF-8
391
2.078125
2
[]
no_license
package code; import org.junit.Test; import static org.junit.Assert.*; /** * @author WanChuanLai * @create 4/21/16. */ public class OrderTest { @Test public void testAdd() throws Exception { Order order=new Order(); order.add(1); } @Test public void testDelete() throws Exception { Order order=new Order(); order.delete(2); } }
true
716b196c7a276b5d148c102fc8d8bfc8fedd0af5
Java
2345free/itzone123-micro-weather
/micro-weather-forecast-webapp/src/main/java/com/itzone123/weather/forecast/webapp/vo/City.java
UTF-8
220
1.554688
2
[]
no_license
package com.itzone123.weather.forecast.webapp.vo; import lombok.Data; @Data public class City { private String cityId; private String cityName; private String cityNameEn; private String province; }
true
93d62ea1cb80d467790253722db695050d750cc2
Java
MilSay/ORQUESTA1
/app/src/main/java/com/android/app/orquesta/model/Provincia.java
UTF-8
636
2.25
2
[]
no_license
package com.android.app.orquesta.model; public class Provincia { public String cod_prov; public String provincia; public Provincia() { } public Provincia(String cod_prov, String provincia) { this.cod_prov = cod_prov; this.provincia = provincia; } public String getCod_prov() { return cod_prov; } public void setCod_prov(String cod_prov) { this.cod_prov = cod_prov; } public String getProvincia() { return provincia; } public void setProvincia(String provincia) { this.provincia = provincia; } }
true
31e558c22868486f030838f7bee731f2585643a0
Java
zhengweitao/My_Java
/MyBasicJava/src/main/java/com/my/basic/java/nio/SocketClient.java
UTF-8
1,971
3.046875
3
[]
no_license
package com.my.basic.java.nio; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.nio.charset.Charset; import java.util.Iterator; public class SocketClient { private Selector selector; public SocketClient(){ } public void init() throws Exception{ SocketChannel server = SocketChannel.open(); server.configureBlocking(false); server.connect(new InetSocketAddress("127.0.0.1",2222)); selector = Selector.open(); server.register(selector, SelectionKey.OP_CONNECT); } public void listen() throws Exception{ while(true){ selector.select(); Iterator<SelectionKey> selectedKeys = selector.selectedKeys().iterator(); while(selectedKeys.hasNext()){ SelectionKey key = selectedKeys.next(); if(key.isConnectable()){ SocketChannel channel = (SocketChannel)key.channel(); //需要调用channel.finishConnect()才能完成连接 if (channel.isConnectionPending()) { channel.finishConnect(); } channel.configureBlocking(false); channel.write(ByteBuffer.wrap("hello! I'am the new one!".getBytes("UTF-8"))); channel.register(selector, SelectionKey.OP_READ); } if(key.isReadable()){ SocketChannel channel = (SocketChannel)key.channel(); ByteBuffer bb = ByteBuffer.allocate(1024); channel.read(bb); bb.flip(); System.out.println("["+System.currentTimeMillis()+"]server: "+Charset.forName("UTF-8").decode(bb)); } selectedKeys.remove(); } } } public static void main(String[] args) { SocketClient sc = new SocketClient(); try { sc.init(); sc.listen(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
true
317f7c824e167575afba3062a89e8e955ba33d15
Java
vaishali-radhakrishnan/sourceninja
/src/main/java/com/kannan/sourcewalker/SourceWalkerTransformer.java
UTF-8
3,036
2.375
2
[]
no_license
package com.kannan.sourcewalker; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.security.ProtectionDomain; /*import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClients;*/ import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.util.CheckClassAdapter; //import org.slf4j.Logger; //import org.slf4j.LoggerFactory; public class SourceWalkerTransformer implements ClassFileTransformer { //Logger logger = LoggerFactory.getLogger(SourceWalkerTransformer.class); public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { try { //System.out.println(" inside transformer " + className); // logger.error( "inside transformer " + className); ClassReader cr = new ClassReader(classfileBuffer); ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); CheckClassAdapter cxa = new CheckClassAdapter(cw); ClassVisitor cv = new ClassInfoGatherer(cxa); cr.accept(cv, ClassReader.EXPAND_FRAMES); byte[] b = cw.toByteArray(); // System.out.println(" inside transformer - returning" + b.length); // logger.error( "inside transformer - returning" + b.length); // print(); return b; } catch (Throwable t) { t.printStackTrace(); StringWriter sw = new StringWriter(); t.printStackTrace(new PrintWriter(sw)); String exceptionAsString = sw.toString(); System.out.println( " throwable found " + exceptionAsString) ; }/*catch (Exception e) { System.out.println( " class might not be found " + e.getMessage()) ; try { throw new ClassNotFoundException(className, e); } catch (ClassNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }*/ return null; } /*private void print(){ try { //System.out.println(" schema str " + schemaInfo.getSchema()); //make a call to metadata service HttpClient httpclient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet("http://localhost:8091/MetaDataService/hello"); // StringEntity se = new StringEntity(schema); // httppost.setEntity(); //Execute and get the response. HttpResponse response = httpclient.execute(httpGet); HttpEntity respEntity = response.getEntity(); } catch (Exception e) { // TODO Auto-generated catch block System.err.println(" error in sw print"); } }*/ }
true
4e301d2d591506f763bfc549768cad1dbf1cb70b
Java
oonis/SAM
/src/SAM/math/QEComputation.java
UTF-8
3,812
2.46875
2
[]
no_license
package SAM.math; import SAM.structures.ImageInformation; import SAM.structures.Measurement; import SAM.structures.Threshold; import SAM.structures.selections.Selection; import SAM.structures.selections.Selections; import ij.ImagePlus; import ij.process.ImageProcessor; import java.util.ArrayList; import java.util.List; /** * Computation for getting qE. */ public class QEComputation extends GenericComputation{ public QEComputation(Selections selections, Measurement... measurements) { super("qE", selections, measurements); } public QEComputation(Selections selections, List<Measurement> measurements) { super("qE", selections, measurements.toArray(new Measurement[measurements.size()])); } @Override public void compute() { List<ImageInformation> fmmImages = mMeasurements[0].getImages(); List<ImageInformation> fmpImages = mMeasurements[1].getImages(); mTimeVector = new long[fmpImages.size()]; if(fmmImages.size() != fmpImages.size()) { System.out.println("Fs and fmp image sizes do not match up"); return; } // Should this even be done? Maybe this should have been done already? Threshold thresholds = mMeasurements[0].getDayExperiment().getSensorExperiment().getThresholds(); double fmmLow = thresholds.getThresholdLow(mMeasurements[0].getName()); double fmmHigh = thresholds.getThresholdHigh(mMeasurements[0].getName()); double fmpLow = thresholds.getThresholdLow(mMeasurements[1].getName()); double fmpHigh = thresholds.getThresholdHigh(mMeasurements[1].getName()); for(int i = 0; i < fmpImages.size(); i++) { ImagePlus fmmImage = fmmImages.get(i).getImage(false,fmmLow,fmmHigh); ImagePlus fmpImage = fmpImages.get(i).getImage(false,fmpLow,fmpHigh); ImageProcessor fmmProcess = mMeasurements[0].generateImage(fmmImage); ImageProcessor fmpProcess = mMeasurements[1].generateImage(fmpImage); fmmImage = new ImagePlus("fmm",fmmProcess); fmpImage = new ImagePlus("fmp",fmpProcess); long time = Math.max(fmpImages.get(i).getTime(), fmmImages.get(i).getTime()); mTimeVector[i] = time; List<Selection> selections = new ArrayList<>(mSelections.getSelections(time)); for (int j = 0; j < selections.size(); j++) { Selection selection = selections.get(j); String name = selection.getName(); ImagePlus fmmPlant = selection.crop(fmmImage, null); ImagePlus fmpPlant = selection.crop(fmpImage, null); double fmmAverage = average(fmmPlant.getProcessor().getFloatArray()); double fmpAverage = average(fmpPlant.getProcessor().getFloatArray()); double qE = (fmpAverage-fmmAverage)/fmmAverage; if (i == 0) { mPlants[j] = new Plant(name, time, qE); } else { if (!name.equals(mPlants[j].getName())) { System.out.println(name + " is missing a value for " + mName + " at " + time); mPlants[j].addValue(Float.NaN); for (int x = j; x < selections.size(); x++) { if (name.equals(mPlants[x].getName())) { mPlants[x].addValue(qE); } } } else { mPlants[j].addValue(qE); } } } } System.out.println("Done qE"); } }
true
9f67f43b97b91c1b546a9837beac62bb6b6ddcc5
Java
CodeQualityTinna/PublicProject
/miaosha-master/src/main/java/com/miaoshaproject/error/BusinessException.java
UTF-8
1,019
2.796875
3
[]
no_license
package com.miaoshaproject.error; /** * @program: miaosha * @description: 包装器业务异常类实现 * @author: 程金鹏 * @create: 2019-07-28 09:56 */ public class BusinessException extends Exception implements CommonError { private CommonError commonError; //直接接收EmBusinessError的传参用于构造业务异常 public BusinessException(CommonError commonerror) { super(); this.commonError = commonerror; } //接收自定义errMsg的方式构造业务异常 public BusinessException(CommonError commonError,String errmeg){ super(); this.commonError=commonError; this.commonError.setCommonErrorMeg(errmeg); } @Override public Integer getErrorCode() { return this.commonError.getErrorCode(); } @Override public String getErrorMeg() { return this.commonError.getErrorMeg(); } @Override public CommonError setCommonErrorMeg(String errorMeg) { return commonError; } }
true
39238439137116486539905da81bb6b941f566b8
Java
FlyingDuck/algorithm-rookie
/src/main/java/com/dongshujin/demo/algorithm/offer/Question29.java
UTF-8
4,546
4.15625
4
[]
no_license
package com.dongshujin.demo.algorithm.offer; import java.util.Random; /** * Created by dongsj on 16/12/3. * */ public class Question29 { /* 数组中出现次数超过一半的数字 Q:数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组 {1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。 A:1,借用快速排序中的 Partition() 函数;2,根据数组特点找出该数 */ // 用于随机选取基准值 private Random random = new Random(); public int partition(int[] array, int start, int end) { // 选取基准值 int index = random.nextInt(end-start) + start; // 将基准值置于数组末尾,以便交换其他值 swap(array, index, end); // 定义small指针,标示数组中小于基准值的位置,初始化在其实位置左侧 int small = start-1; // 遍历数组,当遇到小于基准值的数时,将small指针右移,并且将这个数交换到small指向的位置 for (int pos=start; pos<end; pos++) { if (array[pos] < array[end]) { small++; swap(array, pos, small); } } // 最后将基准值归位 small++; swap(array, end, small); // 返回基准值所在位置 return small; } private void swap(int[] array, int pos1, int pos2) { int tmp = array[pos1]; array[pos1] = array[pos2]; array[pos2] = tmp; } public int moreThanHalfNum(int[] array) { if (null == array) { throw new IllegalArgumentException(); } int middle = array.length >> 1; // 寻找第一个基准值位置 int start = 0; int end = array.length-1; int pos = partition(array, start, end); while (pos != middle) { if (pos < middle) { start = pos+1; } else { end = pos-1; } if (start >= pos) break; pos = partition(array, start, end); } int result = array[middle]; // 检查是否符合超过一半的约束 if (!checkNum(array, result)) { return 0; } return result; } /** * 这种方法,充分利用了数组的特点。 * 数组中有一个数字超过一半,说明它出现的次数比其他所有的数字出现的次数和还要多。因此我们可以考虑在遍历数组的时候保存两个值:一个是数组中的数字,一个是次数。 * 当我们遍历到下一个数字的时候,如果下一个数字和我们之前保存的数字相同,则次数加1;如果下一个数字和我们之前保存的数字不同,则次数减1。如果次数为零,我们需要保存下一个数字,并把次数设为1。 * 由于我们要找的数字出现的次数比其他所有的数字出现的次数之和还要多,那么要找的数字肯定是最后一次把次数设为1时对应的数字。 */ public int moreThanHalfNum2(int[] array) { if (null == array) { throw new IllegalArgumentException(); } int result = array[0]; int times = 1; for (int i=1; i<array.length; i++) { if (result == array[i]) { times++; } else { if (times == 0) { result = array[i]; times = 1; } else { times--; } } } if (!checkNum(array, result)) { return 0; } return result; } private boolean checkNum(int[] array, int result) { int half = array.length >> 1; int times = 0; for (int i=0; i<array.length; i++) { if (array[i] == result) { times++; if (times > half) { return true; } } } return false; } public static void main(String[] args) { Question29 question29 = new Question29(); int[] array = new int[]{1,2,3,2,2,2,5,4,2}; int result = question29.moreThanHalfNum(array); System.out.println("result: " + result); result = question29.moreThanHalfNum2(array); System.out.println("result: " + result); } }
true
b873599a650a8fd52c9c36ac16f5dc609343d06e
Java
nikita167/HelpingHands
/app/src/main/java/com/helpinghands/fragment/SetShakeLevelFragment.java
UTF-8
10,599
1.984375
2
[]
no_license
package com.helpinghands.fragment; import android.content.Context; import android.content.Intent; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.net.Uri; import android.os.Bundle; import android.os.Vibrator; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.helpinghands.R; import com.helpinghands.activity.HomeActivity; import com.helpinghands.constants.AppConstant; import com.helpinghands.service.ShakeListenerService; import com.helpinghands.utils.Logger; import com.helpinghands.utils.SharedPrefUtils; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link SetShakeLevelFragment.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link SetShakeLevelFragment#newInstance} factory method to * create an instance of this fragment. */ public class SetShakeLevelFragment extends Fragment implements SensorEventListener { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private OnFragmentInteractionListener mListener; private HomeActivity homeActivity; private SensorManager sensorManager; private Sensor senAccelerometer; private long lastUpdate = 0; private float last_x, last_y, last_z; private static final int SHAKE_THRESHOLD = 18; private TextView mAccleration; private Vibrator mVibrator; private Button mRecordingButton, mDoneButton; int lastAccelerationValue=0; int currentAccelerationValue=0; // acceleration value recorded before saving int recordedAccelerationValue = 0; boolean mIsRecording=false; private String recordingStage; private static final String TAG = SetShakeLevelFragment.class.getSimpleName(); public SetShakeLevelFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment SetShakeLevelFragment. */ // TODO: Rename and change types and number of parameters public static SetShakeLevelFragment newInstance(String param1, String param2) { SetShakeLevelFragment fragment = new SetShakeLevelFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } sensorManager = (SensorManager)homeActivity.getSystemService(Context.SENSOR_SERVICE); senAccelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); mIsRecording = false; currentAccelerationValue= 0; lastAccelerationValue=0; //sensorManager.registerListener(this, senAccelerometer , SensorManager.SENSOR_DELAY_NORMAL); unregisterShakeListener(); mVibrator = (Vibrator)homeActivity.getSystemService(Context.VIBRATOR_SERVICE); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view= inflater.inflate(R.layout.fragment_set_shake_level, container, false); mAccleration=(TextView)view.findViewById(R.id.text_acceleration); mRecordingButton = (Button)view.findViewById(R.id.btn_record); mDoneButton = (Button)view.findViewById(R.id.btn_save_shake_level); mRecordingButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String recordingStatus = (String) mRecordingButton.getText(); if(recordingStatus.equalsIgnoreCase("Start Recording")){ mIsRecording = true; mRecordingButton.setText("Recording"); currentAccelerationValue= 0; lastAccelerationValue=0; recordedAccelerationValue=0; registerShakeListener(); } else if(recordingStatus.equalsIgnoreCase("Recording")){ // Do nothing // User pressed button second time without setting acceleration } else if(recordingStatus.equalsIgnoreCase("Retry")){ mIsRecording = true; mRecordingButton.setText("Recording"); currentAccelerationValue= 0; lastAccelerationValue=0; recordedAccelerationValue = 0; registerShakeListener(); } } }); mDoneButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(recordedAccelerationValue == 0){ Toast.makeText(homeActivity,"Please set shake threshold value first!",Toast.LENGTH_SHORT).show(); } else{ new SharedPrefUtils().saveValue(homeActivity,AppConstant.USER_SHAKE_THRESHOLD,""+recordedAccelerationValue); // start shake listener service in background Intent shakeIntent = new Intent(homeActivity.getApplicationContext(), ShakeListenerService.class); homeActivity.startService(shakeIntent); homeActivity.pushFragment(new DoneFragment()); } } }); return view; } private void setRecordingButtonText() { if(mIsRecording){ mRecordingButton.setText("Recording"); registerShakeListener(); } else{ mRecordingButton.setText("Start Recording"); } } private void registerShakeListener() { if(sensorManager!=null){ sensorManager.registerListener(this, senAccelerometer, SensorManager.SENSOR_DELAY_NORMAL); } } private void unregisterShakeListener() { if(sensorManager!=null){ sensorManager.unregisterListener(this,senAccelerometer); } } @Override public void onAttach(Context context) { super.onAttach(context); homeActivity=(HomeActivity)context; if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } @Override public void onPause() { super.onPause(); unregisterShakeListener(); mIsRecording = false; } @Override public void onResume() { super.onResume(); setRecordingButtonText(); /* if(sensorManager!=null){ sensorManager.registerListener(this, senAccelerometer, SensorManager.SENSOR_DELAY_FASTEST); }*/ } @Override public void onSensorChanged(SensorEvent event) { Sensor sensor=event.sensor; if(sensor.getType()==Sensor.TYPE_ACCELEROMETER){ float x = event.values[0]; float y = 0;//event.values[1]; float z = 0;//event.values[2]; if(mIsRecording){ long curTime = System.currentTimeMillis(); long diffTime = (curTime - lastUpdate); //lastUpdate = curTime; float acceleration = (float)Math.abs(Math.sqrt(x*x+y*y+z*z)); currentAccelerationValue=(int)acceleration; /*if(curTime%2000==0){ Logger.d(TAG,"C acc : "+currentAccelerationValue+" L acc: "+lastAccelerationValue+" curTime: "+curTime); }*/ if(currentAccelerationValue<lastAccelerationValue && lastAccelerationValue>SHAKE_THRESHOLD ){ Logger.d(TAG,"C acc : "+currentAccelerationValue+" L acc: "+lastAccelerationValue); lastUpdate = System.currentTimeMillis(); vibrateDevice(); recordedAccelerationValue = lastAccelerationValue; updateView(lastAccelerationValue); } else{ lastAccelerationValue=currentAccelerationValue; } } } } private void updateView(int accelerationValue) { if(mAccleration!=null && mRecordingButton!=null){ mAccleration.setText("Acceleration : "+accelerationValue+" m/s2"); mRecordingButton.setText("Retry"); } } private void vibrateDevice() { if(mVibrator!=null){ mIsRecording=false; mVibrator.vibrate(1500); } unregisterShakeListener(); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p/> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name void onFragmentInteraction(Uri uri); } }
true
9a538901ed10e64f4ef4488c0adbdf0677aaaa4b
Java
wangliyong97/CMS
/src/main/java/com/cms/service/impl/BlackIpServiceImpl.java
UTF-8
2,010
1.96875
2
[]
no_license
package com.cms.service.impl; import com.cms.dao.BlackIpMapper; import com.cms.pojo.BlackIp; import com.cms.service.BlackIpService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; /** * Created by wangliyong on 2019/1/12. */ @Service public class BlackIpServiceImpl implements BlackIpService{ @Autowired private BlackIpMapper blackIpMapper; @Override public int deleteByPrimaryKey(Integer id) { // TODO Auto-generated method stub return blackIpMapper.deleteByPrimaryKey(id); } @Override public int insert(BlackIp record) { // TODO Auto-generated method stub return blackIpMapper.insert(record); } @Override public int insertSelective(BlackIp record) { // TODO Auto-generated method stub return blackIpMapper.insertSelective(record); } @Override public BlackIp selectByPrimaryKey(Integer id) { // TODO Auto-generated method stub return blackIpMapper.selectByPrimaryKey(id); } @Override public int updateByPrimaryKeySelective(BlackIp record) { // TODO Auto-generated method stub return blackIpMapper.updateByPrimaryKeySelective(record); } @Override public int updateByPrimaryKey(BlackIp record) { // TODO Auto-generated method stub return blackIpMapper.updateByPrimaryKey(record); } @Override public BlackIp selectBlackIpByIp(String ip) { // TODO Auto-generated method stub return blackIpMapper.selectBlackIpByIp(ip); } @Override public Long selectAllBlackIpCount() { // TODO Auto-generated method stub return blackIpMapper.selectAllBlackIpCount(); } @Override public List<BlackIp> selectLikeBlackIpListByPage(Map<String, Object> map) { // TODO Auto-generated method stub return blackIpMapper.selectLikeBlackIpListByPage(map); } }
true
d18e9bac78e0fd5307134b387a395a056d12dcef
Java
karangoidani/ireland
/app/src/main/java/com/collegedekho/NotificationFragment.java
UTF-8
1,309
2
2
[]
no_license
package com.collegedekho; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import com.collegedekho.adapter.CollegeListAdapter; /** * A simple {@link Fragment} subclass. */ public class NotificationFragment extends Fragment { View view; ListView mListView; Context mContext; private CollegeListAdapter adapter; public NotificationFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment mContext = container.getContext(); ((AppCompatActivity) getActivity()).getSupportActionBar().show(); view = inflater.inflate(R.layout.fragment_notification, container, false); init(); return view; } private void init() { mListView = view.findViewById(R.id.collegeList); adapter = new CollegeListAdapter(mContext); mListView.setAdapter(adapter); } }
true
aa77ac6264f52927d46ebf62bad72b52148ca44b
Java
zt6220493/kangaroo
/kangaroo-rong360/src/main/java/io/github/pactstart/rong360/push/bean/RepaymentBean.java
UTF-8
483
1.59375
2
[]
no_license
package io.github.pactstart.rong360.push.bean; import lombok.Data; import lombok.NoArgsConstructor; @NoArgsConstructor @Data public class RepaymentBean { /** * order_no : 245132241561415 * period_nos : 1 * repay_type : 8 * device_type : ios * repay_return_url : xxxxxxxxxxxxxxxxxxx */ private String order_no; private String period_nos; private int repay_type; private String device_type; private String repay_return_url; }
true
7861f86cbf3b415b696d759409ab8af4fc077826
Java
JaeyeolRyu/coTe
/src/coTe/Pro/Level3/ProFarthestNode2.java
UTF-8
2,042
2.953125
3
[]
no_license
package coTe.Pro.Level3; import java.util.Arrays; import java.util.PriorityQueue; public class ProFarthestNode2 { static int INF = 50001; static int[][] nodeArr; static int[] dis; static boolean[] visit; public static void main(String[] args) { int n = 6; int[][] edge = { { 3, 6 }, { 4, 3 }, { 3, 2 }, { 1, 3 }, { 1, 2 }, { 2, 4 }, { 5, 2 } }; int ans = solution(n, edge); System.out.println(ans); } public static int solution(int n, int[][] edge) { int answer = 0; dis = new int[n + 1]; visit = new boolean[n + 1]; nodeArr = new int[n + 1][n + 1]; for (int i = 1; i < n + 1; i++) { for (int j = 1; j < n + 1; j++) { nodeArr[i][j] = INF; } nodeArr[i][i] = 0; } for (int i = 0; i < edge.length; i++) { nodeArr[edge[i][0]][edge[i][1]] = 1; nodeArr[edge[i][1]][edge[i][0]] = 1; } for (int i = 1; i < n + 1; i++) { dis[i] = INF; } dis[1] = 0; answer = search(1, n); return answer; } public static int search(int start, int n) { PriorityQueue<Node> pq = new PriorityQueue<>(); pq.add(new Node(1, dis[start])); while(!pq.isEmpty()) { Node node = pq.poll(); int dist = node.dis; int idx = node.idx; if(dist > dis[idx]) { continue; } for(int i = 1; i < n+1; i++) { if(nodeArr[idx][i] != 0 && dis[i] > dis[idx] + nodeArr[idx][i]) { dis[i] = dis[idx] + nodeArr[idx][i]; pq.add(new Node(i, dis[i])); } } } Arrays.sort(dis); int max = 0; int cnt = 0; int maxIdx = 0; for (int i = dis.length - 1; i >= 0; i--) { if (dis[i] != INF) { maxIdx = i; max = dis[i]; break; } } for (int i = maxIdx; i >= 0; i--) { if (max == dis[i]) { cnt++; } else { break; } } return cnt; } static class Node implements Comparable<Node> { int idx; int dis; Node(int idx, int dis) { this.idx = idx; this.dis = dis; } @Override public int compareTo(Node o) { return this.dis - o.dis; } } }
true
448ab87180082b591c7744f40ef6ea6185c2cbea
Java
MehdiSpring/Spring-boot-Jokes-App
/src/main/java/com/springguru/service/JokesServiceFromPersonalList.java
UTF-8
920
2.6875
3
[]
no_license
package com.springguru.service; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Service; @Profile("PL") @Service public class JokesServiceFromPersonalList implements JokesService { private List<String> jokes; private Random rand = new Random(); public JokesServiceFromPersonalList() { jokes = new ArrayList<String>(); jokes.add("Oumayma Lhbila msetya"); jokes.add("wa siri ya zay7a ya lfa3la"); jokes.add("soooofiiii mahdiyaaaa wach ntiya labas"); jokes.add("ana kanblikk ba3daya anaya"); jokes.add("wa siri ya l7em9a siri fin tla3bi"); jokes.add("ya dayraa ya lfa3laaa"); jokes.add("ntiya hiya toba ya begla "); } @Override public String getSomejoke() { return jokes.get(rand.nextInt(jokes.size())); } }
true
95e16c255c91a97d31864c98d55fa353abab8edb
Java
royfu77/gsp_demo
/java/src/demos/dlineage/dataflow/model/CursorResultSet.java
UTF-8
705
1.96875
2
[]
no_license
package demos.dlineage.dataflow.model; import gudusoft.gsqlparser.nodes.TResultColumnList; import gudusoft.gsqlparser.stmt.TCursorDeclStmt; import gudusoft.gsqlparser.stmt.TSelectSqlStatement; public class CursorResultSet extends ResultSet { private TCursorDeclStmt cursorStmt; public CursorResultSet( TCursorDeclStmt select ) { super( select, false ); this.cursorStmt = select; } public TResultColumnList getResultColumnObject( ) { return cursorStmt.getSubquery( ).getResultColumnList( ); } public TSelectSqlStatement getSelectStmt( ) { return cursorStmt.getSubquery( ); } public TCursorDeclStmt getCursorStmt( ) { return cursorStmt; } }
true
735f2ee3089453fcec9e16766a677a33d9e2f6b5
Java
sorath92/chutes-ladders
/chute-ladders/src/com/sovan/util/GameBuilder.java
UTF-8
1,646
3.40625
3
[]
no_license
package com.sovan.util; import java.util.ArrayList; import java.util.List; import com.sovan.entities.Board; import com.sovan.entities.Game; import com.sovan.entities.Player; /** * This class is the Game builder class. It instantiates a Game . * * This also validates the game rules . For example : Our Chutes and Ladders * game should have between 2 to 4 players. * * Once validation is done it instantiates the sample Game. This Game is played * in the main class to generate result for the players. * * @author Sovan Kishan Rath * * */ public class GameBuilder { public static Game buildStandardChuteLaddersGame(String[] players) { if (players == null || players.length < 2 || players.length > 4) { System.out.println("...... NUMBER OF PLAYERS SHOULD BE BETWEEN 2 TO 4......"); return null; } if (validatePlayers(players) == false) { System.out.println("...... Player Names should be Alphabet......"); return null; } List<Player> playerList = new ArrayList<Player>(); for (String name : players) { Player p = new Player(); p.setName(name); p.setPosition(0); playerList.add(p); } String gameName = "STANDARD CHUTE AND LADDERS"; Board b = BoardBuilder.getClassicChuteLaddersBoard(); Game chuteLaddersGame = new Game(gameName, b, playerList); return chuteLaddersGame; } public static boolean validatePlayers(String[] playerNames) { for (String p : playerNames) { p = p.trim(); boolean allLetters = p.chars().allMatch(Character::isLetter) && !p.equalsIgnoreCase("") && p != null; if (allLetters == false) { return false; } } return true; } }
true
ff240f3f0d3fc5acc4807b3d459a31363208086a
Java
elvnmage/MyFirstProject
/FirstJavaProject/src/MyClass3.java
UTF-8
920
2.875
3
[]
no_license
public class MyClass3 { public static void main (String args[]) { String name = "Emre"; int age = 33; double score = 15.9; char group = 'Z'; boolean online = true; int a = 10; int b = 5; int x = 6+3; int y = 50*5; int z = 500/5; int f = 100%1; int var = 55; int sum1 = 10+10; int sum2 = 20-10; int sum3 = sum1-sum2; int sum10 = 100*2; int sum11 = sum10 - 50; int sum12 = sum1+sum2; int sum13 = sum11+sum12; int value = 100; int res = value % 10; //boldukten sonra artan sayi int test = 5; ++test;// ++ makes bir sayi fazlasi int falan = 12; int filan = ++falan*2 ; int p = 50; int num1 = 4; int num2 = 8; num2 += num1; // num2 = num2 + num1; // num2 is 12 and num1 is 4 System.out.println (num2); } }
true
b27285014d05defe54fe5bbe98439e84e4318976
Java
dendevjv/AjTdd
/src/ajtdd/chess/Board.java
UTF-8
7,697
3.296875
3
[]
no_license
package ajtdd.chess; import java.util.ArrayList; import java.util.Collections; import java.util.List; import ajtdd.chess.pieces.Piece; import ajtdd.chess.pieces.Piece.Type; /** * Represents a chess board. */ public class Board { public static final String NL = System.getProperty("line.separator"); private static final char EMPTY_CELL = '.'; private static final int SIZE = 8; private Piece[][] pieces; private List<Piece> whitePieces; private List<Piece> blackPieces; public Board() { whitePieces = new ArrayList<>(); blackPieces = new ArrayList<>(); pieces = new Piece[SIZE][SIZE]; initialize(); } public void assignStrengthToPieces() { for (int i = 0; i < pieces.length; i++) { for (int j = 0; j < pieces[0].length; j++) { Piece p = pieces[i][j]; if (p != null && p.getType() != Piece.Type.NoPiece) { p.setStrength(getStrengthOfPiece(p, j)); } } } Collections.sort(blackPieces); Collections.sort(whitePieces); } public int getNumberOfBlackPieces(Piece.Type type) { int n = 0; for (int i = 0; i < pieces.length; i++) { for (int j = 0; j < pieces[0].length; j++) { Piece p = pieces[i][j]; if (p != null && p.isBlack() && p.getType() == type) { n++; } } } return n; } public int getNumberOfPieces() { int numberOfPieces = 0; for (int i = 0; i < pieces.length; i++) { for (int j = 0; j < pieces[0].length; j++) { if (pieces[i][j] != null && pieces[i][j].getType() != Piece.Type.NoPiece) { numberOfPieces++; } } } return numberOfPieces; } public int getNumberOfWhitePieces(Piece.Type type) { int n = 0; for (int i = 0; i < pieces.length; i++) { for (int j = 0; j < pieces[0].length; j++) { Piece p = pieces[i][j]; if (p != null && p.isWhite() && p.getType() == type) { n++; } } } return n; } /** * Retrieves the piece at a given location such as "a8" or "e1". * * @param location * string where 1st char represents column (from 'a' to 'h') and * 2nd char represents rank (from 1 to 8) * @return */ public Piece getPieceAt(String location) { if (location.length() != 2) { throw new IllegalArgumentException("location is not valid: " + location); } char fileChar = location.charAt(0); char rankChar = location.charAt(1); int columnIndex = (int) (fileChar - 'a'); int rowIndex = (int) (rankChar - '0') - 1; return pieces[rowIndex][columnIndex]; } /** * Gets rank (horizontal line) designated by specified index. * * @param rankIndex * index from 1 (bottom) to 8 (top) * @return string representing rank of board */ public String getRank(int rankIndex) { int row = rankIndex - 1; StringBuilder sb = new StringBuilder(); for (int col = 0; col < SIZE; col++) { Piece p = pieces[row][col]; if (p == null) { sb.append(EMPTY_CELL); } else { sb.append(p.toString()); } } return sb.toString(); } public void setEmpty() { for (int i = 0; i < pieces.length; i++) { for (int j = 0; j < pieces[0].length; j++) { pieces[i][j] = Piece.noPiece(); } } blackPieces.clear(); whitePieces.clear(); } /** * Sets piece at specified location on board. * * @param rank * from 1 to 8 (top) * @param col * from 1 to 8 (right) * @param piece */ public void setPiece(int rank, int col, Piece piece) { int rowIndex = rank - 1; int colIndex = col - 1; pieces[rowIndex][colIndex] = piece; if (piece.isBlack()) { blackPieces.add(piece); } else if (piece.isWhite()) { whitePieces.add(piece); } } /** * Sets piece at specified location on board. * * @param location * string where 1st char represents column (from 'a' to 'h') and * 2nd char represents rank (from 1 to 8) * @param piece */ public void setPiece(String location, Piece piece) { if (location.length() != 2) { throw new IllegalArgumentException("location is not valid: " + location); } char fileChar = location.charAt(0); char rankChar = location.charAt(1); int file = (int) (fileChar - 'a') + 1; int rank = (int) (rankChar - '0'); setPiece(rank, file, piece); } public double strengthOfBlackPieces() { double strength = 0.0; for (int i = 0; i < pieces.length; i++) { for (int j = 0; j < pieces[0].length; j++) { if (pieces[i][j].isBlack()) { strength += getStrengthOfPiece(pieces[i][j], j); } } } return strength; } public double strengthOfWhitePieces() { double strength = 0.0; for (int i = 0; i < pieces.length; i++) { for (int j = 0; j < pieces[0].length; j++) { if (pieces[i][j].isWhite()) { strength += getStrengthOfPiece(pieces[i][j], j); } } } return strength; } public Move[] getPossibleMoves(int rank, int column) { ArrayList<Move> moves = new ArrayList<>(); Piece p = pieces[rank - 1][column - 1]; Piece.Type type = p.getType(); Move origin = new Move(rank, column); if (type == Piece.Type.King) { Move next = null; int[] coordinates = {1, 0, 1, 1, 0, 1, -1, 1, -1, 0, -1, -1, 0, -1, 1, -1}; for (int i = 0; i < coordinates.length; i += 2) { next = origin.make(coordinates[i], coordinates[i + 1]); if (isOnBoard(next)) { moves.add(next); } } } Move[] a = new Move[moves.size()]; return moves.toArray(a); } private boolean isOnBoard(Move m) { int r = m.getRank(); int c = m.getColumn(); if (r < 1 || r > SIZE || c < 1 || c > SIZE) { return false; } return true; } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (int row = SIZE; row > 0; row--) { String rank = this.getRank(row); sb.append(rank); sb.append(NL); } return sb.toString(); } private boolean columnContainsMoreSamePieces(int col, Piece piece) { int count = 0; for (int row = 0; row < SIZE; row++) { Piece p = pieces[row][col]; if (p.getType().equals(piece.getType()) && p.getColorString().equals(piece.getColorString())) { count++; } } return count > 1; } private double getStrengthOfPiece(Piece piece, int columnIndex) { double baseStrength = piece.getBaseStrength(); if (piece.getType() == Type.Pawn && columnContainsMoreSamePieces(columnIndex, piece)) { return baseStrength / 2.0; } return baseStrength; } private void initialize() { int row = 0; // first row - bottom row = rank 1 pieces[row][0] = Piece.createRookWhite(); pieces[row][7] = Piece.createRookWhite(); pieces[row][1] = Piece.createKnightWhite(); pieces[row][6] = Piece.createKnightWhite(); pieces[row][2] = Piece.createBishopWhite(); pieces[row][5] = Piece.createBishopWhite(); pieces[row][3] = Piece.createQueenWhite(); pieces[row][4] = Piece.createKingWhite(); row = 1; // second row for (int col = 0; col < SIZE; col++) { pieces[row][col] = Piece.createPawnWhite(); } for (row = 2; row < 6; row++) { for (int col = 0; col < SIZE; col++) { pieces[row][col] = Piece.noPiece(); } } row = 6; // seventh row for (int col = 0; col < SIZE; col++) { pieces[row][col] = Piece.createPawnBlack(); } row = 7; // eighth row - top row = rank 8 pieces[row][0] = Piece.createRookBlack(); pieces[row][7] = Piece.createRookBlack(); pieces[row][1] = Piece.createKnightBlack(); pieces[row][6] = Piece.createKnightBlack(); pieces[row][2] = Piece.createBishopBlack(); pieces[row][5] = Piece.createBishopBlack(); pieces[row][3] = Piece.createQueenBlack(); pieces[row][4] = Piece.createKingBlack(); } List<Piece> getBlackPieces() { return blackPieces; } public List<Piece> getWhitePieces() { return whitePieces; } }
true
d6761fab42b3c8cd4c938b5844746603889c1129
Java
bjornmonnens/Builder-Generator
/src/main/java/pl/mjedynak/idea/plugins/builder/factory/impl/CreateBuilderDialogFactoryImpl.java
UTF-8
1,805
2
2
[]
no_license
package pl.mjedynak.idea.plugins.builder.factory.impl; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiManager; import com.intellij.psi.PsiPackage; import pl.mjedynak.idea.plugins.builder.factory.CreateBuilderDialogFactory; import pl.mjedynak.idea.plugins.builder.factory.ReferenceEditorComboWithBrowseButtonFactory; import pl.mjedynak.idea.plugins.builder.gui.CreateBuilderDialog; import pl.mjedynak.idea.plugins.builder.gui.helper.GuiHelper; import pl.mjedynak.idea.plugins.builder.psi.PsiHelper; public class CreateBuilderDialogFactoryImpl implements CreateBuilderDialogFactory { static final String BUILDER_SUFFIX = "Builder"; static final String METHOD_PREFIX = "with"; private static final String DIALOG_NAME = "CreateBuilder"; private PsiHelper psiHelper; private ReferenceEditorComboWithBrowseButtonFactory referenceEditorComboWithBrowseButtonFactory; private GuiHelper guiHelper; public CreateBuilderDialogFactoryImpl(PsiHelper psiHelper, ReferenceEditorComboWithBrowseButtonFactory referenceEditorComboWithBrowseButtonFactory, GuiHelper guiHelper) { this.psiHelper = psiHelper; this.referenceEditorComboWithBrowseButtonFactory = referenceEditorComboWithBrowseButtonFactory; this.guiHelper = guiHelper; } @Override public CreateBuilderDialog createBuilderDialog(PsiClass sourceClass, Project project, PsiPackage srcPackage, PsiManager psiManager) { return new CreateBuilderDialog(project, DIALOG_NAME, sourceClass, sourceClass.getName() + BUILDER_SUFFIX, METHOD_PREFIX, srcPackage, psiHelper, guiHelper, referenceEditorComboWithBrowseButtonFactory); } }
true
b21df0eb823eda213595a817cf20cb372519eee7
Java
jovanibrasil/mssc-brewery-client
/src/test/java/com/jovani/msscbreweryclient/web/client/BreweryClientTest.java
UTF-8
2,177
2.21875
2
[]
no_license
package com.jovani.msscbreweryclient.web.client; import com.jovani.msscbreweryclient.web.model.BeerDto; import com.jovani.msscbreweryclient.web.model.CustomerDto; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.net.URI; import java.util.UUID; import static org.junit.jupiter.api.Assertions.*; @SpringBootTest class BreweryClientTest { @Autowired private BreweryClient breweryClient; @Test void testGetBeerById() { BeerDto beerDto = this.breweryClient.getBeerById(UUID.randomUUID()); assertNotNull(beerDto); } @Test void testSaveBeer(){ BeerDto beerDto = BeerDto.builder() .beerName("Test") .build(); URI uri = this.breweryClient.saveBeer(beerDto); assertNotNull(uri); } @Test void testUpdateBeer(){ BeerDto beerDto = BeerDto.builder() .beerName("Test") .id(UUID.randomUUID()) .upc(123L) .beerStyle("Beer style") .build(); this.breweryClient.updateBeer(beerDto); } @Test void testDeleteBeer(){ this.breweryClient.deleteBeer(UUID.randomUUID()); } @Test void testGetCustomerById() { CustomerDto customerDto = this.breweryClient.getCustomerById(UUID.randomUUID()); assertNotNull(customerDto); } @Test void testSaveCustomer(){ CustomerDto customerDto = CustomerDto.builder() .customerName("Customer name") .build(); URI uri = this.breweryClient.saveCustomer(customerDto); assertNotNull(uri); } @Test void testUpdateCustomer(){ CustomerDto customerDto = CustomerDto.builder() .customerName("Customer name") .id(UUID.randomUUID()) .build(); this.breweryClient.updateCustomer(customerDto); } @Test void testDeleteCustomer(){ this.breweryClient.deleteCustomer(UUID.randomUUID()); } }
true
7f9038b3e900c9c3e2dba75f1267535e77bf8791
Java
TrashMan7/java-project
/chapter3/Algebra2.java
UTF-8
1,307
4.125
4
[]
no_license
/* Maximus Mackert, * 2/8/2019, * I have created a program to solve 2 * 2 equations with an option * to print no solution if the denominator is 0 */ import java.util.Scanner; class Algebra2 { public static void main(String[] args) { //assign variables and promt user to enter their values Scanner input = new Scanner(System.in); System.out.print("Enter a value for the variables A:"); double A = input.nextDouble(); System.out.print("Enter a value for the variables B:"); double B = input.nextDouble(); System.out.print("Enter a value for the variables C:"); double C = input.nextDouble(); System.out.print("Enter a value for the variables D:"); double D = input.nextDouble(); System.out.print("Enter a value for the variables E:"); double E = input.nextDouble(); System.out.print("Enter a value for the variables F:"); double F = input.nextDouble(); //calculate x System.out.println("Equation x (E * D - B * F) / (A * D - B * C) = x = "); System.out.println("Answer: " + (E * D - B * F ) / (A * D - B * C)); //calculate y System.out.println("Equation y (A * F - E * C) / (A * D - B * C) = y = "); System.out.println("Answer: " + (A * F - E * C) / (A * D - B * C)); if (A * D - B * C == 0) System.out.println("The equation has no solution."); } }
true
224684877ff0431f61d306f152183ba147d3606c
Java
archongum/travis-demo
/src/main/java/springweb/controller/BaseController.java
UTF-8
873
2.078125
2
[]
no_license
package springweb.controller; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import springweb.domain.BaseResponse; import springweb.util.BaseResponses; /** * Base Controller * * @author Archon 2022/6/22 * @since */ @RestController public class BaseController { @Value("${spring.application.name}") private String profile; @Value("${spring.datasource.username}") private String username; @Value("${spring.datasource.password}") private String password; @GetMapping("/base/profile") private BaseResponse getProfile() { return BaseResponses.ok(String.format("spring.application.name=%s, spring.datasource.username=%s, spring.datasource.password=%s", profile, username, password)); } }
true
d56430a01b5a763e429b3c7265383a61e4e20930
Java
jahnavialapati/java_assignments
/java_assignments/MMBankAccount/MMBankTest.java
UTF-8
3,139
2.8125
3
[]
no_license
package com.cg.inheritance; import static org.junit.Assert.*; import java.util.logging.Logger; import org.junit.Test; import static org.junit.Assert.*; import org.junit.Test; public class MMBankTest { @Test(expected=InvalidInputException.class) public void currentAccountIfZero() { BankFactory mmBankFactory=new MMBankFactory(); MMCurrentAccount mmCurrentAccount= (MMCurrentAccount)mmBankFactory.getNewCurrentAccount("Jahnavi",0,1000); try { mmCurrentAccount.withdraw(0); } catch (Exception e) { e.printStackTrace(); RuntimeException invalidException=new InvalidInputException(); invalidException.initCause(e); throw invalidException; } } @Test(expected=InvalidInputException.class) public void currentAccountIfNegative() { Logger logger = Logger.getLogger(MMBankFactory.class.getName()); BankFactory mmBankFactory=new MMBankFactory(); MMCurrentAccount mmCurrentAccount= (MMCurrentAccount)mmBankFactory.getNewCurrentAccount("Jahnavi",0,1000); try { mmCurrentAccount.withdraw(-10); } catch (Exception e) { e.printStackTrace(); RuntimeException invalidException=new InvalidInputException(); invalidException.initCause(e); throw invalidException; } } @Test public void currentAccountCheck() { BankFactory mmBankFactory=new MMBankFactory(); MMCurrentAccount mmCurrentAccount= (MMCurrentAccount)mmBankFactory.getNewCurrentAccount("Jahnavi",0,1000); try { mmCurrentAccount.deposit(5000); mmCurrentAccount.withdraw(1000); } catch (Exception e) { e.printStackTrace(); } } @Test public void savingsAccount() { BankFactory mmBankFactory=new MMBankFactory(); MMSavingsAccount mmSavingsAccount = (MMSavingsAccount)mmBankFactory.getNewSavingsAccount("janu",0,true); try { mmSavingsAccount.deposit(10); } catch (Exception e) { e.printStackTrace(); } } @Test(expected =RuntimeException.class) public void savingsAccountIfZero() { BankFactory mmBankFactory=new MMBankFactory(); MMSavingsAccount mmSavingsAccount = (MMSavingsAccount)mmBankFactory.getNewSavingsAccount("janu",0,true); try { mmSavingsAccount.withdraw(0); } catch (Exception e) { e.printStackTrace(); RuntimeException invalidException=new InvalidInputException(); invalidException.initCause(e); throw invalidException; } } @Test public void savingsAccountCheck() { BankFactory mmBankFactory=new MMBankFactory(); MMSavingsAccount mmSavingsAccount = (MMSavingsAccount)mmBankFactory.getNewSavingsAccount("janu",0,true); try { mmSavingsAccount.deposit(10); } catch (Exception e) { e.printStackTrace(); } } @Test(expected =RuntimeException.class) public void savingsAccountExceeds() throws Exception { BankFactory mmBankFactory=new MMBankFactory(); MMSavingsAccount mmSavingsAccount = (MMSavingsAccount)mmBankFactory.getNewSavingsAccount("janu",0,true); try { mmSavingsAccount.deposit(1000); mmSavingsAccount.withdraw(2000); } catch (Exception e) { e.printStackTrace(); RuntimeException insufficientFunds=new InsufficientException(); insufficientFunds.initCause(e); throw insufficientFunds; } } }
true
e11c319bd947afc934e7173086fb5d30f978933f
Java
kuaifan/eeui-template
/plugins/eeui/framework/android/src/main/java/app/eeui/framework/extend/integration/glide/recyclerview/RecyclerViewPreloader.java
UTF-8
4,418
2.59375
3
[ "MIT" ]
permissive
package app.eeui.framework.extend.integration.glide.recyclerview; import android.app.Activity; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import app.eeui.framework.extend.integration.glide.Glide; import app.eeui.framework.extend.integration.glide.ListPreloader; import app.eeui.framework.extend.integration.glide.ListPreloader.PreloadModelProvider; import app.eeui.framework.extend.integration.glide.ListPreloader.PreloadSizeProvider; import app.eeui.framework.extend.integration.glide.RequestManager; /** * Loads a few resources ahead in the direction of scrolling in any {@link RecyclerView} so that * images are in the memory cache just before the corresponding view in created in the list. Gives * the appearance of an infinitely large image cache, depending on scrolling speed, cpu speed, and * cache size. * * <p> Must be added as a listener to the {@link RecyclerView} using * {@link RecyclerView#addOnScrollListener(RecyclerView.OnScrollListener)}, or have its * corresponding methods called from another * {@link RecyclerView.OnScrollListener} to function. </p> * * <p> This class only works with {@link LinearLayoutManager} and * subclasses of {@link LinearLayoutManager}. </p> * * @param <T> The type of the model being displayed in the {@link RecyclerView}. */ @SuppressWarnings("unused") public final class RecyclerViewPreloader<T> extends RecyclerView.OnScrollListener { private final RecyclerToListViewScrollListener recyclerScrollListener; /** * Helper constructor that accepts an {@link Activity}. */ public RecyclerViewPreloader(@NonNull Activity activity, @NonNull PreloadModelProvider<T> preloadModelProvider, @NonNull PreloadSizeProvider<T> preloadDimensionProvider, int maxPreload) { this(Glide.with(activity), preloadModelProvider, preloadDimensionProvider, maxPreload); } /** * Helper constructor that accepts an {@link FragmentActivity}. */ public RecyclerViewPreloader(@NonNull FragmentActivity fragmentActivity, @NonNull PreloadModelProvider<T> preloadModelProvider, @NonNull PreloadSizeProvider<T> preloadDimensionProvider, int maxPreload) { this(Glide.with(fragmentActivity), preloadModelProvider, preloadDimensionProvider, maxPreload); } /** * Helper constructor that accepts an {@link Fragment}. */ public RecyclerViewPreloader(@NonNull Fragment fragment, @NonNull PreloadModelProvider<T> preloadModelProvider, @NonNull PreloadSizeProvider<T> preloadDimensionProvider, int maxPreload) { this(Glide.with(fragment), preloadModelProvider, preloadDimensionProvider, maxPreload); } /** * Helper constructor that accepts an {@link android.app.Fragment}. * @deprecated Use constructor <code>RecyclerViewPreloader(Fragment, PreloadModelProvider<T>, * PreloadSizeProvider<T>)</code> instead. */ @Deprecated public RecyclerViewPreloader(@NonNull android.app.Fragment fragment, @NonNull PreloadModelProvider<T> preloadModelProvider, @NonNull PreloadSizeProvider<T> preloadDimensionProvider, int maxPreload) { this(Glide.with(fragment), preloadModelProvider, preloadDimensionProvider, maxPreload); } /** * Constructor that accepts interfaces for providing the dimensions of images to preload, the list * of models to preload for a given position, and the request to use to load images. * * @param preloadModelProvider Provides models to load and requests capable of loading them. * @param preloadDimensionProvider Provides the dimensions of images to load. * @param maxPreload Maximum number of items to preload. */ public RecyclerViewPreloader(@NonNull RequestManager requestManager, @NonNull PreloadModelProvider<T> preloadModelProvider, @NonNull PreloadSizeProvider<T> preloadDimensionProvider, int maxPreload) { ListPreloader<T> listPreloader = new ListPreloader<>(requestManager, preloadModelProvider, preloadDimensionProvider, maxPreload); recyclerScrollListener = new RecyclerToListViewScrollListener(listPreloader); } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { recyclerScrollListener.onScrolled(recyclerView, dx, dy); } }
true
6c83e151fd9dcfe0583918f4657bacb28dae6d2e
Java
raskolnikov/tracker
/com.m2yazilim.tracker/com.m2yazilim.tracker.util/src/main/java/com/m2yazilim/tracker/dto/TrackerGroupsDto.java
UTF-8
7,373
1.8125
2
[]
no_license
package com.m2yazilim.tracker.dto; // Generated Nov 21, 2012 12:58:59 PM by Hibernate Tools 4.0.0 /** * TrackerGroupsDto generated by hbm2java */ public class TrackerGroupsDto implements java.io.Serializable { private Integer groupId; private int version; private String groupName; private String groupDesc; private int projectId; private int isAdmin; private int manageProject; private int viewTasks; private int openNewTasks; private int modifyOwnTasks; private int modifyAllTasks; private int viewComments; private int addComments; private int editComments; private int editOwnComments; private int deleteComments; private int createAttachments; private int deleteAttachments; private int viewHistory; private int closeOwnTasks; private int closeOtherTasks; private int assignToSelf; private int assignOthersToSelf; private int addToAssignees; private int viewReports; private int addVotes; private int editAssignments; private int showAsAssignees; private int groupOpen; public TrackerGroupsDto() { } public TrackerGroupsDto(String groupName, String groupDesc, int projectId, int isAdmin, int manageProject, int viewTasks, int openNewTasks, int modifyOwnTasks, int modifyAllTasks, int viewComments, int addComments, int editComments, int editOwnComments, int deleteComments, int createAttachments, int deleteAttachments, int viewHistory, int closeOwnTasks, int closeOtherTasks, int assignToSelf, int assignOthersToSelf, int addToAssignees, int viewReports, int addVotes, int editAssignments, int showAsAssignees, int groupOpen) { this.groupName = groupName; this.groupDesc = groupDesc; this.projectId = projectId; this.isAdmin = isAdmin; this.manageProject = manageProject; this.viewTasks = viewTasks; this.openNewTasks = openNewTasks; this.modifyOwnTasks = modifyOwnTasks; this.modifyAllTasks = modifyAllTasks; this.viewComments = viewComments; this.addComments = addComments; this.editComments = editComments; this.editOwnComments = editOwnComments; this.deleteComments = deleteComments; this.createAttachments = createAttachments; this.deleteAttachments = deleteAttachments; this.viewHistory = viewHistory; this.closeOwnTasks = closeOwnTasks; this.closeOtherTasks = closeOtherTasks; this.assignToSelf = assignToSelf; this.assignOthersToSelf = assignOthersToSelf; this.addToAssignees = addToAssignees; this.viewReports = viewReports; this.addVotes = addVotes; this.editAssignments = editAssignments; this.showAsAssignees = showAsAssignees; this.groupOpen = groupOpen; } public Integer getGroupId() { return this.groupId; } public void setGroupId(Integer groupId) { this.groupId = groupId; } public int getVersion() { return this.version; } public void setVersion(int version) { this.version = version; } public String getGroupName() { return this.groupName; } public void setGroupName(String groupName) { this.groupName = groupName; } public String getGroupDesc() { return this.groupDesc; } public void setGroupDesc(String groupDesc) { this.groupDesc = groupDesc; } public int getProjectId() { return this.projectId; } public void setProjectId(int projectId) { this.projectId = projectId; } public int getIsAdmin() { return this.isAdmin; } public void setIsAdmin(int isAdmin) { this.isAdmin = isAdmin; } public int getManageProject() { return this.manageProject; } public void setManageProject(int manageProject) { this.manageProject = manageProject; } public int getViewTasks() { return this.viewTasks; } public void setViewTasks(int viewTasks) { this.viewTasks = viewTasks; } public int getOpenNewTasks() { return this.openNewTasks; } public void setOpenNewTasks(int openNewTasks) { this.openNewTasks = openNewTasks; } public int getModifyOwnTasks() { return this.modifyOwnTasks; } public void setModifyOwnTasks(int modifyOwnTasks) { this.modifyOwnTasks = modifyOwnTasks; } public int getModifyAllTasks() { return this.modifyAllTasks; } public void setModifyAllTasks(int modifyAllTasks) { this.modifyAllTasks = modifyAllTasks; } public int getViewComments() { return this.viewComments; } public void setViewComments(int viewComments) { this.viewComments = viewComments; } public int getAddComments() { return this.addComments; } public void setAddComments(int addComments) { this.addComments = addComments; } public int getEditComments() { return this.editComments; } public void setEditComments(int editComments) { this.editComments = editComments; } public int getEditOwnComments() { return this.editOwnComments; } public void setEditOwnComments(int editOwnComments) { this.editOwnComments = editOwnComments; } public int getDeleteComments() { return this.deleteComments; } public void setDeleteComments(int deleteComments) { this.deleteComments = deleteComments; } public int getCreateAttachments() { return this.createAttachments; } public void setCreateAttachments(int createAttachments) { this.createAttachments = createAttachments; } public int getDeleteAttachments() { return this.deleteAttachments; } public void setDeleteAttachments(int deleteAttachments) { this.deleteAttachments = deleteAttachments; } public int getViewHistory() { return this.viewHistory; } public void setViewHistory(int viewHistory) { this.viewHistory = viewHistory; } public int getCloseOwnTasks() { return this.closeOwnTasks; } public void setCloseOwnTasks(int closeOwnTasks) { this.closeOwnTasks = closeOwnTasks; } public int getCloseOtherTasks() { return this.closeOtherTasks; } public void setCloseOtherTasks(int closeOtherTasks) { this.closeOtherTasks = closeOtherTasks; } public int getAssignToSelf() { return this.assignToSelf; } public void setAssignToSelf(int assignToSelf) { this.assignToSelf = assignToSelf; } public int getAssignOthersToSelf() { return this.assignOthersToSelf; } public void setAssignOthersToSelf(int assignOthersToSelf) { this.assignOthersToSelf = assignOthersToSelf; } public int getAddToAssignees() { return this.addToAssignees; } public void setAddToAssignees(int addToAssignees) { this.addToAssignees = addToAssignees; } public int getViewReports() { return this.viewReports; } public void setViewReports(int viewReports) { this.viewReports = viewReports; } public int getAddVotes() { return this.addVotes; } public void setAddVotes(int addVotes) { this.addVotes = addVotes; } public int getEditAssignments() { return this.editAssignments; } public void setEditAssignments(int editAssignments) { this.editAssignments = editAssignments; } public int getShowAsAssignees() { return this.showAsAssignees; } public void setShowAsAssignees(int showAsAssignees) { this.showAsAssignees = showAsAssignees; } public int getGroupOpen() { return this.groupOpen; } public void setGroupOpen(int groupOpen) { this.groupOpen = groupOpen; } }
true
ffa0465af03a251fad6302101c4b7bda64b90903
Java
perlaaaaaa/android
/Seasons/java_files/Season.java
UTF-8
2,056
2.28125
2
[]
no_license
package pl.edu.zslp.seasons; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.TextView; import java.util.Random; public class Season extends AppCompatActivity { private ImageView imageView; private TextView textView; public static final Random RANDOM=new Random(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_season); if (getIntent().hasExtra("key")) { /* we assign sended season name from MainActivity to String variable text*/ String text = getIntent().getExtras().getString("key"); /* get TextView object from season.xml */ textView = (TextView) findViewById(R.id.textView); /* display text variable in textView object*/ textView.setText(text); } if (getIntent().hasExtra("key1")) { int image=getIntent().getExtras().getInt("key1"); imageView=(ImageView)findViewById(R.id.imageView); imageView.setImageResource(image); final Animation anim1= AnimationUtils.loadAnimation(this,R.anim.my_animation); final Animation.AnimationListener animationListener = new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } }; anim1.setAnimationListener(animationListener); imageView.startAnimation(anim1); } } }
true
e365601ffd4bddcff01231f0e93d7248597f2791
Java
dhirajn72/datastructureAndAlgorithms
/leetcode/src/main/java/leetcode/FindKPairswithSmallestSums_1.java
UTF-8
3,719
3.4375
3
[]
no_license
package leetcode; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @author Dhiraj * @date 10/08/19 */ public class FindKPairswithSmallestSums_1 { public static void main(String[] args) { int[] arr1 =/*{1,1,2}*/ {1, 7, 11}, arr2 = /*{1,2,3}*/{2, 4, 6}; System.out.println(kSmallestPairs(arr1, arr2, 10)); } public static List<List<Integer>> kSmallestPairs(int[] arr1, int[] arr2, int k) { List<List<Integer>> listOfCombinations= new ArrayList<>(); for (int i = 0; i < arr1.length; i++) { for (int j = 0; j < arr2.length; j++) { List<Integer> integers=new ArrayList<>(); integers.add(arr1[i]); integers.add(arr2[j]); listOfCombinations.add(integers); } } Heap heap=new Heap(listOfCombinations.size()); listOfCombinations.stream() .forEach(e->{ int sum=0; for (int i:e){sum+=i;} heap.insert(new Node(sum,e)); }); List<List<Integer>> list= new ArrayList<>(); while (k-->0){ Node node=heap.remove(); if (node!=null) list.add(node.integers); } return list; } static class Heap { private Node[] arr; private int maxCount; private int currentSize; public Heap(int maxCount) { this.maxCount = maxCount; arr = new Node[maxCount]; } public void insert(Node n) { if (currentSize == maxCount) return; Node node = n; arr[currentSize] = node; trickleUp(currentSize++); } private void trickleUp(int index) { int parent = (index - 1) / 2; Node bottom = arr[index]; while (index > 0 && arr[parent].data > bottom.data) { arr[index] = arr[parent]; index = parent; parent = (parent - 1) / 2; } arr[index] = bottom; } public Node remove() { if (currentSize == 0) return null; Node top = arr[0]; arr[0] = arr[--currentSize]; arr[currentSize] = null; trickleDown(0); return top; } private void trickleDown(int index) { Node top = arr[0]; int largeChild; while (index < currentSize / 2) { int leftChild = 2 * index + 1; int rightChild = 2 * index + 2; if (rightChild < currentSize && arr[leftChild].data > arr[rightChild].data) largeChild = rightChild; else largeChild = leftChild; if (top.data <= arr[largeChild].data) break; arr[index] = arr[largeChild]; index = largeChild; } arr[index] = top; } @Override public String toString() { return "Heap{" + "arr=" + Arrays.toString(arr) + ", maxCount=" + maxCount + ", currentSize=" + currentSize + '}'; } } static class Node { int data; List<Integer> integers; public Node(int data,List<Integer> integers) { this.data = data; this.integers=integers; } @Override public String toString() { return "Node{" + "data=" + data + ", integers=" + integers + '}'; } } }
true
1b5c1b1eebbe8e6495956bcaf31dd565c548efec
Java
SaherAbdelaziz/NewsApp
/app/src/main/java/com/newsapp/newsapp/MyNewsLoader.java
UTF-8
620
2.03125
2
[]
no_license
package com.newsapp.newsapp; import android.content.Context; import java.util.List; /** * Created by SaherOs on 2/23/2018. */ class MyNewsLoader extends android.content.AsyncTaskLoader<List<MyNews>> { private String mUrl; public MyNewsLoader(Context context, String url) { super(context); mUrl = url; } @Override protected void onStartLoading() { forceLoad(); } @Override public List<MyNews> loadInBackground() { if (mUrl.length() < 1 || mUrl == null) { return null; } return Utils_query.fetchNewsData(mUrl); } }
true
cf63de32286b4267a7f52fa90be05fc910626354
Java
junbum-0502/Potal_Project
/src/main/java/com/jun/potal/vo/Schedule.java
UTF-8
1,380
2.15625
2
[]
no_license
package com.jun.potal.vo; public class Schedule { private int cIdx; private int userId; private String title; private String time; private String pName; private String sName; private String classRoom; private int proId; @Override public String toString() { return "Schedule [cIdx=" + cIdx + ", userId=" + userId + ", title=" + title + ", time=" + time + ", pName=" + pName + ", sName=" + sName + ", classRoom=" + classRoom + ", proId=" + proId + "]"; } public int getcIdx() { return cIdx; } public void setcIdx(int cIdx) { this.cIdx = cIdx; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public String getpName() { return pName; } public void setpName(String pName) { this.pName = pName; } public String getsName() { return sName; } public void setsName(String sName) { this.sName = sName; } public String getClassRoom() { return classRoom; } public void setClassRoom(String classRoom) { this.classRoom = classRoom; } public int getProId() { return proId; } public void setProId(int proId) { this.proId = proId; } }
true
16cf7d1eb4ff83017d065be7d7e72679de0ed723
Java
Yapp-17th/Android_1_Backend
/display-service/src/main/java/org/picon/exception/handler/ExceptionAdvisor.java
UTF-8
2,728
2.4375
2
[]
no_license
package org.picon.exception.handler; import org.picon.dto.BaseResponse; import org.picon.exception.BusinessException; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.server.ResponseStatusException; @ControllerAdvice @RestController public class ExceptionAdvisor { @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<?> processValidationError(MethodArgumentNotValidException exception) { BindingResult bindingResult = exception.getBindingResult(); StringBuilder builder = new StringBuilder(); for (FieldError fieldError : bindingResult.getFieldErrors()) { builder.append("{"); builder.append("error field: "+fieldError.getField()); builder.append(" message: "+fieldError.getDefaultMessage()); builder.append(" value: "+fieldError.getRejectedValue()); builder.append("}, "); } String errors = builder.toString(); BaseResponse baseResponse = new BaseResponse(400, errors, "0001", "요청값이 잘못되었습니다."); return ResponseEntity.ok().body(baseResponse); } @ExceptionHandler(BusinessException.class) public ResponseEntity<?> businessException(BusinessException exception) { Throwable cause = exception.getCause(); String errors = cause.toString(); BaseResponse baseResponse = new BaseResponse(200, errors, "0003", "로직 오류"); return ResponseEntity.ok().body(baseResponse); } @ExceptionHandler(RuntimeException.class) public ResponseEntity<?> processIllegalStateError(RuntimeException exception) { Throwable cause = exception.getCause(); String errors = cause.toString(); BaseResponse baseResponse = new BaseResponse(500, errors, "0002", "서버 오류"); return ResponseEntity.ok().body(baseResponse); } @ExceptionHandler(ResponseStatusException.class) public ResponseEntity<?> businessLogicException(ResponseStatusException exception) { String message = exception.getReason(); Integer status = exception.getStatus().value(); String errors = exception.getStatus().toString(); BaseResponse baseResponse = new BaseResponse(status, errors, "0003", message); return ResponseEntity.ok().body(baseResponse); } }
true
432e06afdda3c7d8aa9839e531e9609b04bc56a7
Java
Shubham20015/Ds-Algo
/tree/InsertNode.java
UTF-8
765
3.4375
3
[]
no_license
package tree; import java.util.LinkedList; import java.util.Queue; public class InsertNode { static class Node{ int data; Node left; Node right; Node(int data){ this.data = data; left = right = null; } } static Node root; static void insert(int data,Node temp) { if(temp == null) { root = new Node(data); } else { Queue<Node> q = new LinkedList<>(); q.add(temp); while(!q.isEmpty()) { temp = q.remove(); if(temp.left == null) { temp.left = new Node(data); break; } else q.add(temp.left); if(temp.right == null) { temp.right = new Node(data); break; } else q.add(temp.right); } } } }
true
01f12e7420e6ceb4a37e235a9b68a7ec84fcfca6
Java
1181631922/Teacher
/src/cn/edu/sjzc/teacher/util/PinyinComparatorUtils.java
UTF-8
664
2.4375
2
[]
no_license
package cn.edu.sjzc.teacher.util; import java.util.Comparator; import cn.edu.sjzc.teacher.bean.StudentUserBean; public class PinyinComparatorUtils implements Comparator{ // @Override // public int compare(Object o1, Object o2) { // String str1 = PinyinUtils.getPingYin((String) o1); // String str2 = PinyinUtils.getPingYin((String) o2); // return str1.compareTo(str2); // } // @Override public int compare(Object o1, Object o2) { String str1 = PinyinUtils.getPingYin(((StudentUserBean) o1).getPy()); String str2 = PinyinUtils.getPingYin(((StudentUserBean) o2).getPy()); return str1.compareTo(str2); } }
true
51abb7b2cad60ac2243ce40ade6ed13f6c1c32fc
Java
forever-scmdr/evolve
/src/ecommander/model/Parameter.java
UTF-8
2,630
2.875
3
[]
no_license
package ecommander.model; import ecommander.fwk.Strings; import ecommander.model.datatypes.DataType.Type; /** * Общий класс для одиночных и множественных параметров * @author EEEE */ public abstract class Parameter { public static final String NO_VALUE = Strings.EMPTY; protected ParameterDescription desc = null; protected Parameter() {} public Parameter(ParameterDescription desc) { this.desc = desc; } public final String getName() { return desc.getName(); } /** * Создать правильное значение, полученное из интерфейса пользователя в форме строки * @param value */ protected Object createTypeDependentValue(String value) { return desc.getDataType().createValue(value, desc.getFormatter()); } public final Type getType() { return desc.getType(); } ParameterDescription getDesc() { return desc; } public final int getParamId() { return desc.getId(); } public final boolean isDescMultiple() { return desc.isMultiple(); } public final boolean isVirtual() { return desc.isVirtual(); } public final boolean needsDBIndex() { return desc.needsDBIndex(); } public abstract boolean isMultiple(); /** * Создать значение из строки и установить * @param value * @param isConsistent - при загрузке из БД - true, при изменении в процессе работы приложения - false * @return - если значение параметра изменилось - true, если нет, то false */ abstract boolean createAndSetValue(String value, boolean isConsistent); /** * Установить значение напрямую без создания * @param value * @return - если значение параметра изменилось - true, если нет, то false */ abstract boolean setValue(Object value); public abstract boolean isEmpty(); public abstract boolean containsValue(Object value); /** * Возвращает одно значение * В случае одиночного параметра - его значение, в случае множественного - первое значение * @return */ public abstract Object getValue(); /** * Очистить значение параметра */ public abstract void clear(); /** * Узнать, менялся ли параметр с момента загрузки айтема * @return */ public abstract boolean hasChanged(); }
true
e42496760fe0a5a1fc461120fbb257ccbc4a9f0e
Java
rushtang/J2EE_cmdweb
/test/domotest.java
UTF-8
512
2.15625
2
[]
no_license
import java.io.IOException; import java.sql.SQLException; import view.GoodsCmd;; public class domotest { public static void main(String[] args) throws IllegalArgumentException, SQLException, IOException { try { @SuppressWarnings("unused") Process process = Runtime.getRuntime().exec("/usr/bin/open -a Terminal"); Runtime.getRuntime().exec("ls"); System.out.println(); new GoodsCmd().querygoods(); } catch (Exception e) { e.printStackTrace(); } System.out.println("over~"); } }
true
9eacf7f7232c86b8f5cd4af694834ec4845ea54d
Java
anjomartinez/portafolioporgramacion2
/FigurasGeometricas/src/pa/edu/uip/Circulo.java
UTF-8
490
3.203125
3
[ "Apache-2.0" ]
permissive
package pa.edu.uip; public class Circulo extends Figura { private double radio; @Override public double calcular_area() { this.area = 3.14159 * radio * radio; return this.area; } @Override public double calcular_perimetro() { this.perimetro = 2 * 3.14159 * radio; return this.perimetro; } public double getRadio() { return radio; } public void setRadio(double radio) { this.radio = radio; } }
true
f47a433295a3a27bb3c3ad4d4aa939204911556a
Java
shimuli/jphes-core
/dhis-2/dhis-api/src/main/java/org/hisp/dhis/jphes/hierarchy/mechanism/MechanismUnitStore.java
UTF-8
313
1.859375
2
[ "BSD-3-Clause" ]
permissive
package org.hisp.dhis.jphes.hierarchy.mechanism; import org.hisp.dhis.common.GenericIdentifiableObjectStore; /** * @author bangadennis on 11/01/17. */ public interface MechanismUnitStore extends GenericIdentifiableObjectStore<MechanismUnit> { MechanismUnit getMechanismUnitByShortName(String shortName); }
true
71e030ad6111f205c0bba0a086c01dbe01e189ed
Java
liuyong520/CommanyProjects
/SeleniumAndOsworkflow/src/main/java/com/nnk/template/handler/TaskExecuterSchedureHandler.java
GB18030
2,998
2
2
[]
no_license
package com.nnk.template.handler; import com.alibaba.fastjson.JSONObject; import com.nnk.template.Appliaction; import com.nnk.template.util.Base64Util; import com.nnk.template.util.SimpleQuarzManager; import com.nnk.utils.http.utils.StringUtil; import com.opensymphony.workflow.WorkflowException; import com.opensymphony.workflow.basic.BasicWorkflow; import nnk.msgsrv.server.Request; import org.apache.log4j.Logger; import org.quartz.JobDataMap; import java.util.Map; /** * Created with IntelliJ IDEA. * User: xxydl * Date: 2016/9/20 * Time: 9:43 * email: [email protected] * To change this template use File | Settings | File Templates. */ //ض˵ public class TaskExecuterSchedureHandler { public static final Logger log = Logger.getLogger(TaskExecuterSchedureHandler.class); public void execute(Request request) throws WorkflowException { String content = request.getContent(); String jsonstr = Base64Util.decode(content); Map map = JSONObject.parseObject(jsonstr,Map.class); //id String taskId = (String) map.get("taskId"); // String merid = (String) map.get("merId"); //һִеʱ String starttime = (String) map.get("startTime"); // String jobName = (String) map.get("jobName"); //ظ String repeat = (String) map.get("repeat"); int repeattime =0; if(StringUtil.isNotEmpty(repeat)){ repeattime = Integer.parseInt(repeat); } //ظ String repeatDelay = (String) map.get("repeatDelay"); long interval =0; if(StringUtil.isNotEmpty(repeatDelay)){ interval = Long.parseLong(repeatDelay); } // String endTime = (String) map.get("endTime"); BasicWorkflow basicWorkflow = Appliaction.getBasicWorkflowInstance(); String workflowName = Appliaction.MeridMap.get(merid); if(workflowName==null){ log.info("merid is not exsit"); response(request,"0","Fail",taskId); return; } String jobClass = "com.nnk.template.util.SimpleQuartzJob"; JobDataMap dataMap = new JobDataMap(); dataMap.put("basicWorkflow",basicWorkflow); dataMap.put("workflowName",workflowName); dataMap.put("taskId",taskId); //ɹ response(request,"1","success",taskId); log.info("TaskId JobName"+ jobName + "start!"); SimpleQuarzManager.removeJob(jobName); SimpleQuarzManager.addJob(jobName,jobClass,starttime,endTime,repeattime,interval,dataMap); } public void response(Request request,String status,String desc,String taskId){ JSONObject json = new JSONObject(); json.put("taskId",taskId); json.put("status",status); json.put("desc",desc); String base = Base64Util.encode(json.toJSONString()); request.response(base); } }
true
3896f0a581b6af6b658f03c7b8a69634e90d79d5
Java
cliveyao/EKPV12
/ekp/src/com/landray/kmss/km/review/forms/KmReviewFeedbackInfoForm.java
UTF-8
4,495
1.960938
2
[]
no_license
package com.landray.kmss.km.review.forms; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionMapping; import com.landray.kmss.common.convertor.FormConvertor_Common; import com.landray.kmss.common.convertor.FormConvertor_IDToModel; import com.landray.kmss.common.convertor.FormToModelPropertyMap; import com.landray.kmss.km.review.model.KmReviewFeedbackInfo; import com.landray.kmss.km.review.model.KmReviewMain; import com.landray.kmss.sys.organization.model.SysOrgElement; import com.landray.kmss.sys.right.interfaces.BaseAuthForm; import com.landray.kmss.util.DateUtil; /** * 创建日期 2007-Aug-30 * * @author 舒斌 */ public class KmReviewFeedbackInfoForm extends BaseAuthForm { /** * serialVersionUID */ private static final long serialVersionUID = -781110232694790189L; /* * 主文档ID */ private String fdMainId = null; /* * 创建人 */ private String docCreatorName = null; private String docCreatorId = null; /* * 通知人 */ private String fdNotifyId = null; private String fdNotifyPeople = null; /* * 通知类型 */ private String fdNotifyType = null; /* * 提要 */ private String fdSummary = null; /* * 反馈时间 */ private String docCreatorTime = null; /* * 反馈内容 */ private String docContent = null; private String fdReaderNames = null; /** * @return 返回 提要 */ public String getFdSummary() { return fdSummary; } /** * @param fdSummary * 要设置的 提要 */ public void setFdSummary(String fdSummary) { this.fdSummary = fdSummary; } /** * @return 返回 反馈时间 */ public String getDocCreatorTime() { return docCreatorTime; } /** * @param docCreatorTime * 要设置的 反馈时间 */ public void setDocCreatorTime(String docCreatorTime) { this.docCreatorTime = docCreatorTime; } /** * @return 返回 反馈内容 */ public String getDocContent() { return docContent; } /** * @param docContent * 要设置的 反馈内容 */ public void setDocContent(String docContent) { this.docContent = docContent; } public String getDocCreatorName() { return docCreatorName; } public void setDocCreatorName(String docCreatorName) { this.docCreatorName = docCreatorName; } /* * (非 Javadoc) * * @see org.apache.struts.action.ActionForm#reset(org.apache.struts.action.ActionMapping, * javax.servlet.http.HttpServletRequest) */ public void reset(ActionMapping mapping, HttpServletRequest request) { fdMainId = null; fdNotifyId = null; docCreatorId = null; docCreatorName = null; fdSummary = null; docCreatorTime = null; docContent = null; super.reset(mapping, request); } public Class getModelClass() { return KmReviewFeedbackInfo.class; } public String getDocCreatorId() { return docCreatorId; } public void setDocCreatorId(String docCreatorId) { this.docCreatorId = docCreatorId; } public String getFdMainId() { return fdMainId; } public void setFdMainId(String fdMainId) { this.fdMainId = fdMainId; } public String getFdNotifyPeople() { return fdNotifyPeople; } public void setFdNotifyPeople(String fdNotifyPeople) { this.fdNotifyPeople = fdNotifyPeople; } public String getFdNotifyType() { return fdNotifyType; } public void setFdNotifyType(String fdNotifyType) { this.fdNotifyType = fdNotifyType; } private static FormToModelPropertyMap formToModelPropertyMap; public FormToModelPropertyMap getToModelPropertyMap() { if (formToModelPropertyMap == null) { formToModelPropertyMap = new FormToModelPropertyMap(); formToModelPropertyMap.putAll(super.getToModelPropertyMap()); // 时间 formToModelPropertyMap.put("docCreatorTime", new FormConvertor_Common("docCreateTime") .setDateTimeType(DateUtil.TYPE_DATETIME)); // 创建人 formToModelPropertyMap.put("docCreatorId", new FormConvertor_IDToModel("fdCreator", SysOrgElement.class)); //文档 formToModelPropertyMap.put("fdMainId", new FormConvertor_IDToModel("kmReviewMain", KmReviewMain.class)); } return formToModelPropertyMap; } public String getFdNotifyId() { return fdNotifyId; } public void setFdNotifyId(String fdNotifyId) { this.fdNotifyId = fdNotifyId; } public String getFdReaderNames() { return fdReaderNames; } public void setFdReaderNames(String fdReaderNames) { this.fdReaderNames = fdReaderNames; } }
true
71dfbec7220ecd18a06235547aad21d786eb12c1
Java
PetrGlad/pazuzu-registry
/src/main/java/org/zalando/pazuzu/exception/NotFoundException.java
UTF-8
269
2.21875
2
[ "MIT" ]
permissive
package org.zalando.pazuzu.exception; public class NotFoundException extends ServiceException { public NotFoundException(Error error) { super(error); } public NotFoundException(Error error, String details) { super(error, details); } }
true
d1f0789cfac5ac5284b821ad54974067f560efba
Java
MichealPan9999/myprojectcode2
/app/src/main/java/com/panzq/projectcode/activities/TestStartActivityByComponent.java
UTF-8
1,096
1.828125
2
[]
no_license
package com.panzq.projectcode.activities; import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.os.Bundle; import android.view.View; import com.panzq.projectcode.R; public class TestStartActivityByComponent extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test_start_by_component); } public void gotoNumberPicker(View v) { System.out.println("===========gotoNumberPicker======"); ComponentName componentName = new ComponentName("com.panzq.projectcode", "com.panzq.projectcode.activities.OpenGLES20Complete"); Intent intentComPonent = new Intent(); //Intent intent = new Intent(Intent.ACTION_MAIN); //intent.addCategory(Intent.CATEGORY_LAUNCHER); //intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); intentComPonent.setComponent(componentName); this.startActivity(intentComPonent); } }
true
2afc2b61aae3b46fbb6abad069d09753cd34eb97
Java
SomeraTech/spring-course
/src/main/java/tr/com/somera/helloworld/streotypes/AnotherMessageProvider.java
UTF-8
485
2.484375
2
[]
no_license
package tr.com.somera.helloworld.streotypes; import tr.com.somera.helloworld.common.MessageProvider; public class AnotherMessageProvider implements MessageProvider { public void init() { System.out.println("Initialized anotherMessageProvider"); } public void destroy() { System.out.println("Destroyed anotherMessageProvider"); } @Override public String getMessage() { return "Another message from another message provider"; } }
true
7a7cd8e3cdb1318e0303dc0681cb80545d981424
Java
coypanglei/nanjinJianduo
/app/src/main/java/com/shaoyue/weizhegou/module/credit/fragment/MyDataDhglFragment.java
UTF-8
8,063
1.90625
2
[ "Apache-2.0" ]
permissive
package com.shaoyue.weizhegou.module.credit.fragment; import android.os.Bundle; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import com.blankj.utilcode.util.ObjectUtils; import com.blankj.utilcode.util.SPUtils; import com.libracore.lib.widget.StateButton; import com.shaoyue.weizhegou.R; import com.shaoyue.weizhegou.api.callback.BaseCallback; import com.shaoyue.weizhegou.api.model.BaseResponse; import com.shaoyue.weizhegou.api.remote.DhApi; import com.shaoyue.weizhegou.base.BaseFragment; import com.shaoyue.weizhegou.entity.cedit.InquiryDetailsBean; import com.shaoyue.weizhegou.entity.cedit.MyHangBean; import com.shaoyue.weizhegou.manager.UserMgr; import com.shaoyue.weizhegou.module.credit.adapter.shenqing.InquiryDetailsTwoAdapter; import com.shaoyue.weizhegou.widget.YStarView; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import butterknife.BindView; public class MyDataDhglFragment extends BaseFragment { @BindView(R.id.rv_credit) RecyclerView mRvCredit; @BindView(R.id.rv_credit_two) RecyclerView mRvCreditTwo; @BindView(R.id.ll_all) LinearLayout llAll; @BindView(R.id.starBar) YStarView starBar; @BindView(R.id.tv_tg) TextView tvTg; @BindView(R.id.sb_edit) StateButton sbEdit; private InquiryDetailsTwoAdapter mAdapter; private InquiryDetailsTwoAdapter mAdapterTwo; private List<InquiryDetailsBean> mList = new ArrayList<>(); private List<InquiryDetailsBean> mListTwo = new ArrayList<>(); public static MyDataDhglFragment newInstance() { Bundle args = new Bundle(); MyDataDhglFragment fragment = new MyDataDhglFragment(); fragment.setArguments(args); return fragment; } @Override protected int getLayoutId() { return R.layout.fragment_dhgl_my_data; } @Override protected void initView(View rootView) { super.initView(rootView); starBar.setStarCount(5);//星星总数 starBar.setChange(false);//设置星星是否可以点击和滑动改变 mAdapter = new InquiryDetailsTwoAdapter(); mAdapterTwo = new InquiryDetailsTwoAdapter(); mRvCredit.setLayoutManager(new GridLayoutManager(getActivity(), 4)); mRvCredit.setAdapter(mAdapter); mRvCredit.setNestedScrollingEnabled(false);//禁止滑动 mRvCreditTwo.setLayoutManager(new GridLayoutManager(getActivity(), 4)); mRvCreditTwo.setAdapter(mAdapterTwo); mRvCreditTwo.setNestedScrollingEnabled(false);//禁止滑动 } @Override public void onResume() { super.onResume(); initData(); } /** * 刷新数据 */ private void initData() { Map<String, String> map = new HashMap<>(); map.put("zjhm", SPUtils.getInstance().getString(UserMgr.SP_APPLY_ID)); DhApi.lookInfo(map, new BaseCallback<BaseResponse<MyHangBean>>() { @Override public void onSucc(BaseResponse<MyHangBean> result) { llAll.setVisibility(View.VISIBLE); mList.clear(); mListTwo.clear(); if (ObjectUtils.isNotEmpty(result.data)) { if (null != result.data.getRecords()) { if (result.data.getRecords().size() > 0) { MyHangBean.RecordsBean myHangBean = result.data.getRecords().get(0); MyHangBean.RecordsBean myHangPeiOu = new MyHangBean.RecordsBean(); //我行评级 starBar.setRating(myHangBean.getWhpj());//设置星星亮的颗数 if ("查看详情".equals(SPUtils.getInstance().getString("status"))) { sbEdit.setVisibility(View.GONE); } // //提示信息 // if (ObjectUtils.isNotEmpty(myHangBean.getDescription())) { // tvError.setVisibility(View.VISIBLE); // tvError.setText(myHangBean.getDescription()); // } try { //通过未通过 if ("未通过".equals(myHangBean.getXtshjl())) { tvTg.setText(myHangBean.getXtshjl()); tvTg.setTextColor(getResources().getColor(R.color.color_b9b8b8)); } else { tvTg.setText(myHangBean.getXtshjl()); tvTg.setTextColor(getResources().getColor(R.color.color_49a0ed)); } } catch (IllegalStateException e) { } if (result.data.getRecords().size() > 1) { myHangPeiOu = result.data.getRecords().get(0); } mList.add(new InquiryDetailsBean("授信额度(万元)", myHangBean.getYsxje() + "", "")); mList.add(new InquiryDetailsBean("用信余额(万元)", myHangBean.getYxye() + "", "")); mList.add(new InquiryDetailsBean("不良贷款余额(万元)", myHangBean.getBnbldk() + "", "")); mList.add(new InquiryDetailsBean("担保不良(万元)", myHangBean.getDbbldk(), "")); mList.add(new InquiryDetailsBean("五级分类", myHangBean.getSqwjfl(), "")); mList.add(new InquiryDetailsBean("本期授信日期", myHangBean.getSxrq(), "")); mList.add(new InquiryDetailsBean("", "", "")); mList.add(new InquiryDetailsBean("", "", "")); mListTwo.add(new InquiryDetailsBean("存款时点余额(元)", myHangBean.getCksdye() + "", myHangPeiOu.getCksdye() + "")); mListTwo.add(new InquiryDetailsBean("近一年存款日均(元)", myHangBean.getJynckrj() + "", myHangPeiOu.getJynckrj() + "")); mListTwo.add(new InquiryDetailsBean("活期存款年日均(元)", myHangBean.getHqcknrj() + "", myHangPeiOu.getHqcknrj() + "")); mListTwo.add(new InquiryDetailsBean("定期存款年日均(元)", myHangBean.getDqcknrj() + "", myHangPeiOu.getDqcknrj() + "")); } mAdapter.setNewData(mList); mAdapterTwo.setNewData(mListTwo); } } } }, this); } // @OnClick({R.id.tv_tg, R.id.tv_wtg}) // public void onViewClicked(View view) { // // //不能点击 id有时不能点击 // if (click) { // Drawable drawable = getResources().getDrawable(R.drawable.icon_left_star_black); // drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); // Drawable drawable2 = getResources().getDrawable(R.drawable.icon_left_blue); // drawable2.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); // switch (view.getId()) { // case R.id.tv_tg: // // tvError.setVisibility(View.VISIBLE); // tvError.setText("系统未通过,人工干预已通过!!"); // tvWtg.setCompoundDrawables(drawable, null, null, null); // tvWtg.setTextColor(getResources().getColor(R.color.color_b9b8b8)); // tvTg.setCompoundDrawables(drawable2, null, null, null); // tvTg.setTextColor(getResources().getColor(R.color.color_49a0ed)); // break; // // // } // // } // } }
true
e4f6628dd7022b0dcdeaf7bb874c08f8c5a81374
Java
cmFodWx5YWRhdjEyMTA5/smell-and-machine-learning
/ast_results/andOTP_andOTP/app/src/main/java/org/shadowice/flocke/andotp/Activities/BaseActivity.java
UTF-8
1,481
1.773438
2
[]
no_license
// isComment package org.shadowice.flocke.andotp.Activities; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; public abstract class isClassOrIsInterface extends ThemedActivity { private ScreenOffReceiver isVariable; private BroadcastReceivedCallback isVariable; @Override protected void isMethod(Bundle isParameter) { super.isMethod(isNameExpr); isNameExpr = new ScreenOffReceiver(); isMethod(isNameExpr, isNameExpr.isFieldAccessExpr); } @Override protected void isMethod() { isMethod(isNameExpr); super.isMethod(); } private void isMethod() { if (isMethod() != MainActivity.class) isMethod(); } public void isMethod(BroadcastReceivedCallback isParameter) { this.isFieldAccessExpr = isNameExpr; } public class isClassOrIsInterface extends BroadcastReceiver { public IntentFilter isVariable = new IntentFilter(isNameExpr.isFieldAccessExpr); @Override public void isMethod(Context isParameter, Intent isParameter) { if (isNameExpr.isMethod().isMethod(isNameExpr.isFieldAccessExpr)) { if (isNameExpr != null) isNameExpr.isMethod(); isMethod(); } } } interface isClassOrIsInterface { void isMethod(); } }
true
b6360008d1ee79fa50c907e0c120ba31e64d572a
Java
TheBestDevelopers/FindMyBeer
/FindMyBeer-backend/src/main/java/com/thebestdevelopers/find_my_beer/DTO/PubDTO.java
UTF-8
702
2.328125
2
[ "Apache-2.0" ]
permissive
package com.thebestdevelopers.find_my_beer.DTO; /** * @author Jakub Pisula */ public class PubDTO { private long id; private String pubName; private String gks; public PubDTO() { } public PubDTO(long user_id, String pubName) { this.id = user_id; this.pubName = pubName; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getPubName() { return pubName; } public void setPubName(String pubName) { this.pubName = pubName; } public String getGks() { return gks; } public void setGks(String gks) { this.gks = gks; } }
true
450117b24cffa76823db80f95b91979da6e8f28f
Java
defex04/Javito
/javito/src/main/java/com/db/javito/service/interf/MainService.java
UTF-8
221
1.90625
2
[]
no_license
package com.db.javito.service.interf; import com.db.javito.model.Main; import java.util.List; public interface MainService { void insert(Main main); String getById(Integer id); List<Main> getAllData(); }
true
e089219986ab2bf0a7ac6dcd60d624e89fa9101f
Java
santhoshthegreat/J2ME
/Memory/src/Resizer.java
UTF-8
2,344
2.890625
3
[]
no_license
import javax.microedition.lcdui.*; import java.io.IOException; public class Resizer { public static Image resizeImage(Image src, int screenWidth, int screenHeight) { int srcWidth = src.getWidth(); int srcHeight = src.getHeight(); Image tmp = Image.createImage(screenWidth, srcHeight); Graphics g = tmp.getGraphics(); int ratio = (srcWidth << 16) / screenWidth; int pos = ratio / 2; for (int x = 0; x < screenWidth; x++) { g.setClip(x, 0, 1, srcHeight); g.drawImage(src, x - (pos >> 16), 0, Graphics.LEFT | Graphics.TOP); pos += ratio; } Image resizedImage = Image.createImage(screenWidth, screenHeight); g = resizedImage.getGraphics(); ratio = (srcHeight << 16) / screenHeight; pos = ratio / 2; for (int y = 0; y < screenHeight; y++) { g.setClip(0, y, screenWidth, 1); g.drawImage(tmp, 0, y - (pos >> 16), Graphics.LEFT | Graphics.TOP); pos += ratio; } return resizedImage; } public static Image resizeImagepng(Image src,int destW,int destH) { int srcW = src.getWidth(); int srcH = src.getHeight(); int div=1; // Correction of width and height to be divideable by div-parameter if ((div != 0) && (destW % div != 0)) { for (int i=1; i<=div; i++) { if ((destW - i) % div == 0) { destW = destW - div; if (destH % (destW / div) != 0) { for (int j=1; j<=div; j++) { if ((destH - j) % (destW / div) == 0) { destH = destH - j; break; } } } } } } // Prepare arrays for line-by-line-processing final int[] lineRGB = new int[srcW]; final int[] srcPos = new int[destW]; int n = 0; int eps = -(srcW >> 1); for( int x = 0; x < srcW; x++ ) { eps += destW; if ( (eps << 1) >= srcW ) { if( ++n == destW ) { break; } srcPos[n] = x; eps -= srcW; } } final int[] dest = new int[destW*destH]; for( int y = 0; y < destH; y++ ) { src.getRGB( lineRGB, 0, srcW, 0, y * srcH / destH, srcW, 1 ); for( int x = 0; x < destW; x++ ) { dest[y*destW+x] = lineRGB[srcPos[x]]; } } System.gc(); Image destImg = Image.createRGBImage(dest, destW, destH, true); return destImg; } }
true
90842f04e0d0884e835660e27eb1d503bbef0e7e
Java
lihong112/springboot_shiro_sunli
/src/main/java/com/sunli/sale/service/impl/PreviousSaleServiceImpl.java
UTF-8
3,444
2.125
2
[]
no_license
package com.sunli.sale.service.impl; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.sunli.sale.domain.PreviousSale; import com.sunli.sale.dto.reqDTO.PreviousSaleSelectListDTO; import com.sunli.sale.mappers.PreviousSaleMapper; import com.sunli.sale.service.PreviousSaleService; import com.sunli.sale.utils.DateUtils; import org.springframework.stereotype.Service; import tk.mybatis.mapper.entity.Example; import tk.mybatis.mapper.util.StringUtil; import javax.annotation.Resource; import java.util.Date; import java.util.List; @Service public class PreviousSaleServiceImpl implements PreviousSaleService { @Resource private PreviousSaleMapper previousSaleMapper; @Override public int insert(PreviousSale previousSale) { previousSale.setCreateTime(new Date()); return previousSaleMapper.insert(previousSale); } @Override public PageInfo<PreviousSale> selectList(PreviousSaleSelectListDTO dto) { Example example = new Example(PreviousSale.class); Example.Criteria criteria = example.createCriteria(); if(dto.getSpendingTime2()!=null && dto.getSpendingTime1()!=null){ criteria.andBetween("spendingTime",dto.getSpendingTime1(),dto.getSpendingTime2()); }else { List<Integer> type = dto.getType(); Boolean isFix=false; for (Integer tp: type) { if(tp.equals(0)){ isFix=true; } } if(!isFix){ Date date=new Date(); Date minMonthDay = DateUtils.getMinMonthDay(date); Date maxMonthDay = DateUtils.getMaxMonthDay(date); criteria.andBetween("spendingTime", minMonthDay,maxMonthDay); } } if(StringUtil.isNotEmpty(dto.getName())){ criteria.andLike("name",dto.getName()); } if(dto.getMoney1()!=null && dto.getMoney2()!=null){ criteria.andBetween("money",dto.getMoney1(),dto.getMoney2()); } if(dto.getType()!=null){ criteria.andIn("type",dto.getType()); } Integer pageNum=dto.getPageNum()!=null?dto.getPageNum():1; Integer pageSize=dto.getPageSize()!=null?dto.getPageSize():100; PageHelper.startPage(pageNum,pageSize); List<PreviousSale> previousSales = previousSaleMapper.selectByExample(example); return new PageInfo<PreviousSale>(previousSales); } @Override public int updateOne(PreviousSale previousSale) { Long id = previousSale.getId(); PreviousSale sale = previousSaleMapper.selectByPrimaryKey(id); if(StringUtil.isNotEmpty(previousSale.getName())) sale.setName(previousSale.getName()); if (StringUtil.isNotEmpty(previousSale.getRemark())) sale.setRemark(previousSale.getRemark()); if (previousSale.getMoney()!=null) sale.setMoney(previousSale.getMoney()); if (previousSale.getType()!=null) sale.setType(previousSale.getType()); if (previousSale.getSpendingTime()!=null) sale.setSpendingTime(previousSale.getSpendingTime()); sale.setModifyTime(new Date()); int i = previousSaleMapper.updateByPrimaryKey(sale); return i; } @Override public int deleteOne(Integer id) { return previousSaleMapper.deleteByPrimaryKey(id); } }
true
b4f9da77ca90719983fd20bba6481f5957df785c
Java
lilei0523/tianditu-microservice-parent
/tianditu-microservice-util/src/main/java/com/cyy/chinamobile/tianditu/microservice/util/common/CodeUtil.java
UTF-8
907
2.5
2
[]
no_license
package com.cyy.chinamobile.tianditu.microservice.util.common; import java.security.SecureRandom; import java.util.Random; import sun.misc.BASE64Encoder; public class CodeUtil { /** * * @Title: getSalt * @Description: 获取盐值 * @return * @throws Exception * @return: String */ public static String getSalt() throws Exception { Random random = new SecureRandom(); byte[] salt = new byte[8]; random.nextBytes(salt); String str = new BASE64Encoder().encode(salt); return str; } /** * * @Title: getMessageCode * @Description: 获取num位随机码 * @return * @return: String */ public static String getRandomCode(int num) { StringBuffer digitDivisor = new StringBuffer("1"); for (int i = 1; i < num; i++) { digitDivisor.append("0"); } return Integer.toString((int) ((Math.random() * 9 + 1) * Integer.parseInt(digitDivisor.toString()))); } }
true
e528ade71cc779ed584841cc6889e04e542f983f
Java
ihmcrobotics/ihmc-open-robotics-software
/ihmc-robotics-toolkit/src/main/java/us/ihmc/robotics/physics/ImpulseBasedJointTwistProvider.java
UTF-8
3,314
2.28125
2
[ "Apache-2.0" ]
permissive
package us.ihmc.robotics.physics; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.ejml.data.DMatrixRMaj; import org.ejml.dense.row.CommonOps_DDRM; import us.ihmc.euclid.tuple3D.interfaces.Vector3DReadOnly; import us.ihmc.mecano.multiBodySystem.interfaces.JointBasics; import us.ihmc.mecano.multiBodySystem.interfaces.JointReadOnly; import us.ihmc.mecano.multiBodySystem.interfaces.RigidBodyBasics; import us.ihmc.mecano.tools.JointStateType; import us.ihmc.mecano.tools.MultiBodySystemTools; public class ImpulseBasedJointTwistProvider implements JointStateProvider { private final RigidBodyBasics rootBody; private int impulseDimension; private boolean isImpulseZero = true; private final DMatrixRMaj impulse = new DMatrixRMaj(6, 1); private final List<JointBasics> joints = new ArrayList<>(); private final Map<JointBasics, DMatrixRMaj> apparentInertiaMatrixInverseMap = new HashMap<>(); public ImpulseBasedJointTwistProvider(RigidBodyBasics rootBody) { this.rootBody = rootBody; } public void clear(int impulseDimension) { isImpulseZero = true; this.impulseDimension = impulseDimension; impulse.reshape(impulseDimension, 1); impulse.zero(); joints.clear(); apparentInertiaMatrixInverseMap.clear(); } public void addAll(Collection<? extends JointBasics> joints) { for (JointBasics joint : joints) { add(joint); } } public void add(JointBasics joint) { if (MultiBodySystemTools.getRootBody(joint.getPredecessor()) != rootBody) return; joints.add(joint); apparentInertiaMatrixInverseMap.put(joint, new DMatrixRMaj(joint.getDegreesOfFreedom(), impulseDimension)); } public List<JointBasics> getJoints() { return joints; } public DMatrixRMaj getApparentInertiaMatrixInverse(JointBasics joint) { return apparentInertiaMatrixInverseMap.get(joint); } public void setImpulseToZero() { isImpulseZero = true; impulse.zero(); } public void setImpulse(double impulse) { isImpulseZero = false; this.impulse.set(0, impulse); } public void setImpulse(DMatrixRMaj impulse) { isImpulseZero = false; this.impulse.set(impulse); } public void setImpulse(Vector3DReadOnly impulse) { isImpulseZero = false; impulse.get(this.impulse); } public void setImpulse(Vector3DReadOnly impulseLinear, double impulseAngular) { isImpulseZero = false; impulseLinear.get(this.impulse); this.impulse.set(3, 0, impulseAngular); } @Override public JointStateType getState() { return JointStateType.VELOCITY; } private final DMatrixRMaj jointTwist = new DMatrixRMaj(6, 1); @Override public DMatrixRMaj getJointState(JointReadOnly joint) { if (isImpulseZero) return null; DMatrixRMaj apparentInertiaMatrixInverse = apparentInertiaMatrixInverseMap.get(joint); if (apparentInertiaMatrixInverse == null) return null; jointTwist.reshape(joint.getDegreesOfFreedom(), 1); CommonOps_DDRM.mult(apparentInertiaMatrixInverse, impulse, jointTwist); return jointTwist; } }
true
578374a2388a75c713de4b0589935b7aa2ed054d
Java
windychablis/RxJavaAndRetrofit
/outsidescreen/src/main/java/com/lilosoft/outsidescreen/bean/NetWorkInfo.java
UTF-8
4,067
1.8125
2
[]
no_license
package com.lilosoft.outsidescreen.bean; /** * Created by chablis on 2016/11/8. */ public class NetWorkInfo { /** * workwin_id : 2 * deptname : 区城管委 * callnum_ip : * loginname : * workin_ip : * userout_ip : 10.0.2.15 * depttel : 027-111122 * supervisiontel : 027-1231231 * website : * urltype : * url : * area_code : 360105000000 * tv_ip : * tvname : * sp_ip : */ private String workwin_id; private String deptname; private String callnum_ip; private String loginname; private String workin_ip; private String userout_ip; private String depttel; private String supervisiontel; private String website; private String urltype; private String url; private String area_code; private String tv_ip; private String tvname; private String sp_ip; @Override public String toString() { return "NetWorkInfo{" + "workwin_id='" + workwin_id + '\'' + ", deptname='" + deptname + '\'' + ", callnum_ip='" + callnum_ip + '\'' + ", loginname='" + loginname + '\'' + ", workin_ip='" + workin_ip + '\'' + ", userout_ip='" + userout_ip + '\'' + ", depttel='" + depttel + '\'' + ", supervisiontel='" + supervisiontel + '\'' + ", website='" + website + '\'' + ", urltype='" + urltype + '\'' + ", url='" + url + '\'' + ", area_code='" + area_code + '\'' + ", tv_ip='" + tv_ip + '\'' + ", tvname='" + tvname + '\'' + ", sp_ip='" + sp_ip + '\'' + '}'; } public String getWorkwin_id() { return workwin_id; } public void setWorkwin_id(String workwin_id) { this.workwin_id = workwin_id; } public String getDeptname() { return deptname; } public void setDeptname(String deptname) { this.deptname = deptname; } public String getCallnum_ip() { return callnum_ip; } public void setCallnum_ip(String callnum_ip) { this.callnum_ip = callnum_ip; } public String getLoginname() { return loginname; } public void setLoginname(String loginname) { this.loginname = loginname; } public String getWorkin_ip() { return workin_ip; } public void setWorkin_ip(String workin_ip) { this.workin_ip = workin_ip; } public String getUserout_ip() { return userout_ip; } public void setUserout_ip(String userout_ip) { this.userout_ip = userout_ip; } public String getDepttel() { return depttel; } public void setDepttel(String depttel) { this.depttel = depttel; } public String getSupervisiontel() { return supervisiontel; } public void setSupervisiontel(String supervisiontel) { this.supervisiontel = supervisiontel; } public String getWebsite() { return website; } public void setWebsite(String website) { this.website = website; } public String getUrltype() { return urltype; } public void setUrltype(String urltype) { this.urltype = urltype; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getArea_code() { return area_code; } public void setArea_code(String area_code) { this.area_code = area_code; } public String getTv_ip() { return tv_ip; } public void setTv_ip(String tv_ip) { this.tv_ip = tv_ip; } public String getTvname() { return tvname; } public void setTvname(String tvname) { this.tvname = tvname; } public String getSp_ip() { return sp_ip; } public void setSp_ip(String sp_ip) { this.sp_ip = sp_ip; } }
true
e3196c3e36b3b1ca7eba1043cbb87746c011061b
Java
NolzCoding/DungeonGenerator
/src/main/java/io/github/NolzCoding/Utils/MapGenerator.java
UTF-8
5,689
2.21875
2
[]
no_license
package io.github.NolzCoding.Utils; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.bukkit.BukkitWorld; import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormat; import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormats; import com.sk89q.worldedit.extent.clipboard.io.ClipboardReader; import com.sk89q.worldedit.function.operation.Operation; import com.sk89q.worldedit.function.operation.Operations; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.session.ClipboardHolder; import io.github.NolzCoding.Main; import org.bukkit.Bukkit; import org.bukkit.Location; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Random; public class MapGenerator { private final WorldEdit worldEdit = WorldEdit.getInstance(); private final Main main = Main.getMain(); public void createMap(int dimensions, int maxTunnels, int maxLenght, Location location) { Bukkit.getLogger().info("GENERATING PLEASE WAIT"); ArrayList<Integer> map = createArray(1, dimensions); int row = random(0, dimensions); int column = random(0, dimensions); ArrayList<ArrayList<Integer>> dirs = new ArrayList<>(); dirs.add(newdir(-1, 0)); dirs.add(newdir(1, 0)); dirs.add(newdir(0, -1)); dirs.add(newdir(0, 1)); ArrayList<Integer> lastDir = dirs.get(random(0,dirs.size() -1)); ArrayList<Integer> randomDir; LocalDateTime then = LocalDateTime.now(); //Stops the shit from running for ever, prob teribble idea while (maxLenght > 0 && maxTunnels > 0 && dimensions > 0) { do { randomDir = dirs.get(random(0,dirs.size() -1)); if (ChronoUnit.SECONDS.between(then, LocalDateTime.now()) >= 2) break; //Stops the shit from running for ever } while ((randomDir.get(0).equals(-lastDir.get(0)) && randomDir.get(1).equals(-lastDir.get(1))) || (randomDir.get(0).equals(lastDir.get(0)) && randomDir.get(1).equals(lastDir.get(1))) ); if (ChronoUnit.SECONDS.between(then, LocalDateTime.now()) >= 2) break; //Stops the shit from running for ever int randomLenght = random(0, maxLenght); int tunnelLenght = 0; while (tunnelLenght < randomLenght) { if ( ((row == 0) && (randomDir.get(0) == -1)) || ((column == 0) && (randomDir.get(1) == -1)) || ((row == dimensions - 1) && (randomDir.get(0) == 1)) || ((column == dimensions - 1) && (randomDir.get(1) == 1)) ){ break; } else { map.set(row * column, 0); row += randomDir.get(0); column += randomDir.get(1); tunnelLenght++; } } if (tunnelLenght > 0) { lastDir = randomDir; maxTunnels--; } } pastepart(location, map, dimensions); } private void pastepart(Location orgin, ArrayList<Integer> map, int dimensions) { File file = new File(main.getDataFolder(), "scem/square.schem"); ClipboardFormat format = ClipboardFormats.findByFile(file); for (int x = 0; x < dimensions; x++) { for (int y = 0; y < dimensions; y++) { if (map.get(y*x) == 0) { Location loc = orgin.clone(); loc.add(x * 5, 0, y * 5); paste(loc, format, file); } } } } private ArrayList<Integer> createArray(int num, int dimensions) { ArrayList<Integer> integers = new ArrayList<>(); for (int x = 0; x < dimensions; x++) { for (int y = 0; y < dimensions; y++) { integers.add(num); } } return integers; } private ArrayList<Integer> newdir(int one, int two) { ArrayList<Integer> arrayList = new ArrayList<>(); arrayList.add(one); arrayList.add(two); return arrayList; } private int random(int min, int max) { Random r = new Random(); return r.nextInt((max - min) + 1) + min; } private void paste(Location loc, ClipboardFormat format, File file) { if (format != null) { try (ClipboardReader reader = format.getReader(new FileInputStream(file))) { Clipboard clipboard = reader.read(); try (EditSession editSession = worldEdit.getEditSessionFactory().getEditSession(new BukkitWorld(loc.getWorld()), -1)) { Operation operation = new ClipboardHolder(clipboard) .createPaste(editSession) .to(BlockVector3.at( loc.getX(), loc.getY(), loc.getZ() )) .ignoreAirBlocks(false) .build(); Operations.complete(operation); } } catch (IOException | WorldEditException e) { e.printStackTrace(); } } } }
true
4dabecc715a37dc44642b7129a182e72fcd8d35f
Java
swolarz/service-discovery-api
/src/main/java/com/put/swolarz/servicediscoveryapi/api/controller/PostOnceExactlyException.java
UTF-8
253
2.015625
2
[]
no_license
package com.put.swolarz.servicediscoveryapi.api.controller; public class PostOnceExactlyException extends Exception { public PostOnceExactlyException(String poeToken) { super(String.format("Duplicate POST request: %s", poeToken)); } }
true
ad7d6d2bfbc1265ff81722fb1965c318e6236017
Java
AlexZFX/AlgorithmStudy
/src/main/java/com/alexzfx/leetCode/struct/SortHelper.java
UTF-8
683
3.0625
3
[]
no_license
package com.alexzfx.leetCode.struct; import java.util.Arrays; import java.util.Random; import static com.alexzfx.leetCode.struct.HeapSort.heapSort; /** * Author : Alex * Date : 2018/10/20 9:38 * Description : */ public class SortHelper { public static void main(String[] args) { int[] nums = new int[1000]; Random random = new Random(); for (int i = 0; i < 1000; i++) { nums[i] = random.nextInt(100); } heapSort(nums); System.out.println(Arrays.toString(nums)); } public static void swap(int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } }
true
f2a260b44700d19da792971b3e5b50b2b2c90b65
Java
Mishin870/LabGenReloadedAPI
/src/main/java/com/mishin870/labgenreloaded/api/network/messages/MessageAlert.java
UTF-8
1,431
2.515625
3
[]
no_license
package com.mishin870.labgenreloaded.api.network.messages; import com.jsoniter.any.Any; import com.mishin870.labgenreloaded.api.PluginBase; import com.mishin870.labgenreloaded.api.network.IMessageAbstractFactory; import com.mishin870.labgenreloaded.api.network.Message; import com.mishin870.labgenreloaded.api.network.MessageController; /** * Сообщение для отображения алерта у пользователя (клиент -&gt; сервер)<br> * Алерт - это сообщение с одной кнопкой "ок" */ public class MessageAlert extends Message { /** * Текст внутри алерта */ public String text; /** * Заголовок окна алерта */ public String title; /** * Мета алерта */ public long meta; public MessageAlert() {} public MessageAlert(long meta, String text, String title) { this.meta = meta; this.text = text; this.title = title; } public MessageAlert(long meta, String text) { this(meta, text, ""); } public MessageAlert(String text) { this(-1, text, ""); } @Override public int getCode() { return MessageController.MSG_ALERT; } @Override public void visit(PluginBase pluginBase) { pluginBase.onMessage(this); } public static class Factory implements IMessageAbstractFactory { @Override public Message create(Any data) { return data.as(MessageAlert.class); } } }
true
542d9a73c490e636c99a4fbbf1633bad3683bd62
Java
sharmaabhilaksh/designPatternsExamples
/src/com/Test.java
UTF-8
578
2.65625
3
[]
no_license
package com; import java.io.*; public class Test { public static void main(String[] args) { try{ BufferedReader br = new BufferedReader(new FileReader("/home/abhilaksh/Desktop/1")); BufferedWriter bw = new BufferedWriter(new FileWriter("/home/abhilaksh/Desktop/2")); int i; do{ i=br.read(); bw.write((char)i); }while (i!=-1); bw.close(); br.close(); }catch(Exception e) { e.printStackTrace(); } } }
true
a7aaab4710595f3f977acfad9063df0f9420f8eb
Java
smartvilllab/GraphqlSample
/app/src/main/java/com/pixelro/graphqlsample/MainActivity.java
UTF-8
5,657
1.882813
2
[]
no_license
package com.pixelro.graphqlsample; import android.os.Bundle; import com.apollographql.apollo.ApolloCall; import com.apollographql.apollo.ApolloCallback; import com.apollographql.apollo.ApolloClient; import com.apollographql.apollo.api.Operation; import com.apollographql.apollo.api.Response; import com.apollographql.apollo.api.ResponseField; import com.apollographql.apollo.cache.normalized.CacheKey; import com.apollographql.apollo.cache.normalized.CacheKeyResolver; import com.apollographql.apollo.cache.normalized.NormalizedCacheFactory; import com.apollographql.apollo.cache.normalized.sql.ApolloSqlHelper; import com.apollographql.apollo.cache.normalized.sql.SqlNormalizedCacheFactory; import com.apollographql.apollo.exception.ApolloException; import com.auth0.android.jwt.Claim; import com.auth0.android.jwt.JWT; import com.com.pixelro.graphqlsample.AllMembersQuery; import com.com.pixelro.graphqlsample.SignInMutation; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonObjectFormatVisitor; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.snackbar.Snackbar; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.util.Log; import android.view.View; import android.view.Menu; import android.view.MenuItem; import org.jetbrains.annotations.NotNull; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.Map; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.security.Keys; import java.security.Key; public class MainActivity extends AppCompatActivity { private final String TAG = this.getClass().toString(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = findViewById(R.id.fab); fab.setVisibility(View.GONE); // fab.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) // .setAction("Action", null).show(); // } // }); // setApollo(); setJWT(); } private void setJWT() { String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7ImlkIjoiY2thM2g0ejhyMDAwMGo2NnczajVvdHMwMCIsImVtYWlsIjoiZXJAZW5raW5vLmNvbSIsIm5hbWUiOiLstZzsmIjsp4AiLCJ0ZWwiOiIwMTAyNDkwODk1NSJ9LCJpYXQiOjE1OTEwODUyMTAsImV4cCI6MTU5MTE3MTYxMH0.yZQgpDbelEwLj4sCuqC_zbf5_bzri9Ee3kcDqUZzWw4"; try { JSONObject jsonObj = JWTUtils.getJson(token,"user"); String email = (String) jsonObj.get("email"); String name = (String) jsonObj.get("name"); String id= (String) jsonObj.get("id"); String tel = (String) jsonObj.get("tel"); Log.i(">>>>>>>>>>>", email + " " + name + " " + id + " " + tel); } catch (Exception e) { e.printStackTrace(); } // JWT jwt = new JWT(token); // Date expiresAt = jwt.getExpiresAt(); // boolean isExpired = jwt.isExpired(10); // 10 seconds leeway // String subject = jwt.getSubject(); // Log.i(TAG, (expiresAt!=null)? "expiresAt : " + expiresAt.toString() : "expiresAt NULL"); // Log.i(TAG, "isExpired : " + isExpired ); // Log.i(TAG, (subject!=null)? "subject : " + subject.toString() : "subject NULL"); // // // JSONObject user1 = Jwts.parser().parseClaimsJws(token).getBody().get("user",JSONObject.class); // Map<String, Claim> allClaims = jwt.getClaims(); // Claim userClaim = jwt.getClaim("user"); // String userStr = jwt.getClaim("user").asString(); // JSONObject user1 = userClaim. asObject(JSONObject.class); // JSONObject user2 = new JSONObject().; // Log.i(TAG, "userStr : " + userStr.toString()); // Log.i(TAG, "user : " + user1.toString()); // // for (String item : list) { // Log.i(TAG, "user item : " + item ); // } // JSONObject jsonUser2 = (JSONObject) allClaims.get("user").asObject(Class<JSONObject>); // JSONObject jsonUser2 = (JSONObject) allClaims.get("user").asObject(Class<JSONObject>); // try { // Log.i(TAG, "jsonUser : " + jsonUser2.toString() ); // Log.i(TAG, "jsonUser2 : " + jsonUser2.get("id").toString() ); // Log.i(TAG, "jsonUser2 : " + jsonUser2.get("email").toString() ); // Log.i(TAG, "jsonUser2 : " + jsonUser2.get("name").toString() ); // Log.i(TAG, "jsonUser2 : " + jsonUser2.get("tel").toString() ); // } catch (JSONException e) { // e.printStackTrace(); // } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
true
859eb2427faf1aec0ff87814a00de634d29bd4cb
Java
yundanfengqingfeng/chao
/chao-springboot/src/main/java/com/chao/springboot/system/service/impl/SysUserServiceImpl.java
UTF-8
1,842
2.3125
2
[]
no_license
package com.chao.springboot.system.service.impl; import com.chao.springboot.system.bean.SysUser; import com.chao.springboot.system.repository.SysUserRepository; import com.chao.springboot.system.service.SysUserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import javax.annotation.Resource; @Service public class SysUserServiceImpl implements SysUserService { private final Logger log = LoggerFactory.getLogger(this.getClass()); @Resource private SysUserRepository sysUserRepository; @Override public SysUser save(SysUser sysUser) { return sysUserRepository.save(sysUser); } @Override public SysUser findOne(int id) { return sysUserRepository.findOne(id); } @Override public SysUser findByUsername(String username) { log.info("进入了SysUserService.findByUsername().....username={}",username); return sysUserRepository.findByUsername(username); } @Override public SysUser findByUserCodeAndPassword(String userCode, String password) { log.info("进入了findByUserCodeAndPassword通过账号与密码查找用户的方法findByUserCodeAndPassword()..."); return null; } @Override public boolean exists(int id) { return sysUserRepository.exists(id); } @Override public Iterable<SysUser> findAll() { return sysUserRepository.findAll(); } @Override public long count() { return sysUserRepository.count(); } @Override public void delete(int id) { sysUserRepository.delete(id); } @Override public void delete(SysUser sysUser) { sysUserRepository.delete(sysUser); } @Override public void deleteAll() { sysUserRepository.deleteAll(); } }
true
491d10ddec1b4fdfec65c0fc67a84af7e9175ccb
Java
Jasonchen99/ssm
/src/main/java/com/cpy/controller/AccountController.java
UTF-8
1,329
2.234375
2
[]
no_license
package com.cpy.controller; import com.cpy.domain.Account; import com.cpy.service.AccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.List; /** * @author 93404 * @version 1.0 * @description: 账户web * @date 21/01/29 11:37 */ @Controller @RequestMapping("/account") public class AccountController { @Autowired private AccountService accountService; @RequestMapping("/findAll") public String findAll(Model model){ System.out.println("表现层:查询所有账户"); //调用service方法 List<Account> accounts=accountService.findAll(); model.addAttribute("list",accounts); return "list"; } @RequestMapping("/save") public void save(Account account, HttpServletRequest request, HttpServletResponse response) throws Exception { System.out.println("表现层:保存所有账户"); //调用service方法 accountService.saveAccount(account); response.sendRedirect(request.getContextPath()+"/account/findAll"); return; } }
true
98bda35dbb0b1743ebe3b2e57146d537ae9d7756
Java
NobodyLikesZergs/VKbirhtday
/app/src/main/java/com/example/maq/sdr/data/remote/beans/VkAccountBean.java
UTF-8
1,633
2.328125
2
[]
no_license
package com.example.maq.sdr.data.remote.beans; import com.example.maq.sdr.domain.entities.Message; import com.example.maq.sdr.domain.entities.VkAccount; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import java.util.LinkedList; public class VkAccountBean { @SerializedName("user_id") @Expose private String id; @SerializedName("first_name") @Expose private String firstName; @SerializedName("last_name") @Expose private String lastName; @SerializedName("photo_200_orig") @Expose private String imgUrl; @SerializedName("photo_200") @Expose private String photo200; @SerializedName("photo_100") @Expose private String photo100; @SerializedName("bdate") private String birthDate; public VkAccount createVkAccountObject() { DateTime parsedBirthDate = null; String[] formats = {"dd.MM.yyyy", "dd.MM"}; for (int i = 0; i < 2; i++) { try { parsedBirthDate = DateTimeFormat.forPattern(formats[i]).parseDateTime(birthDate); if (i == 1) { parsedBirthDate = parsedBirthDate.withYear(3000); } } catch (Exception e) { } } String avatar; if (photo200 != null) avatar = photo200; else avatar = imgUrl; return new VkAccount(id, avatar, photo100, parsedBirthDate, new LinkedList<Message>(), firstName, lastName); } }
true
310abb190dda47d92863805b95fcdcf1882a0aea
Java
mainmonkey/JRSLib
/src/edu/ncepu/jrslib/io/RateReader.java
UTF-8
160
1.820313
2
[]
no_license
package edu.ncepu.jrslib.io; import edu.ncepu.jrslib.data.DataSet; public interface RateReader { public DataSet readRating(String path) throws Exception; }
true
750b20750b00a2c78d5bf812b3faba9b755e2470
Java
DavidMuikia/Automation
/src/test/java/automationTestcases/TC_005_Registration_Radio_Button.java
UTF-8
611
2.046875
2
[]
no_license
package automationTestcases; import org.openqa.selenium.By; import org.testng.annotations.Test; import automation.basePage.InitiateDriver; public class TC_005_Registration_Radio_Button extends InitiateDriver { @Test public void tc001() { driver.findElement(By.name("fld_username")).sendKeys("Hello"); // Write Data driver.findElement(By.name("fld_username")).clear(); driver.findElement(By.name("fld_username")).sendKeys("Testing"); driver.findElement(By.xpath("//input[@name='add_type' and @value='home']")).click(); // Radio Button driver.findElement(By.name("terms")).click(); } }
true
377ca874e4031f1b023e74876ef2692e75c29a22
Java
djat/suprabrowser
/ss.core/src/ss/domainmodel/SphereLocation.java
UTF-8
1,393
2.234375
2
[]
no_license
package ss.domainmodel; import ss.framework.entities.ISimpleEntityProperty; import ss.framework.entities.xmlentities.XmlEntityObject; public class SphereLocation extends XmlEntityObject { public static final String ITEM_ROOT_ELEMENT_NAME = "sphere"; private final ISimpleEntityProperty url = super .createAttributeProperty( "@URL"); private final ISimpleEntityProperty exDisplay = super .createAttributeProperty( "@ex_display"); private final ISimpleEntityProperty exSystem = super .createAttributeProperty( "@ex_system"); private final ISimpleEntityProperty exMessage = super .createAttributeProperty( "@ex_message"); /** * */ public SphereLocation() { super( ITEM_ROOT_ELEMENT_NAME ); } public String getDisplay() { return this.exDisplay.getValue(); } public void setDisplay(String value) { this.exDisplay.setValue( value ); } public String getUrl() { return this.url.getValue(); } public void setUrl(String value) { this.url.setValue( value ); } public String getSystem() { return this.exSystem.getValue(); } public void setSystem(String value) { this.exSystem.setValue( value ); } public String getMessage() { return this.exMessage.getValue(); } public void setMessage(String value) { this.exMessage.setValue( value ); } }
true
3a53f98d98f188dec8fff2756585756d26d335d9
Java
juanCano29/SimsaTickets
/app/src/main/java/com/example/juankno4/simsaticket/adaptadores/adaptaHistR.java
UTF-8
1,845
2.1875
2
[]
no_license
package com.example.juankno4.simsaticket.adaptadores; import android.annotation.SuppressLint; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.example.juankno4.simsaticket.Modelos.HistorialEmp; import com.example.juankno4.simsaticket.Modelos.Personas; import com.example.juankno4.simsaticket.Modelos.Problemas; import com.example.juankno4.simsaticket.Modelos.TipoProb; import com.example.juankno4.simsaticket.R; import java.util.List; public class adaptaHistR extends RecyclerView.Adapter<adaptaHistR.ViewHolder> { private List<HistorialEmp> Listemp; public adaptaHistR(List<HistorialEmp> listemp) { Listemp = listemp; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cartas_historial, viewGroup, false); return new ViewHolder(v); } @SuppressLint("SetTextI18n") @Override public void onBindViewHolder(@NonNull adaptaHistR.ViewHolder viewHolder, int i) { viewHolder.Tprob.setText(Listemp.get(i).getNombreProblema()); viewHolder.est.setText(Listemp.get(i).getEstatus()); viewHolder.no.setText(Listemp.get(i).getId().toString()); } @Override public int getItemCount() { return Listemp.size(); } public class ViewHolder extends RecyclerView.ViewHolder { TextView Tprob,est,no; public ViewHolder(View v) { super(v); Tprob=itemView.findViewById(R.id.tipi); est=itemView.findViewById(R.id.esta); no=itemView.findViewById(R.id.hrst); } } }
true