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
6a454e9f55e360b74d0bd2252f27da480c2fa2ad
Java
TohidMakari/AnnuityFormula
/src/main/java/com/company/annuityformula/api/PrincipalStrategy.java
UTF-8
454
2.875
3
[]
no_license
package com.company.annuityformula.api; import java.math.BigDecimal; /** * Created by t.makari on 4/7/2019. * <p> * Principal is calculated by the following * formula Principal = Annuity - Interest * * </p> * */ public interface PrincipalStrategy { /** * @param annuity calculated annuity formula * @param interest intrest rate * @return */ BigDecimal calculate(BigDecimal annuity, BigDecimal interest); }
true
2e393f7f402d931da7a0b21aa1fac5b97a992534
Java
shixiangzhao/J2X3
/src/main/java/shixzh/j2x3/y2017/m04/d24/Bank.java
UTF-8
235
2.390625
2
[]
no_license
package shixzh.j2x3.y2017.m04.d24; public abstract class Bank { public abstract void transfer(int from, int to, double amount) throws InterruptedException; public abstract double getTotalBalance(); public abstract int size(); }
true
d771939d9bfdac444b3bf84ee3316bb3625d7511
Java
jbossws/jbossws-cxf
/modules/testsuite/shared-tests/src/test/java/org/jboss/test/ws/jaxws/handlerauth/SimpleHandler.java
UTF-8
2,301
1.96875
2
[ "Apache-2.0" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.jboss.test.ws.jaxws.handlerauth; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import javax.xml.namespace.QName; import jakarta.xml.ws.handler.MessageContext; import jakarta.xml.ws.handler.soap.SOAPHandler; import jakarta.xml.ws.handler.soap.SOAPMessageContext; public class SimpleHandler implements SOAPHandler<SOAPMessageContext> { public static AtomicInteger counter = new AtomicInteger(0); public static AtomicInteger outboundCounter = new AtomicInteger(0); @Override public boolean handleMessage(SOAPMessageContext context) { Boolean isOutbound = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY); String operation = ((QName) context.get(MessageContext.WSDL_OPERATION)).getLocalPart(); if (!isOutbound && !operation.startsWith("getHandlerCounter")) { counter.incrementAndGet(); } else if (isOutbound && !operation.startsWith("getHandlerCounter")) { outboundCounter.incrementAndGet(); } return true; } @Override public boolean handleFault(SOAPMessageContext context) { String operation = ((QName) context.get(MessageContext.WSDL_OPERATION)).getLocalPart(); if (!operation.startsWith("getHandlerCounter")) { outboundCounter.incrementAndGet(); } return true; } @Override public void close(MessageContext context) { //NOOP } @Override public Set<QName> getHeaders() { return null; } }
true
f817d4f100a274c2b6a6b9140360f89fe27cfcc0
Java
mrzhuzx/jja1901javaweb
/javaweb_model/src/main/java/com/javaweb/tzhu/dao/impl/FoodDaoJDBCImpl.java
UTF-8
1,758
2.234375
2
[]
no_license
package com.javaweb.tzhu.dao.impl; import com.javaweb.tzhu.appcomm.BaseDaoMysql; import com.javaweb.tzhu.dao.FoodDao; import com.javaweb.tzhu.entity.Food; import org.springframework.stereotype.Repository; import java.util.List; public class FoodDaoJDBCImpl extends BaseDaoMysql<Food> implements FoodDao { public List<Food> search(Integer foodStyleId, Integer lunchId) { StringBuffer sb = new StringBuffer(); sb.append(" select * from food where 1=1 "); if (foodStyleId > 0) { sb.append(" and foodStyleId=" + foodStyleId); } if (lunchId > 0) { sb.append(" and lunchId=" + lunchId); } String sql = sb.toString(); System.out.println(sql); return findList(Food.class, sql); } public List<Food> search(Integer foodStyleId, Integer lunchId, Integer pageNum, Integer pageSize) { StringBuffer sb = new StringBuffer(); sb.append(" select * from food where 1=1 "); if (foodStyleId > 0) { sb.append(" and foodStyleId=" + foodStyleId); } if (lunchId > 0) { sb.append(" and lunchId=" + lunchId); } sb.append(" limit "+((pageNum-1)*pageSize)+","+pageSize); String sql = sb.toString(); System.out.println(sql); return findList(Food.class, sql); } /** * 查询产品分类 * * @param foodStyleId * @return */ public Integer count(Integer foodStyleId) { StringBuffer sql= new StringBuffer("SELECT count(*) as 'count' FROM food where 1=1 "); if(foodStyleId>0){ sql.append(" and foodstyleid="+foodStyleId); } return countAll(sql.toString()); } }
true
e69f2dd2bec6af00bcdff1a543354963ccc95474
Java
Malacrida/ing-sw-2019-lista-lograsso-malacrida
/src/main/java/it/polimi/isw2019/view/VisitorView.java
UTF-8
905
2.078125
2
[]
no_license
package it.polimi.isw2019.view; import it.polimi.isw2019.message.movemessage.*; import it.polimi.isw2019.model.exception.EndTurn; public interface VisitorView{ void visitActionView(ActionMessage actionMessage); void visitRun(RunMessage runMessage); void visitGrab(GrabMessage grabMessage); void visitReload(ReloadMessage reloadMessage); void visitUpdateView(UpdateMessage updateMessage); void waitForStart(EndRegistration endRegistration); void useWeaponCard(UseWeaponCardMessage useWeaponCardMessage); void visitCardChoice(ChoiceCard choiceCard); void usePowerUpCard(UsePowerUpCardMessage usePowerUpCardMessage); void firstPlayerChooseMap(FirstMessageFirstPlayer firstMessageFirstPlayer); void visitStartView (StartMessage startMessage); void terminatorAction(TerminatorMessage terminatorMessage); void visitEndGame(EndGame endGame); }
true
c4198259de49d3925f14bff1576cafca71a49024
Java
caio-ps/sismultas
/multas-web/src/br/com/fiap/sismultas/web/ws/email/EnviaEmailNotificacao.java
UTF-8
1,236
1.609375
2
[]
no_license
package br.com.fiap.sismultas.web.ws.email; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebService; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.ws.RequestWrapper; import javax.xml.ws.ResponseWrapper; /** * This class was generated by the JAX-WS RI. * JAX-WS RI 2.1.6 * Generated source version: 2.1 * */ @WebService(name = "EnviaEmailNotificacao", targetNamespace = "http://ws.sismultas.fiap.com.br/") @XmlSeeAlso({ ObjectFactory.class }) public interface EnviaEmailNotificacao { /** * * @param relatorio * @throws Exception_Exception */ @WebMethod(action = "enviaEmailNotificacao") @RequestWrapper(localName = "enviaEmailNotificacao", targetNamespace = "http://ws.sismultas.fiap.com.br/", className = "br.com.fiap.sismultas.web.ws.email.EnviaEmailNotificacao_Type") @ResponseWrapper(localName = "enviaEmailNotificacaoResponse", targetNamespace = "http://ws.sismultas.fiap.com.br/", className = "br.com.fiap.sismultas.web.ws.email.EnviaEmailNotificacaoResponse") public void enviaEmailNotificacao( @WebParam(name = "relatorio", targetNamespace = "") RelatorioVO relatorio) throws Exception_Exception ; }
true
7e4bd74262d10d97ae2e8c1abefea2ed1de6b372
Java
lucasvieira34/academicweb-api
/src/main/java/br/com/academicwebapi/repository/DisciplinaRepository.java
UTF-8
386
1.960938
2
[]
no_license
package br.com.academicwebapi.repository; import br.com.academicwebapi.models.Disciplina; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.Optional; @Repository public interface DisciplinaRepository extends JpaRepository<Disciplina, Long> { Optional<Disciplina> findByNome(String nomeDisciplina); }
true
e402ecdb01e4a0515573c62d718bc4354de7b9b8
Java
gabrielpadilh4/controle-de-ponto-e-acesso-com-spring-boot
/src/main/java/com/github/gabrielpadilh4/controledepontoacesso/repository/CategoriaUsuarioRepository.java
UTF-8
367
1.640625
2
[]
no_license
package com.github.gabrielpadilh4.controledepontoacesso.repository; import com.github.gabrielpadilh4.controledepontoacesso.model.CategoriaUsuario; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface CategoriaUsuarioRepository extends JpaRepository<CategoriaUsuario, Long> { }
true
13974e5a6337bd4e0b98f10d76754d45af55c18c
Java
amarschn/EnclosureOptimizer
/src/EnclosureProblem.java
UTF-8
7,775
2.859375
3
[]
no_license
import org.moeaframework.core.Solution; import org.moeaframework.core.variable.EncodingUtils; import org.moeaframework.core.variable.RealVariable; import org.moeaframework.problem.AbstractProblem; /** * * @author drew SimpleEnclosure is a formulation of the PCB enclosure design * problem that has been simplified to mass, temperature, and cost * objectives, where each objective is simplified significantly. * * */ public class EnclosureProblem extends AbstractProblem { /* * General constants */ public final double LI_SPECIFIC_ENERGY = 100.0; // W*h/kg public final double LI_ENERGY_DENSITY = 500000.0; // W*h/m^3 public final double AMBIENT_TEMP = 25.0; // celsius public final double LI_COST_DENSITY = 2.5; // W*h/$ /* * User-set variables */ // Dimensions of the enclosure public final double ENC_HEIGHT = 0.01; public final double ENC_LENGTH = 0.05; public final double ENC_WIDTH = 0.02; public final double ENC_OUTER_VOLUME = ENC_HEIGHT * ENC_LENGTH * ENC_WIDTH; // Dimensions of the PCB public final double PCB_HEIGHT = 0.0015; public final double PCB_LENGTH = 0.010; public final double PCB_WIDTH = 0.015; public final double PCB_VOLUME = PCB_HEIGHT * PCB_LENGTH * PCB_WIDTH; public final double PCB_MASS = PCB_VOLUME * 1850; // 1850 is density of FR4 public final boolean MOBILE = true; public final int ENC_QUANTITY = 100; /* * Materials that are allowed */ public final Material[] MATERIALS = new Material[] { new Aluminum(), new ABS(), new MDF(), new Steel() }; public final FabMethod[] FAB_METHODS = new FabMethod[] { new Machined(), new Printed(), new LaserCut(), new InjectionMolded() }; /* * Different indices used to select different parameter variables */ private int encMaterialIndex = 0; private int encFabMethodIndex = 1; private int encFabTimeIndex = 2; private int encWallThicknessIndex = 3; private int powerConsumptionIndex = 4; private int batteryLifeIndex = 5; public EnclosureProblem() { // Decision variables are wall thickness and material // Objectives are Mass, Temperature, and Cost super(6, 7); } @Override public void evaluate(Solution solution) { // Initialize the objectives double totalMass = 0.0; double surfaceTemperature = 0.0; double totalCost = 0.0; double operationTime = 0.0; double computationAbility = 0.0; double durability = 0.0; double marketAdvantage = 0.0; /* * Get the values for the decision variables */ // thickness is in millimeters double encWallThickness = EncodingUtils .getReal(solution.getVariable(encWallThicknessIndex)); // material is one of 4 types int encMaterial = EncodingUtils .getInt(solution.getVariable(encMaterialIndex)); // fabrication method is one of 3 types int encFabMethod = EncodingUtils .getInt(solution.getVariable(encFabMethodIndex)); // manufacturing time is in days int encFabTime = EncodingUtils .getInt(solution.getVariable(encFabTimeIndex)); // power consumption is in watts double powerConsumption = EncodingUtils .getReal(solution.getVariable(powerConsumptionIndex)); /* * Perform needed calculations based on decision variables */ // This is the inner void subtracted from the outer volume double materialVolume = this.ENC_OUTER_VOLUME - (this.ENC_HEIGHT - encWallThickness) * (this.ENC_WIDTH - encWallThickness) * (this.ENC_LENGTH - encWallThickness); double materialMass = materialVolume * this.MATERIALS[encMaterial].getMassDensity(); // cost of the material double materialCost = materialMass * this.MATERIALS[encMaterial].getCostDensity() * ENC_QUANTITY; // cost of fabrication double fabCost = this.FAB_METHODS[encFabMethod].getCost(ENC_QUANTITY, this.MATERIALS[encMaterial], materialMass, encFabTime); /* * Set the objective functions */ // Evaluate temperature surfaceTemperature = AMBIENT_TEMP + (powerConsumption * encWallThickness) / (this.MATERIALS[encMaterial].getThermalConductivity() * this.ENC_WIDTH * this.ENC_LENGTH); // Computation ability is a function of power consumption and we // want to maximize it, so we use a negative sign computationAbility = powerConsumption; // Durability is a function of wall thickness and material. We want to // maximize it. durability = this.MATERIALS[encMaterial].getYieldStrength() * encWallThickness; // Market advantage is a function related to the quantity of // units and time of fabrication. marketAdvantage = ENC_QUANTITY / encFabTime; if (MOBILE) { // battery life is in watt-hours double batteryLife = EncodingUtils .getReal(solution.getVariable(batteryLifeIndex)); // the mass of the battery is a function of battery life double batteryMass = batteryLife / LI_SPECIFIC_ENERGY; // cost of the battery double batteryCost = batteryLife / LI_COST_DENSITY; // Evaluate total mass totalMass = materialMass + PCB_MASS + batteryMass; // Operation time (we want to maximize this, so we use a negative // sign) operationTime = batteryLife / powerConsumption; // Evaluate cost totalCost = materialCost + fabCost + batteryCost; // Set the objectives for the evaluation solution.setObjectives(new double[] { totalMass, surfaceTemperature, totalCost, -operationTime, -computationAbility, -durability, -marketAdvantage }); } else { // Evaluate total mass totalMass = materialMass + PCB_MASS; // Evaluate cost totalCost = materialCost + fabCost; // Set the objectives for the evaluation solution.setObjectives(new double[] { totalMass, surfaceTemperature, totalCost, -computationAbility, -durability, -marketAdvantage }); } } @Override public Solution newSolution() { Solution solution = new Solution(numberOfVariables, numberOfObjectives); // different kinds of materials solution.setVariable(encMaterialIndex, EncodingUtils.newInt(0, MATERIALS.length - 1)); // different kinds of fab methods solution.setVariable(encFabMethodIndex, EncodingUtils.newInt(0, FAB_METHODS.length - 1)); // goes from 1 to 10 days solution.setVariable(encFabTimeIndex, EncodingUtils.newInt(1, 10)); // thickness in meters solution.setVariable(encWallThicknessIndex, new RealVariable(0.001, 0.1)); // power consumption in watts solution.setVariable(powerConsumptionIndex, new RealVariable(0.001, 1000.0)); if (MOBILE) { double batteryLimit = LI_ENERGY_DENSITY * ENC_OUTER_VOLUME; // W-hrs of battery life. solution.setVariable(batteryLifeIndex, new RealVariable(0.001, batteryLimit)); } return solution; } }
true
82e372e9879e0745670a0242da690a3ecd32f479
Java
ReparoMC/ChatThing
/src/me/reparo/chatthing/Util.java
UTF-8
2,730
2.5
2
[]
no_license
package me.reparo.chatthing; import java.util.List; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; public class Util { /* * Configuration file */ static FileConfiguration getConfig() { return ChatThing.ct.getConfig(); } /* * Colour // variables */ public static String colour(String s) { return ChatColor.translateAlternateColorCodes('&', s); } public static String colour(CommandSender sender, String s) { if(sender instanceof Player) { return ChatColor.translateAlternateColorCodes('&', s) .replace("%sendername", sender.getName()) .replace("%senderdisplay", ((Player) sender).getDisplayName()); } else { return ChatColor.translateAlternateColorCodes('&', s) .replace("%sendername", sender.getName()) .replace("%senderdisplay", sender.getName()); } } /* * Chat lock */ public static boolean chatlocked; public static List<String> chatlockcommands = getConfig().getStringList("Chat lock blocked commands"); public static String chatlockenabledbroadcast(CommandSender sender) { return colour(sender, getConfig().getString("Chat lock enabled broadcast")); } public static String chatlockdisabledbroadcast(CommandSender sender) { return colour(sender, getConfig().getString("Chat lock disabled broadcast")); } public static String chatlockenablederrormessage(CommandSender sender) { return colour(sender, getConfig().getString("Chat lock enabled error message")); } /* * Chat clear */ public static String spamchatwith(CommandSender sender) { return colour(sender, getConfig().getString("Spam chat with")); } public static String chathasbeencleared(CommandSender sender) { return colour(sender, getConfig().getString("Chat has been cleared")); } public static int spamchat = getConfig().getInt("Spam chat"); /* * Permission handling */ public static boolean hasPermission(CommandSender sender, String permission) { if(sender.hasPermission(permission)) { return true; } else { sender.sendMessage(colour(sender, getConfig().getString("No permission"))); return false; } } /* * Enabled or disabled feature */ public static boolean isEnabled(String feature) { if(feature.equalsIgnoreCase("commandspy")) { return getConfig().getBoolean("Enable commandspy"); } else if(feature.equalsIgnoreCase("chatclear")) { return getConfig().getBoolean("Enable chatclear"); } else if(feature.equalsIgnoreCase("chatlock")) { return getConfig().getBoolean("Enable chatlock"); } else { return false; } } }
true
e50c4d9760a86bf988272646c4a1b29937ef6674
Java
RiccardoGrieco/outta-my-circle
/app/src/main/java/com/acg/outtamycircle/StartScreen.java
UTF-8
4,695
2.125
2
[]
no_license
package com.acg.outtamycircle; import android.graphics.Color; import com.badlogic.androidgames.framework.Graphics; import com.badlogic.androidgames.framework.Graphics.PixmapFormat; import com.badlogic.androidgames.framework.impl.AndroidGame; import com.badlogic.androidgames.framework.impl.AndroidLoadingScreen; import com.badlogic.androidgames.framework.impl.AndroidPixmap; import com.badlogic.androidgames.framework.impl.CircularAndroidTileEffect; import com.badlogic.androidgames.framework.impl.RectangularAndroidTileEffect; public class StartScreen extends AndroidLoadingScreen { public StartScreen(AndroidGame game) { super(game); } @Override public void onProgress(int progress) { final Graphics graphics = androidGame.getGraphics(); int x = (graphics.getWidth()-Assets.loading.getWidth())/2; int y = (graphics.getHeight()-Assets.loading.getHeight())/2; //x: 13, y: 254, width: 290, height: 19 graphics.drawPixmap(Assets.loading, x,y); int val = 473; float vals = (float)progress*(float)val/100f; graphics.drawRect((int)vals+12+x,y+12,val-(int)vals,31, Color.BLACK); androidGame.display(); //force the canvas rendering :'( } @Override public void doJob() { Graphics graphics = androidGame.getGraphics(); Assets.background = graphics.newPixmap("tiles/bgtile.png", PixmapFormat.ARGB8888); Assets.backgroundTile = new RectangularAndroidTileEffect((AndroidPixmap)Assets.background); Assets.loading = graphics.newPixmap("etc/loading.png", PixmapFormat.ARGB8888); graphics.drawEffect(Assets.backgroundTile, 0,0, graphics.getWidth(), graphics.getHeight()); setProgress(15); Assets.arena = graphics.newPixmap("tiles/arenatile.png", PixmapFormat.ARGB8888); Assets.arenaTile = new CircularAndroidTileEffect((AndroidPixmap)Assets.arena); setProgress(30); Assets.help = graphics.newPixmap("buttons/help.png", PixmapFormat.ARGB8888); Assets.start = graphics.newPixmap("buttons/start.png", PixmapFormat.ARGB8888); Assets.back = graphics.newPixmap("buttons/back.png", PixmapFormat.ARGB8888); Assets.quickGame = graphics.newPixmap("buttons/quickgame.png", PixmapFormat.ARGB8888); Assets.sound = graphics.newPixmap("buttons/sound.png", PixmapFormat.ARGB8888); Assets.nosound = graphics.newPixmap("buttons/nosound.png", PixmapFormat.ARGB8888); Assets.rightArrow = graphics.newPixmap("buttons/r_arrow.png", PixmapFormat.ARGB8888); Assets.leftArrow = graphics.newPixmap("buttons/l_arrow.png", PixmapFormat.ARGB8888); setProgress(45); Assets.skins = graphics.newPixmapsFromFolder("skins",PixmapFormat.ARGB8888); setProgress(50); Assets.attacks = graphics.newPixmapsFromFolder("attacks",PixmapFormat.ARGB8888); Assets.powerups = graphics.newPixmapsFromFolder("powerups",PixmapFormat.ARGB8888); setProgress(65); Assets.wait = graphics.newPixmap("etc/wait.png", PixmapFormat.ARGB8888); Assets.unknownSkin = graphics.newPixmap("etc/unknown.png", PixmapFormat.ARGB8888); Assets.logo = graphics.newPixmap("etc/logo.png", PixmapFormat.ARGB8888); Assets.random = graphics.newPixmap("etc/random.png", PixmapFormat.ARGB8888); Assets.swordsBlack = graphics.newPixmap("etc/swords_black.png", PixmapFormat.ARGB8888); Assets.swordsWhite = graphics.newPixmap("etc/swords_white.png", PixmapFormat.ARGB8888); Assets.sad = graphics.newPixmap("etc/sad.png", PixmapFormat.ARGB8888); Assets.happy = graphics.newPixmap("etc/happy.png", PixmapFormat.ARGB8888); Assets.neutral = graphics.newPixmap("etc/neutral.png", PixmapFormat.ARGB8888); Assets.wait = graphics.newPixmap("etc/wait.png", PixmapFormat.ARGB8888); setProgress(80); Assets.click = androidGame.getAudio().newSound("audio/click.mp3"); Assets.powerupCollision = androidGame.getAudio().newSound("audio/powerupcollision.mp3"); Assets.newPowerup = androidGame.getAudio().newSound("audio/newpowerup.mp3"); Assets.gameCharacterCollision = androidGame.getAudio().newSound("audio/gamecharcollision.mp3"); Assets.attackEnabled = androidGame.getAudio().newSound("audio/attackenabled.mp3"); Assets.attackDisabled = androidGame.getAudio().newSound("audio/attackdisabled.mp3"); setProgress(100); androidGame.setScreen(new MainMenuScreen(androidGame)); } @Override public void pause() { } @Override public void resume() { } @Override public void back() { androidGame.finish(); } }
true
6624bc171fbaa01b5431e2894ecfc17f59908012
Java
dr3116/Maple-Leaf-reading
/project/Maple-Leaf-reading-plus/src/main/java/com/example/service/BookService.java
UTF-8
1,365
1.9375
2
[]
no_license
package com.example.service; import com.example.entity.Book; import com.github.pagehelper.PageInfo; import java.util.Date; import java.util.List; public interface BookService { List<Book> getAllBooks(); List<Book> getAllBooksByNumberOfCollectionsDesc(); List<Book> getAllBooksByNumberOfReadingVplumeDesc(); int insertBook(String bookName, String classification, int readingVolume, int numberOfChapters, Date releaseTime,String bookPhoto,double bookRating,String author,int numberOfCollections,String briefIntroduction); int updateBook(String bookName, String classification, int readingVolume, int numberOfChapters, Date releaseTime,String bookPhoto,double bookRating,String author,int numberOfCollections,String briefIntroduction); int deleteBook(String bookName); String getBooksCount(); List<Book> findBookByBookName(String bookName); Book findBookByOneBookName(String bookName); List<Book> getAllBooksByPageF(int pageNum,int pageSize); PageInfo<Book> getAllBooksByPages(int pageNum, int pageSize); PageInfo<Book> getAllBooksByPagesAndDynamic(int pageNum, int pageSize,String bookName,String author,String classification); PageInfo<Book> getAllBooksByPagesAndBookName(int pageNum, int pageSize,String bookName); List<Book> findBookByManyCondition(String bookName,String classification,String author); }
true
3b34c658f0c65f2679c57d569610e266ee4220e1
Java
fxbp/CMXSI-PROJ2
/DockerService/src/main/java/vps/docker/DockerService/Runnable/CmdRunnable.java
UTF-8
1,800
2.734375
3
[]
no_license
package vps.docker.DockerService.Runnable; import org.springframework.beans.factory.annotation.Value; import vps.docker.DockerService.Instructions.Instruction; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class CmdRunnable implements Runnable { private Instruction _cmd; @Value("${run.debug}") private boolean _debug; public CmdRunnable(Instruction command) { _cmd = command; } @Override public void run() { try { Process p = Runtime.getRuntime().exec(_cmd.getCommand()); p.waitFor(); BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream())); // read the output from the command List<String> output = readBuffer(stdInput,"Here is the standard output of the command:\n"); // read any errors from the attempted command List<String> error = readBuffer(stdError,"Here is the standard error of the command (if any):\n"); _cmd.processResult(output,error,p.exitValue()); } catch (IOException | InterruptedException e) { e.printStackTrace(); } } private List<String> readBuffer(BufferedReader input, String message) throws IOException { if(_debug) System.out.println(message); String s; List<String> result = new ArrayList<>(); while ((s = input.readLine()) != null) { if(_debug) System.out.println(s); result.add(s); } return result; } }
true
1b1377fa7ecf99812832b7805987056123681ba8
Java
smussergey/training
/block06-task-custom-exception/src/main/java/training/controller/Regex.java
UTF-8
253
1.789063
2
[]
no_license
package training.controller; public interface Regex { // Cyrillic String NAME_UKR = "^[А-ЩЬЮЯҐІЇЄ]{1}[а-щьюяґіїє']{1,}$"; // Latin or default String NAME_LAT = "^[A-Z]{1}[a-z]{1,}$"; String LOGIN = "^\\w{0,}$"; }
true
ebc0c5cb85e66ae17323a2caf3fbe8187b8ce69f
Java
yy0/demo
/src/main/java/com/example/demo/config/RedisMQConfig.java
UTF-8
2,077
2.203125
2
[]
no_license
package com.example.demo.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisStandaloneConfiguration; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.listener.ChannelTopic; import org.springframework.data.redis.listener.RedisMessageListenerContainer; import org.springframework.data.redis.listener.adapter.MessageListenerAdapter; /** * Created by wujianjiang on 2019-1-9. */ @Configuration public class RedisMQConfig { @Value("${spring.redis.host}") private String host; @Value("${spring.redis.port}") private int port; @Value("${spring.redis.topic}") private String topic; @Bean public ScanMessageDelegate scanMessageDelegate() { ScanMessageDelegate delegate = new ScanMessageDelegate(); return delegate; } @Bean public MessageListenerAdapter messageListenerAdapter(ScanMessageDelegate delegate) { return new MessageListenerAdapter(delegate, "handleMessage"); } @Bean public RedisMessageListenerContainer scanRedisMessageListenerContainer() { RedisMessageListenerContainer listenerContainer = new RedisMessageListenerContainer(); RedisStandaloneConfiguration standaloneConfig = new RedisStandaloneConfiguration(host, port); JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(standaloneConfig); listenerContainer.setConnectionFactory(jedisConnectionFactory); ScanMessageDelegate delegate = scanMessageDelegate(); MessageListenerAdapter messageListener = messageListenerAdapter(delegate); listenerContainer.addMessageListener(messageListener, new ChannelTopic(topic)); return listenerContainer; } class ScanMessageDelegate { public void handleMessage(String message) { System.out.println(message); } } }
true
2a56e19ab7cf94f44c305f3af5a1b2cfa2790d9d
Java
carincon93/sales-network-linked-lists
/src/FinanceCompany/Program.java
UTF-8
1,629
3.140625
3
[]
no_license
package FinanceCompany; public class Program { public static void main(String[] args) { Seller maria = new Seller("Maria"); Seller luis = new Seller("Luis"); Seller pedro = new Seller("Pedro"); Seller pepito = new Seller("Pepito"); Seller carlitos = new Seller("Carlitos"); Seller fulanito = new Seller("Fulanito"); Seller juan = new Seller("juan"); Seller yenny = new Seller("yenny"); Seller andrea = new Seller("andrea"); carlitos.addSellerAssociated(yenny, yenny.membershipInititalFee, andrea, andrea.membershipInititalFee); pepito.addSellerAssociated(carlitos, carlitos.membershipInititalFee, juan, juan.membershipInititalFee); pedro.addSellerAssociated(pepito, pepito.membershipInititalFee, fulanito, fulanito.membershipInititalFee); maria.addSellerAssociated(luis, luis.membershipInititalFee, pedro, pedro.membershipInititalFee); System.out.println("Maria's balance: " + maria.membershipInititalFee); System.out.println("Smallest balance: " + Math.min(maria.smallestBallance, Math.min(pedro.smallestBallance, Math.min(pepito.smallestBallance, carlitos.smallestBallance)))); System.out.println("Largest balance: " + Math.max(maria.membershipInititalFee, Math.max(pedro.membershipInititalFee, Math.max(pepito.membershipInititalFee, carlitos.membershipInititalFee)))); double totalBalance = maria.membershipInititalFee + pedro.membershipInititalFee + pepito.membershipInititalFee + carlitos.membershipInititalFee; System.out.println("Total balance: " + totalBalance); } }
true
4a8e211b083692b428527494c82d1b9ebc539e9a
Java
titilomt/Projects_CCPuc
/aed03/Colaborador.java
UTF-8
3,117
3.140625
3
[]
no_license
package aed03; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.RandomAccessFile; public class Colaborador implements Registro { protected int codigo; protected String name; protected String email; public Colaborador(int c, String n, String e) { codigo = c; name = n; email = e; } public Colaborador() { codigo = 0; name = ""; email = ""; } public void setCodigo(int c) { codigo = c; } public int getCodigo() { return codigo; } public String toString() { return "\nCódigo...:" + codigo + "\nNome....:" + name + "\nEmail...:" + email; } public final void writeRegistroIndicadorTamanho(RandomAccessFile arq) throws IOException { ByteArrayOutputStream registro = new ByteArrayOutputStream(); DataOutputStream saida = new DataOutputStream( registro ); saida.writeInt(codigo); saida.writeUTF(name); saida.writeUTF(email); byte[] buffer = registro.toByteArray(); short tamanho = (short)buffer.length; arq.writeShort(tamanho); arq.write(buffer); } public final void writeRegistroIndicadorTamanho(DataOutputStream arq) throws IOException { ByteArrayOutputStream registro = new ByteArrayOutputStream(); DataOutputStream saida = new DataOutputStream( registro ); saida.writeInt(codigo); saida.writeUTF(name); saida.writeUTF(email); byte[] buffer = registro.toByteArray(); short tamanho = (short)buffer.length; arq.writeShort(tamanho); arq.write(buffer); } public final void readRegistroIndicadorTamanho(RandomAccessFile arq) throws IOException, ClassNotFoundException { short tamanho = arq.readShort(); byte[] ba = new byte[tamanho]; if(arq.read(ba) != tamanho) throw new IOException("Dados inconsistentes"); ByteArrayInputStream registro = new ByteArrayInputStream(ba); DataInputStream entrada = new DataInputStream(registro); codigo = entrada.readInt(); name = entrada.readUTF(); email = entrada.readUTF(); } public final void readRegistroIndicadorTamanho(DataInputStream arq) throws IOException, ClassNotFoundException { short tamanho = arq.readShort(); byte[] ba = new byte[tamanho]; if(arq.read(ba) != tamanho) throw new IOException("Dados inconsistentes"); ByteArrayInputStream registro = new ByteArrayInputStream(ba); DataInputStream entrada = new DataInputStream(registro); codigo = entrada.readInt(); name = entrada.readUTF(); email = entrada.readUTF(); } public Object clone() throws CloneNotSupportedException{ return super.clone(); } public int compareTo(){ return 1; } }
true
71c93cb16e89fd35a2f787612c4f87e51da44e9d
Java
ArturKorop/AlgorithmsGradle
/src/test/java/com/korartur/firstsession/algorithms3/BeautifulArrangement526Test.java
UTF-8
585
2.53125
3
[]
no_license
package com.korartur.firstsession.algorithms3; import org.junit.Assert; import org.junit.Test; public class BeautifulArrangement526Test { @Test public void test1() { var b = new BeautifulArrangement526(); Assert.assertEquals(2, b.countArrangement(2)); } @Test public void test2() { var b = new BeautifulArrangement526(); Assert.assertEquals(10, b.countArrangement(5)); } @Test public void test3() { var b = new BeautifulArrangement526(); Assert.assertEquals(24679, b.countArrangement(15)); } }
true
b5cbfa9be8e1694024035a3a5fc0953e67b514b9
Java
kabakan/JCollection
/src/com/ocp_8/chapter05Localization/Test14.java
UTF-8
1,266
3.65625
4
[]
no_license
package com.ocp_8.chapter05Localization; import java.time.LocalDate; import java.time.LocalTime; import java.time.ZoneId; import java.time.ZonedDateTime; /** * Created by Kanat KB on 03.10.2017. * <p> * 14. Note that March 13, 2016, is the weekend that we spring forward, and November 6, 2016, * is when we fall back for daylight savings time. Which of the following can fill in the blank * without the code throwing an exception? * <p> * 14. A, C, D. Option B is incorrect because there is no March 40th. Option E is incorrect * because 2017 isn’t a leap year and therefore has no February 29th. Option D is correct * because it is just a regular date and has nothing to do with daylight savings time. Options A * and C are correct because Java is smart enough to adjust for daylight savings time. * <p> * A. LocalDate.of(2016, 3, 13) * B. LocalDate.of(2016, 3, 40) * C. LocalDate.of(2016, 11, 6) * D. LocalDate.of(2016, 11, 7) * E. LocalDate.of(2017, 2, 29) */ public class Test14 { public static void main(String[] args) { ZoneId zone = ZoneId.of("US/Eastern"); LocalDate date = LocalDate.of(2016, 3, 13); LocalTime time1 = LocalTime.of(2, 15); ZonedDateTime a = ZonedDateTime.of(date, time1, zone); } }
true
ad737a82b50bf6e83ec9619e64a22953f750213a
Java
GeraldLima/UCM_TP_Practica-2
/Practica2/src/logica/bytecode/conditionalJumps/IfEq.java
UTF-8
598
2.8125
3
[ "MIT" ]
permissive
package logica.bytecode.conditionalJumps; import logica.bytecode.ByteCode; public class IfEq extends ConditionalJumps{ public IfEq(){ } public IfEq(int j){ super(j); } @Override protected boolean compare(int n1, int n2) { return (n1 == n2); } @Override protected ByteCode parseAux(String string1, String string2) { if(string1.equalsIgnoreCase("IFEQ")){ int param = Integer.parseInt(string2); return new IfEq(param); } return null; } @Override protected String toStringAux() { return "IFEQ"; } }
true
a54fb6f783f47ba9e5edf146e37def166d4b65d5
Java
AKSHARA-T-S-B/javaProject
/CyclePriceCalculator/CyclePricing/TestCycleEstimator.java
UTF-8
32,769
2.578125
3
[]
no_license
package CyclePricing; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyMap; import static org.mockito.Matchers.anyString; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import org.junit.Test; import org.mockito.Mockito; import Model.Cycle; import Model.Components.ChainAssembly.ChainAssembly; import Model.Components.ChainAssembly.FixedGear; import Model.Components.ChainAssembly.Gear3; import Model.Components.ChainAssembly.Gear4; import Model.Components.ChainAssembly.Gear5; import Model.Components.ChainAssembly.Gear6; import Model.Components.ChainAssembly.Gear7; import Model.Components.ChainAssembly.Gear8; import Model.Components.Frame.Aluminium; import Model.Components.Frame.Contilever; import Model.Components.Frame.Diamond; import Model.Components.Frame.Frame; import Model.Components.Frame.Recumbent; import Model.Components.Frame.Steel; import Model.Components.Frame.StepThrough; import Model.Components.Frame.Titanium; import Model.Components.HandleBar.DropBar; import Model.Components.HandleBar.HandleBar; import Model.Components.HandleBar.PursuitBar; import Model.Components.HandleBar.RiserBar; import Model.Components.Seating.ComfortSaddle; import Model.Components.Seating.CruiserSaddle; import Model.Components.Seating.RacingSaddle; import Model.Components.Seating.Seating; import Model.Components.Wheels.Rim; import Model.Components.Wheels.Spokes; import Model.Components.Wheels.Tube; import Model.Components.Wheels.Tyre; import Model.Components.Wheels.Wheels; /** * * @author AKSHARA * */ public class TestCycleEstimator { CycleEstimator cycleEstimator = new CycleEstimator(); Cycle cycle = new Cycle(); BlockingQueue<Map<String, Object>> blockingQueue = new ArrayBlockingQueue<>(10); CyclePriceCalculator cyclePriceCalculator = new CyclePriceCalculator(cycle, blockingQueue); CyclePriceCalculator cyclePriceCalculatorSpy; Map<String, Integer> setCostMap() { Map<String, Integer> costMap = new HashMap<>(); costMap.put("year", 2020); costMap.put("jan", 250); costMap.put("feb", 250); costMap.put("mar", 250); costMap.put("apr", 260); costMap.put("may", 260); costMap.put("jun", 260); costMap.put("jul", 260); costMap.put("aug", 270); costMap.put("sep", 270); costMap.put("oct", 280); costMap.put("nov", 280); costMap.put("dec", 280); return costMap; } /** * testcyclePriceCalculator is to test cyclePriceCalculator */ @Test public void testcyclePriceCalculator() { Map<String, String> cyclePriceMap = new HashMap<>(); cyclePriceMap.put("frame", "1200"); cyclePriceMap.put("seating", "580"); cyclePriceMap.put("wheels", "895"); cyclePriceMap.put("chainAssembly", "800"); cyclePriceMap.put("handleBar", "620"); String expected = "4095"; String actual = cyclePriceCalculator.cyclePriceCalculator(cyclePriceMap); assertEquals(expected, actual); } /** * testGetCurrentYear is to test getCurrentYear() */ @Test public void testGetCurrentYear() { String expected = "2020"; String actual = cyclePriceCalculator.getCurrentYear(); assertEquals(expected, actual); } /** * testGetCurrentMonth is to test getCurrentMonth */ @Test public void testGetCurrentMonth() { String expected = "jul"; String actual = cyclePriceCalculator.getCurrentMonth(); assertEquals(expected, actual); } /** * testCycleBuilder is to test cycleBuilder */ @Test public void testCycleBuilder() { Map<String, Object> cycleMap = new HashMap<>(); cycleMap.put("name", "cycle"); Map<String, String> dateMap = new HashMap<>(); dateMap.put("year", "2020"); dateMap.put("month", "jul"); cycleMap.put("date_of_pricing", dateMap); cycleMap.put("frame", "diamond, steel"); cycleMap.put("wheels", ""); cycleMap.put("chainAssembly", "fixedGear"); cycleMap.put("seating", "comfort"); cycleMap.put("handleBar", "pursuit"); Map<String, Object> cycleMap1 = new HashMap<>(); cycleMap1.put("name", "cycle"); cycleMap.put("wheels", ""); assertEquals(cycleMap.toString(), cyclePriceCalculator.cycleBuilder(cycleMap1).toString()); } /** * testInitialiseSubComponentMap is to test initialiseSubComponentMap */ @Test public void testInitialiseSubComponentMap() { Map<String, Integer> subComponentMap = new HashMap<>(); subComponentMap.put("rate", 0); subComponentMap.put("yearFlag", 0); subComponentMap.put("currentIndex", 0); assertEquals(subComponentMap, cyclePriceCalculator.initialiseSubComponentMap(new HashMap<String, Integer>())); } /** * testFindRate is to test findRate */ @Test public void testFindRate() { Map<String, Integer> subComponentMap = new HashMap<>(); subComponentMap.put("rate", 250); subComponentMap.put("yearFlag", 1); subComponentMap.put("currentIndex", 0); subComponentMap.put("year", 2020); Map<String, Integer> subComponentMap1 = new HashMap<>(); subComponentMap1.put("year", 2020); Map<String, Integer> costMap = new HashMap<>(); costMap.put("jul", 250); Map<String, Integer> subComponentMap2 = cyclePriceCalculator.findRate(subComponentMap1, "2020", "jul", costMap, 0); assertEquals(subComponentMap, subComponentMap2); } /** * testFrameRateCalculator1 is to test frame type diamond in frameRateCalculator */ @SuppressWarnings("unchecked") @Test public void testFrameRateCalculator1() { String expected = "520"; Frame frame = new Frame(); Diamond[] diamond = new Diamond[1]; diamond[0] = new Diamond(); diamond[0].setYear(2020); diamond[0].setCostMap(setCostMap()); frame.setDiamond(diamond); Steel[] steel = new Steel[1]; steel[0] = new Steel(); steel[0].setYear(2020); steel[0].setCostMap(setCostMap()); frame.setSteel(steel); cycle.setFrame(frame); Map<String, Integer> subComponentMap = new HashMap<>(); subComponentMap.put("yearFlag", 1); subComponentMap.put("rate", 520); subComponentMap.put("currentIndex", 0); subComponentMap.put("year", 2020); CyclePriceCalculator cyclePriceCalculator1 = new CyclePriceCalculator(cycle, blockingQueue); CyclePriceCalculator cyclePriceCalculatorSpy = Mockito.spy(cyclePriceCalculator1); Mockito.when(cyclePriceCalculatorSpy.findRate(anyMap(), anyString(), anyString(), anyMap(), anyInt())) .thenReturn(subComponentMap); String actual = cyclePriceCalculatorSpy.frameRateCalculator("diamond, steel", "2020", "jul", cycle); assertEquals(expected, actual); } /** * testFrameRateCalculator2 is to test frame type stepthrough in frameRateCalculator */ @SuppressWarnings("unchecked") @Test public void testFrameRateCalculator2() { String expected = "500"; Frame frame = new Frame(); StepThrough[] stepThrough = new StepThrough[1]; stepThrough[0] = new StepThrough(); stepThrough[0].setYear(2020); stepThrough[0].setCostMap(setCostMap()); frame.setStepThrough(stepThrough); Steel[] steel = new Steel[1]; steel[0] = new Steel(); steel[0].setYear(2020); steel[0].setCostMap(setCostMap()); frame.setSteel(steel); cycle.setFrame(frame); Map<String, Integer> subComponentMap = new HashMap<>(); subComponentMap.put("yearFlag", 1); subComponentMap.put("rate", 500); subComponentMap.put("currentIndex", 0); subComponentMap.put("year", 2020); CyclePriceCalculator cyclePriceCalculator1 = new CyclePriceCalculator(cycle, blockingQueue); CyclePriceCalculator cyclePriceCalculatorSpy = Mockito.spy(cyclePriceCalculator1); Mockito.when(cyclePriceCalculatorSpy.findRate(anyMap(), anyString(), anyString(), anyMap(), anyInt())) .thenReturn(subComponentMap); String actual = cyclePriceCalculatorSpy.frameRateCalculator("stepthrough, steel", "2020", "jul", cycle); assertEquals(expected, actual); } /** * testFrameRateCalculator3 is to test frame type contilever in frameRateCalculator */ @SuppressWarnings("unchecked") @Test public void testFrameRateCalculator3() { String expected = "330"; Frame frame = new Frame(); Contilever[] contilever = new Contilever[1]; contilever[0] = new Contilever(); contilever[0].setYear(2020); contilever[0].setCostMap(setCostMap()); frame.setContilever(contilever); Steel[] steel = new Steel[1]; steel[0] = new Steel(); steel[0].setYear(2020); steel[0].setCostMap(setCostMap()); frame.setSteel(steel); cycle.setFrame(frame); Map<String, Integer> subComponentMap = new HashMap<>(); subComponentMap.put("yearFlag", 1); subComponentMap.put("rate", 330); subComponentMap.put("currentIndex", 0); subComponentMap.put("year", 2020); CyclePriceCalculator cyclePriceCalculator1 = new CyclePriceCalculator(cycle, blockingQueue); CyclePriceCalculator cyclePriceCalculatorSpy = Mockito.spy(cyclePriceCalculator1); Mockito.when(cyclePriceCalculatorSpy.findRate(anyMap(), anyString(), anyString(), anyMap(), anyInt())) .thenReturn(subComponentMap); String actual = cyclePriceCalculatorSpy.frameRateCalculator("contilever, steel", "2020", "jul", cycle); assertEquals(expected, actual); } /** * testFrameRateCalculator4 is to test frame type recumbent in frameRateCalculator */ @SuppressWarnings("unchecked") @Test public void testFrameRateCalculator4() { String expected = "300"; Frame frame = new Frame(); Recumbent[] recumbent = new Recumbent[1]; recumbent[0] = new Recumbent(); recumbent[0].setYear(2020); recumbent[0].setCostMap(setCostMap()); frame.setRecumbent(recumbent); Steel[] steel = new Steel[1]; steel[0] = new Steel(); steel[0].setYear(2020); steel[0].setCostMap(setCostMap()); frame.setSteel(steel); cycle.setFrame(frame); Map<String, Integer> subComponentMap = new HashMap<>(); subComponentMap.put("yearFlag", 1); subComponentMap.put("rate", 300); subComponentMap.put("currentIndex", 0); subComponentMap.put("year", 2020); CyclePriceCalculator cyclePriceCalculator1 = new CyclePriceCalculator(cycle, blockingQueue); CyclePriceCalculator cyclePriceCalculatorSpy = Mockito.spy(cyclePriceCalculator1); Mockito.when(cyclePriceCalculatorSpy.findRate(anyMap(), anyString(), anyString(), anyMap(), anyInt())) .thenReturn(subComponentMap); String actual = cyclePriceCalculatorSpy.frameRateCalculator("recumbent, steel", "2020", "jul", cycle); assertEquals(expected, actual); } /** * testFrameRateCalculator5 is to test frame type titanium in frameRateCalculator */ @SuppressWarnings("unchecked") @Test public void testFrameRateCalculator5() { String expected = "900"; Frame frame = new Frame(); Contilever[] contilever = new Contilever[1]; contilever[0] = new Contilever(); contilever[0].setYear(2020); contilever[0].setCostMap(setCostMap()); frame.setContilever(contilever); Titanium[] titanium = new Titanium[1]; titanium[0] = new Titanium(); titanium[0].setYear(2020); titanium[0].setCostMap(setCostMap()); frame.setTitanium(titanium); cycle.setFrame(frame); Map<String, Integer> subComponentMap = new HashMap<>(); subComponentMap.put("yearFlag", 1); subComponentMap.put("rate", 900); subComponentMap.put("currentIndex", 0); subComponentMap.put("year", 2020); CyclePriceCalculator cyclePriceCalculator1 = new CyclePriceCalculator(cycle, blockingQueue); CyclePriceCalculator cyclePriceCalculatorSpy = Mockito.spy(cyclePriceCalculator1); Mockito.when(cyclePriceCalculatorSpy.findRate(anyMap(), anyString(), anyString(), anyMap(), anyInt())) .thenReturn(subComponentMap); String actual = cyclePriceCalculatorSpy.frameRateCalculator("titanium, contilever", "2020", "jul", cycle); assertEquals(expected, actual); } /** * testFrameRateCalculator6 is to test frame type aluminum in frameRateCalculator */ @SuppressWarnings("unchecked") @Test public void testFrameRateCalculator6() { String expected = "900"; Frame frame = new Frame(); Aluminium[] aluminium = new Aluminium[1]; aluminium[0] = new Aluminium(); aluminium[0].setYear(2020); aluminium[0].setCostMap(setCostMap()); frame.setAluminium(aluminium); Diamond[] diamond = new Diamond[1]; diamond[0] = new Diamond(); diamond[0].setYear(2020); diamond[0].setCostMap(setCostMap()); frame.setDiamond(diamond); cycle.setFrame(frame); Map<String, Integer> subComponentMap = new HashMap<>(); subComponentMap.put("yearFlag", 1); subComponentMap.put("rate", 900); subComponentMap.put("currentIndex", 0); subComponentMap.put("year", 2020); CyclePriceCalculator cyclePriceCalculator1 = new CyclePriceCalculator(cycle, blockingQueue); CyclePriceCalculator cyclePriceCalculatorSpy = Mockito.spy(cyclePriceCalculator1); Mockito.when(cyclePriceCalculatorSpy.findRate(anyMap(), anyString(), anyString(), anyMap(), anyInt())) .thenReturn(subComponentMap); String actual = cyclePriceCalculatorSpy.frameRateCalculator("aluminium, diamond", "2020", "jul", cycle); assertEquals(expected, actual); } /** * testFrameRateCalculator7 is test frame type steel in frameRateCalculator */ @SuppressWarnings("unchecked") @Test public void testFrameRateCalculator7() { String expected = "550"; Frame frame = new Frame(); Recumbent[] recumbent = new Recumbent[1]; recumbent[0] = new Recumbent(); recumbent[0].setYear(2020); recumbent[0].setCostMap(setCostMap()); frame.setRecumbent(recumbent); Steel[] steel = new Steel[1]; steel[0] = new Steel(); steel[0].setYear(2020); steel[0].setCostMap(setCostMap()); frame.setSteel(steel); cycle.setFrame(frame); Map<String, Integer> subComponentMap = new HashMap<>(); subComponentMap.put("yearFlag", 1); subComponentMap.put("rate", 550); subComponentMap.put("currentIndex", 0); subComponentMap.put("year", 2020); CyclePriceCalculator cyclePriceCalculator1 = new CyclePriceCalculator(cycle, blockingQueue); CyclePriceCalculator cyclePriceCalculatorSpy = Mockito.spy(cyclePriceCalculator1); Mockito.when(cyclePriceCalculatorSpy.findRate(anyMap(), anyString(), anyString(), anyMap(), anyInt())) .thenReturn(subComponentMap); String actual = cyclePriceCalculatorSpy.frameRateCalculator("steel, recumbent", "2020", "jul", cycle); assertEquals(expected, actual); } /** * testWheelsRateCalculator1 is test tubesless type of wheels in wheelsRateCalculator */ @Test public void testWheelsRateCalculator1() { String expected = "1650"; Wheels wheels = new Wheels(); Rim[] rim = new Rim[1]; rim[0] = new Rim(); rim[0].setYear(2020); rim[0].setCostMap(setCostMap()); wheels.setRim(rim); Spokes[] spokes = new Spokes[1]; spokes[0] = new Spokes(); spokes[0].setYear(2020); spokes[0].setCostMap(setCostMap()); wheels.setSpokes(spokes); Tube[] tube = new Tube[1]; tube[0] = new Tube(); tube[0].setYear(2020); tube[0].setCostMap(setCostMap()); wheels.setTube(tube); Tyre[] tyre = new Tyre[1]; tyre[0] = new Tyre(); tyre[0].setYear(2020); tyre[0].setCostMap(setCostMap()); wheels.setTyre(tyre); cycle.setWheels(wheels); Map<String, Integer> subComponentMap = new HashMap<>(); subComponentMap.put("yearFlag", 1); subComponentMap.put("rate", 550); subComponentMap.put("currentIndex", 0); subComponentMap.put("year", 2020); CyclePriceCalculator cyclePriceCalculator1 = new CyclePriceCalculator(cycle, blockingQueue); CyclePriceCalculator cyclePriceCalculatorSpy = Mockito.spy(cyclePriceCalculator1); Mockito.when(cyclePriceCalculatorSpy.findRate(anyMap(), anyString(), anyString(), anyMap(), anyInt())) .thenReturn(subComponentMap); String actual = cyclePriceCalculatorSpy.wheelsRateCalculator("tubeless", "2020", "jul", cycle); assertEquals(expected, actual); } /** * testWheelsRateCalculator2 is test rimless type of wheels in wheelsRateCalculator */ @Test public void testWheelsRateCalculator2() { String expected = "1500"; Wheels wheels = new Wheels(); Rim[] rim = new Rim[1]; rim[0] = new Rim(); rim[0].setYear(2020); rim[0].setCostMap(setCostMap()); wheels.setRim(rim); Spokes[] spokes = new Spokes[1]; spokes[0] = new Spokes(); spokes[0].setYear(2020); spokes[0].setCostMap(setCostMap()); wheels.setSpokes(spokes); Tube[] tube = new Tube[1]; tube[0] = new Tube(); tube[0].setYear(2020); tube[0].setCostMap(setCostMap()); wheels.setTube(tube); Tyre[] tyre = new Tyre[1]; tyre[0] = new Tyre(); tyre[0].setYear(2020); tyre[0].setCostMap(setCostMap()); wheels.setTyre(tyre); cycle.setWheels(wheels); Map<String, Integer> subComponentMap = new HashMap<>(); subComponentMap.put("yearFlag", 1); subComponentMap.put("rate", 500); subComponentMap.put("currentIndex", 0); subComponentMap.put("year", 2020); CyclePriceCalculator cyclePriceCalculator1 = new CyclePriceCalculator(cycle, blockingQueue); CyclePriceCalculator cyclePriceCalculatorSpy = Mockito.spy(cyclePriceCalculator1); Mockito.when(cyclePriceCalculatorSpy.findRate(anyMap(), anyString(), anyString(), anyMap(), anyInt())) .thenReturn(subComponentMap); String actual = cyclePriceCalculatorSpy.wheelsRateCalculator("rimless", "2020", "jul", cycle); assertEquals(expected, actual); } /** * testWheelsRateCalculator3 is test spokeless type of wheels in wheelsRateCalculator */ @Test public void testWheelsRateCalculator3() { String expected = "1200"; Wheels wheels = new Wheels(); Rim[] rim = new Rim[1]; rim[0] = new Rim(); rim[0].setYear(2020); rim[0].setCostMap(setCostMap()); wheels.setRim(rim); Spokes[] spokes = new Spokes[1]; spokes[0] = new Spokes(); spokes[0].setYear(2020); spokes[0].setCostMap(setCostMap()); wheels.setSpokes(spokes); Tube[] tube = new Tube[1]; tube[0] = new Tube(); tube[0].setYear(2020); tube[0].setCostMap(setCostMap()); wheels.setTube(tube); Tyre[] tyre = new Tyre[1]; tyre[0] = new Tyre(); tyre[0].setYear(2020); tyre[0].setCostMap(setCostMap()); wheels.setTyre(tyre); cycle.setWheels(wheels); Map<String, Integer> subComponentMap = new HashMap<>(); subComponentMap.put("yearFlag", 1); subComponentMap.put("rate", 400); subComponentMap.put("currentIndex", 0); subComponentMap.put("year", 2020); CyclePriceCalculator cyclePriceCalculator1 = new CyclePriceCalculator(cycle, blockingQueue); CyclePriceCalculator cyclePriceCalculatorSpy = Mockito.spy(cyclePriceCalculator1); Mockito.when(cyclePriceCalculatorSpy.findRate(anyMap(), anyString(), anyString(), anyMap(), anyInt())) .thenReturn(subComponentMap); String actual = cyclePriceCalculatorSpy.wheelsRateCalculator("spokeless", "2020", "jul", cycle); assertEquals(expected, actual); } /** * testChainAssemblyRateCalculator1 is to test fixed gear in chainAssemblyRateCalculator */ @Test public void testChainAssemblyRateCalculator1() { String expected = "520"; ChainAssembly chainAssembly = new ChainAssembly(); FixedGear[] fixed = new FixedGear[1]; fixed[0] = new FixedGear(); fixed[0].setYear(2020); fixed[0].setCostMap(setCostMap()); chainAssembly.setFixedGear(fixed); cycle.setChainAssembly(chainAssembly); Map<String, Integer> subComponentMap = new HashMap<>(); subComponentMap.put("yearFlag", 1); subComponentMap.put("rate", 520); subComponentMap.put("currentIndex", 0); subComponentMap.put("year", 2020); CyclePriceCalculator cyclePriceCalculator1 = new CyclePriceCalculator(cycle, blockingQueue); CyclePriceCalculator cyclePriceCalculatorSpy = Mockito.spy(cyclePriceCalculator1); Mockito.when(cyclePriceCalculatorSpy.findRate(anyMap(), anyString(), anyString(), anyMap(), anyInt())) .thenReturn(subComponentMap); String actual = cyclePriceCalculatorSpy.chainAssemblyRateCalculator("fixed", "2020", "jul", cycle); assertEquals(expected, actual); } /** * testChainAssemblyRateCalculator2 is to test gear3 in chainAssemblyRateCalculator */ @Test public void testChainAssemblyRateCalculator2() { String expected = "600"; ChainAssembly chainAssembly = new ChainAssembly(); Gear3[] gear3 = new Gear3[1]; gear3[0] = new Gear3(); gear3[0].setYear(2020); gear3[0].setCostMap(setCostMap()); chainAssembly.setGear3(gear3); cycle.setChainAssembly(chainAssembly); Map<String, Integer> subComponentMap = new HashMap<>(); subComponentMap.put("yearFlag", 1); subComponentMap.put("rate", 600); subComponentMap.put("currentIndex", 0); subComponentMap.put("year", 2020); CyclePriceCalculator cyclePriceCalculator1 = new CyclePriceCalculator(cycle, blockingQueue); CyclePriceCalculator cyclePriceCalculatorSpy = Mockito.spy(cyclePriceCalculator1); Mockito.when(cyclePriceCalculatorSpy.findRate(anyMap(), anyString(), anyString(), anyMap(), anyInt())) .thenReturn(subComponentMap); String actual = cyclePriceCalculatorSpy.chainAssemblyRateCalculator("gear3", "2020", "jul", cycle); assertEquals(expected, actual); } /** * testChainAssemblyRateCalculator3 is to test gear4 in chainAssemblyRateCalculator */ @Test public void testChainAssemblyRateCalculator3() { String expected = "650"; ChainAssembly chainAssembly = new ChainAssembly(); Gear4[] gear4 = new Gear4[1]; gear4[0] = new Gear4(); gear4[0].setYear(2020); gear4[0].setCostMap(setCostMap()); chainAssembly.setGear4(gear4); cycle.setChainAssembly(chainAssembly); Map<String, Integer> subComponentMap = new HashMap<>(); subComponentMap.put("yearFlag", 1); subComponentMap.put("rate", 650); subComponentMap.put("currentIndex", 0); subComponentMap.put("year", 2020); CyclePriceCalculator cyclePriceCalculator1 = new CyclePriceCalculator(cycle, blockingQueue); CyclePriceCalculator cyclePriceCalculatorSpy = Mockito.spy(cyclePriceCalculator1); Mockito.when(cyclePriceCalculatorSpy.findRate(anyMap(), anyString(), anyString(), anyMap(), anyInt())) .thenReturn(subComponentMap); String actual = cyclePriceCalculatorSpy.chainAssemblyRateCalculator("gear4", "2020", "jul", cycle); assertEquals(expected, actual); } /** * testChainAssemblyRateCalculator4 is to test gear5 in chainAssemblyRateCalculator */ @Test public void testChainAssemblyRateCalculator4() { String expected = "670"; ChainAssembly chainAssembly = new ChainAssembly(); Gear5[] gear5 = new Gear5[1]; gear5[0] = new Gear5(); gear5[0].setYear(2020); gear5[0].setCostMap(setCostMap()); chainAssembly.setGear5(gear5); cycle.setChainAssembly(chainAssembly); Map<String, Integer> subComponentMap = new HashMap<>(); subComponentMap.put("yearFlag", 1); subComponentMap.put("rate", 670); subComponentMap.put("currentIndex", 0); subComponentMap.put("year", 2020); CyclePriceCalculator cyclePriceCalculator1 = new CyclePriceCalculator(cycle, blockingQueue); CyclePriceCalculator cyclePriceCalculatorSpy = Mockito.spy(cyclePriceCalculator1); Mockito.when(cyclePriceCalculatorSpy.findRate(anyMap(), anyString(), anyString(), anyMap(), anyInt())) .thenReturn(subComponentMap); String actual = cyclePriceCalculatorSpy.chainAssemblyRateCalculator("gear5", "2020", "jul", cycle); assertEquals(expected, actual); } /** * testChainAssemblyRateCalculator5 is to test gear6 in chainAssemblyRateCalculator */ @Test public void testChainAssemblyRateCalculator5() { String expected = "680"; ChainAssembly chainAssembly = new ChainAssembly(); Gear6[] gear6 = new Gear6[1]; gear6[0] = new Gear6(); gear6[0].setYear(2020); gear6[0].setCostMap(setCostMap()); chainAssembly.setGear6(gear6); cycle.setChainAssembly(chainAssembly); Map<String, Integer> subComponentMap = new HashMap<>(); subComponentMap.put("yearFlag", 1); subComponentMap.put("rate", 680); subComponentMap.put("currentIndex", 0); subComponentMap.put("year", 2020); CyclePriceCalculator cyclePriceCalculator1 = new CyclePriceCalculator(cycle, blockingQueue); CyclePriceCalculator cyclePriceCalculatorSpy = Mockito.spy(cyclePriceCalculator1); Mockito.when(cyclePriceCalculatorSpy.findRate(anyMap(), anyString(), anyString(), anyMap(), anyInt())) .thenReturn(subComponentMap); String actual = cyclePriceCalculatorSpy.chainAssemblyRateCalculator("gear6", "2020", "jul", cycle); assertEquals(expected, actual); } /** * testChainAssemblyRateCalculator6 is to test gear7 in chainAssemblyRateCalculator */ @Test public void testChainAssemblyRateCalculator6() { String expected = "680"; ChainAssembly chainAssembly = new ChainAssembly(); Gear7[] gear7 = new Gear7[1]; gear7[0] = new Gear7(); gear7[0].setYear(2020); gear7[0].setCostMap(setCostMap()); chainAssembly.setGear7(gear7); cycle.setChainAssembly(chainAssembly); Map<String, Integer> subComponentMap = new HashMap<>(); subComponentMap.put("yearFlag", 1); subComponentMap.put("rate", 680); subComponentMap.put("currentIndex", 0); subComponentMap.put("year", 2020); CyclePriceCalculator cyclePriceCalculator1 = new CyclePriceCalculator(cycle, blockingQueue); CyclePriceCalculator cyclePriceCalculatorSpy = Mockito.spy(cyclePriceCalculator1); Mockito.when(cyclePriceCalculatorSpy.findRate(anyMap(), anyString(), anyString(), anyMap(), anyInt())) .thenReturn(subComponentMap); String actual = cyclePriceCalculatorSpy.chainAssemblyRateCalculator("gear7", "2020", "jul", cycle); assertEquals(expected, actual); } /** * testChainAssemblyRateCalculator7 is to test gear8 in chainAssemblyRateCalculator */ @Test public void testChainAssemblyRateCalculator7() { String expected = "680"; ChainAssembly chainAssembly = new ChainAssembly(); Gear8[] gear8 = new Gear8[1]; gear8[0] = new Gear8(); gear8[0].setYear(2020); gear8[0].setCostMap(setCostMap()); chainAssembly.setGear8(gear8); cycle.setChainAssembly(chainAssembly); Map<String, Integer> subComponentMap = new HashMap<>(); subComponentMap.put("yearFlag", 1); subComponentMap.put("rate", 680); subComponentMap.put("currentIndex", 0); subComponentMap.put("year", 2020); CyclePriceCalculator cyclePriceCalculator1 = new CyclePriceCalculator(cycle, blockingQueue); CyclePriceCalculator cyclePriceCalculatorSpy = Mockito.spy(cyclePriceCalculator1); Mockito.when(cyclePriceCalculatorSpy.findRate(anyMap(), anyString(), anyString(), anyMap(), anyInt())) .thenReturn(subComponentMap); String actual = cyclePriceCalculatorSpy.chainAssemblyRateCalculator("gear8", "2020", "jul", cycle); assertEquals(expected, actual); } /** * testSeatingRateCalculator1 is to test cruiser saddle in seatingRateCalculator */ @Test public void testSeatingRateCalculator1() { String expected = "560"; Seating seating = new Seating(); CruiserSaddle[] cruiser = new CruiserSaddle[1]; cruiser[0] = new CruiserSaddle(); cruiser[0].setYear(2020); cruiser[0].setCostMap(setCostMap()); seating.setCruiserSaddle(cruiser); cycle.setSeating(seating); Map<String, Integer> subComponentMap = new HashMap<>(); subComponentMap.put("yearFlag", 1); subComponentMap.put("rate", 560); subComponentMap.put("currentIndex", 0); subComponentMap.put("year", 2020); CyclePriceCalculator cyclePriceCalculator1 = new CyclePriceCalculator(cycle, blockingQueue); CyclePriceCalculator cyclePriceCalculatorSpy = Mockito.spy(cyclePriceCalculator1); Mockito.when(cyclePriceCalculatorSpy.findRate(anyMap(), anyString(), anyString(), anyMap(), anyInt())) .thenReturn(subComponentMap); String actual = cyclePriceCalculatorSpy.seatingRateCalculator("cruiser", "2020", "jul", cycle); assertEquals(expected, actual); } /** * testSeatingRateCalculator2 is to test racing saddle in seatingRateCalculator */ @Test public void testSeatingRateCalculator2() { String expected = "590"; Seating seating = new Seating(); RacingSaddle[] racing = new RacingSaddle[1]; racing[0] = new RacingSaddle(); racing[0].setYear(2020); racing[0].setCostMap(setCostMap()); seating.setRacingSaddle(racing); cycle.setSeating(seating); Map<String, Integer> subComponentMap = new HashMap<>(); subComponentMap.put("yearFlag", 1); subComponentMap.put("rate", 590); subComponentMap.put("currentIndex", 0); subComponentMap.put("year", 2020); CyclePriceCalculator cyclePriceCalculator1 = new CyclePriceCalculator(cycle, blockingQueue); CyclePriceCalculator cyclePriceCalculatorSpy = Mockito.spy(cyclePriceCalculator1); Mockito.when(cyclePriceCalculatorSpy.findRate(anyMap(), anyString(), anyString(), anyMap(), anyInt())) .thenReturn(subComponentMap); String actual = cyclePriceCalculatorSpy.seatingRateCalculator("racing", "2020", "jul", cycle); assertEquals(expected, actual); } /** * testSeatingRateCalculator3 is to test comfort saddle in seatingRateCalculator */ @Test public void testSeatingRateCalculator3() { String expected = "650"; Seating seating = new Seating(); ComfortSaddle[] comfort = new ComfortSaddle[1]; comfort[0] = new ComfortSaddle(); comfort[0].setYear(2020); comfort[0].setCostMap(setCostMap()); seating.setComfortSaddle(comfort); cycle.setSeating(seating); Map<String, Integer> subComponentMap = new HashMap<>(); subComponentMap.put("yearFlag", 1); subComponentMap.put("rate", 650); subComponentMap.put("currentIndex", 0); subComponentMap.put("year", 2020); CyclePriceCalculator cyclePriceCalculator1 = new CyclePriceCalculator(cycle, blockingQueue); CyclePriceCalculator cyclePriceCalculatorSpy = Mockito.spy(cyclePriceCalculator1); Mockito.when(cyclePriceCalculatorSpy.findRate(anyMap(), anyString(), anyString(), anyMap(), anyInt())) .thenReturn(subComponentMap); String actual = cyclePriceCalculatorSpy.seatingRateCalculator("comfort", "2020", "jul", cycle); assertEquals(expected, actual); } /** * testHandlBarRateCalculator1 is to test drop handle bar in handlBarRateCalculator */ @Test public void testHandlBarRateCalculator1() { String expected = "700"; HandleBar handleBar = new HandleBar(); DropBar[] dropBar = new DropBar[1]; dropBar[0] = new DropBar(); dropBar[0].setYear(2020); dropBar[0].setCostMap(setCostMap()); handleBar.setDropBar(dropBar); cycle.setHandleBar(handleBar); Map<String, Integer> subComponentMap = new HashMap<>(); subComponentMap.put("yearFlag", 1); subComponentMap.put("rate", 700); subComponentMap.put("currentIndex", 0); subComponentMap.put("year", 2020); CyclePriceCalculator cyclePriceCalculator1 = new CyclePriceCalculator(cycle, blockingQueue); CyclePriceCalculator cyclePriceCalculatorSpy = Mockito.spy(cyclePriceCalculator1); Mockito.when(cyclePriceCalculatorSpy.findRate(anyMap(), anyString(), anyString(), anyMap(), anyInt())) .thenReturn(subComponentMap); String actual = cyclePriceCalculatorSpy.handleBarRateCalculator("drop", "2020", "jul", cycle); assertEquals(expected, actual); } /** * testHandlBarRateCalculator2 is to test pursuit handle bar in handlBarRateCalculator */ @Test public void testHandlBarRateCalculator2() { String expected = "700"; HandleBar handleBar = new HandleBar(); PursuitBar[] pursuitBar = new PursuitBar[1]; pursuitBar[0] = new PursuitBar(); pursuitBar[0].setYear(2020); pursuitBar[0].setCostMap(setCostMap()); handleBar.setPursuitBar(pursuitBar); cycle.setHandleBar(handleBar); Map<String, Integer> subComponentMap = new HashMap<>(); subComponentMap.put("yearFlag", 1); subComponentMap.put("rate", 700); subComponentMap.put("currentIndex", 0); subComponentMap.put("year", 2020); CyclePriceCalculator cyclePriceCalculator1 = new CyclePriceCalculator(cycle, blockingQueue); CyclePriceCalculator cyclePriceCalculatorSpy = Mockito.spy(cyclePriceCalculator1); Mockito.when(cyclePriceCalculatorSpy.findRate(anyMap(), anyString(), anyString(), anyMap(), anyInt())) .thenReturn(subComponentMap); String actual = cyclePriceCalculatorSpy.handleBarRateCalculator("pursuit", "2020", "jul", cycle); assertEquals(expected, actual); } /** * testHandlBarRateCalculator3 is to test riser handle bar in handlBarRateCalculator */ @Test public void testHandlBarRateCalculator3() { String expected = "700"; HandleBar handleBar = new HandleBar(); RiserBar[] riserBar = new RiserBar[1]; riserBar[0] = new RiserBar(); riserBar[0].setYear(2020); riserBar[0].setCostMap(setCostMap()); handleBar.setRiserBar(riserBar); cycle.setHandleBar(handleBar); Map<String, Integer> subComponentMap = new HashMap<>(); subComponentMap.put("yearFlag", 1); subComponentMap.put("rate", 700); subComponentMap.put("currentIndex", 0); subComponentMap.put("year", 2020); CyclePriceCalculator cyclePriceCalculator1 = new CyclePriceCalculator(cycle, blockingQueue); CyclePriceCalculator cyclePriceCalculatorSpy = Mockito.spy(cyclePriceCalculator1); Mockito.when(cyclePriceCalculatorSpy.findRate(anyMap(), anyString(), anyString(), anyMap(), anyInt())) .thenReturn(subComponentMap); String actual = cyclePriceCalculatorSpy.handleBarRateCalculator("riser", "2020", "jul", cycle); assertEquals(expected, actual); } }
true
118a79b61b3216814277ac24d7adaaadfdd4b784
Java
rajeev-sudarsan/extensions-with-springboot
/Parent/src/main/java/sh/cyber/parent/business/extension/point/DefaultOrderQuantity.java
UTF-8
395
2.390625
2
[]
no_license
package sh.cyber.parent.business.extension.point; import org.springframework.stereotype.Component; @Component("DefaultOrderQuantity") public class DefaultOrderQuantity implements OrderQuantity { /** * Implementation of method defined in extension point. * @return String with information about invoked method. */ public String getInfo() { return "I am default method"; } }
true
3053af2d42734dbb0914a2f87b6752daf86a259c
Java
polyaxon/sdks
/java/http_client/v1/src/test/java/org/openapitools/client/api/ProjectsV1ApiTest.java
UTF-8
14,599
1.609375
2
[ "Apache-2.0" ]
permissive
/* * Polyaxon SDKs and REST API specification. * * * The version of the OpenAPI document: 2.0.0-rc38 * Contact: [email protected] * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package org.openapitools.client.api; import org.openapitools.client.ApiException; import java.io.File; import org.openapitools.client.model.RuntimeError; import org.openapitools.client.model.V1EntityStageBodyRequest; import org.openapitools.client.model.V1ListActivitiesResponse; import org.openapitools.client.model.V1ListBookmarksResponse; import org.openapitools.client.model.V1ListProjectVersionsResponse; import org.openapitools.client.model.V1ListProjectsResponse; import org.openapitools.client.model.V1Project; import org.openapitools.client.model.V1ProjectSettings; import org.openapitools.client.model.V1ProjectVersion; import org.openapitools.client.model.V1Stage; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * API tests for ProjectsV1Api */ @Disabled public class ProjectsV1ApiTest { private final ProjectsV1Api api = new ProjectsV1Api(); /** * Archive project * * @throws ApiException if the Api call fails */ @Test public void archiveProjectTest() throws ApiException { String owner = null; String name = null; api.archiveProject(owner, name); // TODO: test validations } /** * Bookmark project * * @throws ApiException if the Api call fails */ @Test public void bookmarkProjectTest() throws ApiException { String owner = null; String name = null; api.bookmarkProject(owner, name); // TODO: test validations } /** * Create new project * * @throws ApiException if the Api call fails */ @Test public void createProjectTest() throws ApiException { String owner = null; V1Project body = null; V1Project response = api.createProject(owner, body); // TODO: test validations } /** * Create version * * @throws ApiException if the Api call fails */ @Test public void createVersionTest() throws ApiException { String owner = null; String project = null; String versionKind = null; V1ProjectVersion body = null; V1ProjectVersion response = api.createVersion(owner, project, versionKind, body); // TODO: test validations } /** * Create new artifact version stage * * @throws ApiException if the Api call fails */ @Test public void createVersionStageTest() throws ApiException { String owner = null; String entity = null; String kind = null; String name = null; V1EntityStageBodyRequest body = null; V1Stage response = api.createVersionStage(owner, entity, kind, name, body); // TODO: test validations } /** * Delete project * * @throws ApiException if the Api call fails */ @Test public void deleteProjectTest() throws ApiException { String owner = null; String name = null; api.deleteProject(owner, name); // TODO: test validations } /** * Delete version * * @throws ApiException if the Api call fails */ @Test public void deleteVersionTest() throws ApiException { String owner = null; String entity = null; String kind = null; String name = null; api.deleteVersion(owner, entity, kind, name); // TODO: test validations } /** * Disbale project CI * * @throws ApiException if the Api call fails */ @Test public void disableProjectCITest() throws ApiException { String owner = null; String name = null; api.disableProjectCI(owner, name); // TODO: test validations } /** * Enable project CI * * @throws ApiException if the Api call fails */ @Test public void enableProjectCITest() throws ApiException { String owner = null; String name = null; api.enableProjectCI(owner, name); // TODO: test validations } /** * Get project * * @throws ApiException if the Api call fails */ @Test public void getProjectTest() throws ApiException { String owner = null; String name = null; V1Project response = api.getProject(owner, name); // TODO: test validations } /** * Get project activities * * @throws ApiException if the Api call fails */ @Test public void getProjectActivitiesTest() throws ApiException { String owner = null; String name = null; Integer offset = null; Integer limit = null; String sort = null; String query = null; Boolean bookmarks = null; String mode = null; Boolean noPage = null; V1ListActivitiesResponse response = api.getProjectActivities(owner, name, offset, limit, sort, query, bookmarks, mode, noPage); // TODO: test validations } /** * Get Project settings * * @throws ApiException if the Api call fails */ @Test public void getProjectSettingsTest() throws ApiException { String owner = null; String name = null; V1ProjectSettings response = api.getProjectSettings(owner, name); // TODO: test validations } /** * Get project stats * * @throws ApiException if the Api call fails */ @Test public void getProjectStatsTest() throws ApiException { String owner = null; String name = null; Integer offset = null; Integer limit = null; String sort = null; String query = null; Boolean bookmarks = null; String mode = null; String kind = null; String aggregate = null; String groupby = null; String trunc = null; Object response = api.getProjectStats(owner, name, offset, limit, sort, query, bookmarks, mode, kind, aggregate, groupby, trunc); // TODO: test validations } /** * Get version * * @throws ApiException if the Api call fails */ @Test public void getVersionTest() throws ApiException { String owner = null; String entity = null; String kind = null; String name = null; V1ProjectVersion response = api.getVersion(owner, entity, kind, name); // TODO: test validations } /** * Get version stages * * @throws ApiException if the Api call fails */ @Test public void getVersionStagesTest() throws ApiException { String owner = null; String entity = null; String kind = null; String name = null; V1Stage response = api.getVersionStages(owner, entity, kind, name); // TODO: test validations } /** * List archived projects for user * * @throws ApiException if the Api call fails */ @Test public void listArchivedProjectsTest() throws ApiException { String user = null; Integer offset = null; Integer limit = null; String sort = null; String query = null; Boolean noPage = null; V1ListProjectsResponse response = api.listArchivedProjects(user, offset, limit, sort, query, noPage); // TODO: test validations } /** * List bookmarked projects for user * * @throws ApiException if the Api call fails */ @Test public void listBookmarkedProjectsTest() throws ApiException { String user = null; Integer offset = null; Integer limit = null; String sort = null; String query = null; Boolean noPage = null; V1ListBookmarksResponse response = api.listBookmarkedProjects(user, offset, limit, sort, query, noPage); // TODO: test validations } /** * List project names * * @throws ApiException if the Api call fails */ @Test public void listProjectNamesTest() throws ApiException { String owner = null; Integer offset = null; Integer limit = null; String sort = null; String query = null; Boolean bookmarks = null; String mode = null; Boolean noPage = null; V1ListProjectsResponse response = api.listProjectNames(owner, offset, limit, sort, query, bookmarks, mode, noPage); // TODO: test validations } /** * List projects * * @throws ApiException if the Api call fails */ @Test public void listProjectsTest() throws ApiException { String owner = null; Integer offset = null; Integer limit = null; String sort = null; String query = null; Boolean bookmarks = null; String mode = null; Boolean noPage = null; V1ListProjectsResponse response = api.listProjects(owner, offset, limit, sort, query, bookmarks, mode, noPage); // TODO: test validations } /** * List versions names * * @throws ApiException if the Api call fails */ @Test public void listVersionNamesTest() throws ApiException { String owner = null; String entity = null; String kind = null; Integer offset = null; Integer limit = null; String sort = null; String query = null; Boolean noPage = null; V1ListProjectVersionsResponse response = api.listVersionNames(owner, entity, kind, offset, limit, sort, query, noPage); // TODO: test validations } /** * List versions * * @throws ApiException if the Api call fails */ @Test public void listVersionsTest() throws ApiException { String owner = null; String entity = null; String kind = null; Integer offset = null; Integer limit = null; String sort = null; String query = null; Boolean noPage = null; V1ListProjectVersionsResponse response = api.listVersions(owner, entity, kind, offset, limit, sort, query, noPage); // TODO: test validations } /** * Patch project * * @throws ApiException if the Api call fails */ @Test public void patchProjectTest() throws ApiException { String owner = null; String projectName = null; V1Project body = null; V1Project response = api.patchProject(owner, projectName, body); // TODO: test validations } /** * Patch project settings * * @throws ApiException if the Api call fails */ @Test public void patchProjectSettingsTest() throws ApiException { String owner = null; String project = null; V1ProjectSettings body = null; V1ProjectSettings response = api.patchProjectSettings(owner, project, body); // TODO: test validations } /** * Patch version * * @throws ApiException if the Api call fails */ @Test public void patchVersionTest() throws ApiException { String owner = null; String project = null; String versionKind = null; String versionName = null; V1ProjectVersion body = null; V1ProjectVersion response = api.patchVersion(owner, project, versionKind, versionName, body); // TODO: test validations } /** * Restore project * * @throws ApiException if the Api call fails */ @Test public void restoreProjectTest() throws ApiException { String owner = null; String name = null; api.restoreProject(owner, name); // TODO: test validations } /** * Transfer version * * @throws ApiException if the Api call fails */ @Test public void transferVersionTest() throws ApiException { String owner = null; String project = null; String versionKind = null; String versionName = null; V1ProjectVersion body = null; api.transferVersion(owner, project, versionKind, versionName, body); // TODO: test validations } /** * Unbookmark project * * @throws ApiException if the Api call fails */ @Test public void unbookmarkProjectTest() throws ApiException { String owner = null; String name = null; api.unbookmarkProject(owner, name); // TODO: test validations } /** * Update project * * @throws ApiException if the Api call fails */ @Test public void updateProjectTest() throws ApiException { String owner = null; String projectName = null; V1Project body = null; V1Project response = api.updateProject(owner, projectName, body); // TODO: test validations } /** * Update project settings * * @throws ApiException if the Api call fails */ @Test public void updateProjectSettingsTest() throws ApiException { String owner = null; String project = null; V1ProjectSettings body = null; V1ProjectSettings response = api.updateProjectSettings(owner, project, body); // TODO: test validations } /** * Update version * * @throws ApiException if the Api call fails */ @Test public void updateVersionTest() throws ApiException { String owner = null; String project = null; String versionKind = null; String versionName = null; V1ProjectVersion body = null; V1ProjectVersion response = api.updateVersion(owner, project, versionKind, versionName, body); // TODO: test validations } /** * Upload artifact to a store via project access * * @throws ApiException if the Api call fails */ @Test public void uploadProjectArtifactTest() throws ApiException { String owner = null; String project = null; String uuid = null; File uploadfile = null; String path = null; Boolean overwrite = null; api.uploadProjectArtifact(owner, project, uuid, uploadfile, path, overwrite); // TODO: test validations } }
true
9df1f0fb91770d7d29de2dd42cef4d6778dc47d6
Java
zhongren/work
/src/main/java/com/admin/common/orm/criteria/UpdateCriteria.java
UTF-8
1,166
1.90625
2
[]
no_license
package com.admin.common.orm.criteria; import com.admin.common.orm.condition.Condition; import com.admin.common.orm.condition.UpdateValue; import java.util.List; /** * Created by zr on 2017/8/13. */ public class UpdateCriteria { private Object id; private String tableName; private List<Condition> conditionList; private List<UpdateValue> updateValueList; public String getTableName() { return tableName; } public void setTableName(String tableName) { this.tableName = tableName; } public List<Condition> getConditionList() { return conditionList; } public void setConditionList(List<Condition> conditionList) { this.conditionList = conditionList; } public Object getId() { return id; } public void setId(Object id) { this.id = id; } public UpdateCriteria(String tableName) { this.tableName = tableName; } public List<UpdateValue> getUpdateValueList() { return updateValueList; } public void setUpdateValueList(List<UpdateValue> updateValueList) { this.updateValueList = updateValueList; } }
true
cd6b2d4e2f9ed0f13666f767b77eb1df46174293
Java
JavaMrYang/JavaBasic
/src/com/sun/source/util/AbstractSet.java
UTF-8
1,181
2.875
3
[]
no_license
package com.sun.source.util; import java.util.Objects; public abstract class AbstractSet<E> extends AbstractCollection<E> implements Set<E> { protected AbstractSet() { } public boolean equals(Object o) { if(o==this) return true; if(!(o instanceof Set)) return false; Collection<?> c=(Collection<?>) o; if(c.size()!=this.size()) return false; try { return containsAll(c); } catch (ClassCastException unused) { return false; } catch (NullPointerException unused) { return false; } } public int hashCode() { int h=0; Iterator<E> it=iterator(); while(it.hasNext()) { E e=it.next(); if(e!=null) h+=e.hashCode(); } return h; } public boolean removeAll(Collection<?> c) { Objects.requireNonNull(c); boolean modified=false; if(this.size()>c.size()) { for(Iterator<?> it=this.iterator();it.hasNext();) { modified|=remove(it.next()); } }else { for(Iterator<?> it=iterator();it.hasNext();) { if(c.contains(it.next())) { it.remove(); modified=true; } } } return modified; } }
true
d078689f205cfc3bbd4ae29875b92033a1e7e2c7
Java
Kawser-nerd/CLCDSA
/Source Codes/CodeJamData/15/12/2.java
UTF-8
1,775
3.140625
3
[]
no_license
import java.util.*; import java.io.*; import java.math.*; public class Haircut { final static String PROBLEM_NAME = "haircut"; final static String WORK_DIR = "D:\\GCJ\\" + PROBLEM_NAME + "\\"; void solve(Scanner sc, PrintWriter pw) { int B = sc.nextInt(); long N = sc.nextLong(); int[] T = new int[B]; for (int i = 0; i < B; i++) { T[i] = sc.nextInt(); } long L = 0, R = 1000000000000000L; while (R - L > 1) { long mid = (L + R) / 2; long servedBefore = 0; for (int i = 0; i < B; i++) { servedBefore += (mid - 1) / T[i] + 1; } if (servedBefore < N) { L = mid; } else { R = mid; } } long when = L; for (int i = 0; i < B; i++) { N -= (when - 1) / T[i] + 1; } for (int i = 0; i < B; i++) { if (when % T[i] == 0) { N--; if (N == 0) { pw.println(i + 1); return; } } } } public static void main(String[] args) throws Exception { Scanner sc = new Scanner(new FileReader(WORK_DIR + "input.txt")); PrintWriter pw = new PrintWriter(new FileWriter(WORK_DIR + "output.txt")); int caseCnt = sc.nextInt(); for (int caseNum=0; caseNum<caseCnt; caseNum++) { System.out.println("Processing test case " + (caseNum + 1)); pw.print("Case #" + (caseNum+1) + ": "); new Haircut().solve(sc, pw); } pw.flush(); pw.close(); sc.close(); } }
true
b342f6fb511b7b8380b595e1d8f01926c5701f88
Java
oakproject/paxquery
/paxquery-algebra/src/main/java/fr/inria/oak/paxquery/algebra/operators/unary/GroupBy.java
UTF-8
4,153
2.078125
2
[]
no_license
/******************************************************************************* * Copyright (C) 2013, 2014, 2015 by Inria and Paris-Sud University * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package fr.inria.oak.paxquery.algebra.operators.unary; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import fr.inria.oak.paxquery.algebra.operators.BaseLogicalOperator; import fr.inria.oak.paxquery.common.datamodel.metadata.NestedMetadata; import fr.inria.oak.paxquery.common.datamodel.metadata.NestedMetadataUtils; import fr.inria.oak.paxquery.common.exception.PAXQueryExecutionException; /** * GroupBy logical operator. * */ public class GroupBy extends BaseUnaryOperator { private static final Log logger = LogFactory.getLog(GroupBy.class); private int[] reduceByColumns; private int[] groupByColumns; private int[] nestColumns; /** * * @param child * The child operator * @param groupedColumns * The columns (at top level) that should be packed together in a * group If we need to group together columns which are below the * top level, give also an ancestor path (int[]) as per the * second constructor below * @throws XMLStratosphereExecutionException */ public GroupBy(BaseLogicalOperator child, int[] reduceByColumns, int[] groupByColumns, int[] nestColumns) throws PAXQueryExecutionException { super(child); this.visible = true; this.ownName = "GroupBy"; this.reduceByColumns = reduceByColumns; this.groupByColumns = groupByColumns; this.nestColumns = nestColumns; buildOwnDetails(); } @Override public void buildNRSMD() { for (BaseLogicalOperator op : this.children) op.buildNRSMD(); // We keep only the columns that are useful at the highest level (the // group-by columns, // the aggregation columns and the nested column) final NestedMetadata groupByNRSMD = NestedMetadataUtils .makeProjectRSMD(this.children.get(0).getNRSMD(), this.groupByColumns); final NestedMetadata nestedNRSMD = NestedMetadataUtils.makeProjectRSMD( this.children.get(0).getNRSMD(), this.nestColumns); this.nestedMetadata = NestedMetadataUtils.addNestedField(groupByNRSMD, nestedNRSMD); } public int[] getReduceByColumns() { return this.reduceByColumns; } public int[] getGroupByColumns() { return this.groupByColumns; } public int[] getNestColumns() { return this.nestColumns; } public void setReduceByColumns(int[] reduceByColumns) { this.reduceByColumns = reduceByColumns; } public void setGroupByColumns(int[] groupByColumns) { this.groupByColumns = groupByColumns; } public void setNestColumns(int[] nestColumns) { this.nestColumns = nestColumns; } public void buildOwnDetails() { StringBuffer sb = new StringBuffer(); sb.append("["); if (this.reduceByColumns.length != 0) { sb.append(this.reduceByColumns[0]); for (int i = 1; i < this.reduceByColumns.length; i++) { sb.append(","); sb.append(this.reduceByColumns[i]); } } sb.append("],["); if (this.groupByColumns.length != 0) { sb.append(this.groupByColumns[0]); for (int i = 1; i < this.groupByColumns.length; i++) { sb.append(","); sb.append(this.groupByColumns[i]); } } sb.append("],["); if (this.nestColumns.length != 0) { sb.append(this.nestColumns[0]); for (int i = 1; i < this.nestColumns.length; i++) { sb.append(","); sb.append(this.nestColumns[i]); } } sb.append("]"); this.ownDetails = new String(sb); } }
true
e42ce65804ed7dab7dc5ab61fdc35b366e76ba83
Java
kingLional/Hub
/Hub Essentials/src/me/DevJochem/Hub/listeners/playerhide.java
UTF-8
1,412
2.640625
3
[]
no_license
package me.DevJochem.Hub.listeners; import java.util.ArrayList; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; import me.DevJochem.Hub.Main; public class playerhide implements Listener { ArrayList<String> toggled = new ArrayList<String>(); private Main plugin; public playerhide(Main instance) { plugin = instance; } @EventHandler public void Compass(PlayerInteractEvent e) { if(e.getAction() == Action.RIGHT_CLICK_AIR || e.getAction().equals(Action.RIGHT_CLICK_AIR)) { if (e.getPlayer().getItemInHand().getType().equals(Material.WATCH)) { if(toggled.contains(e.getPlayer().getName())) { toggled.remove(e.getPlayer().getName()); hideAllPlayers(e.getPlayer()); return; } else if(!toggled.contains(e.getPlayer().getName())) { toggled.add(e.getPlayer().getName()); showAllPlayers(e.getPlayer()); return; } } } } public void hideAllPlayers(Player player) { for(Player p : Bukkit.getOnlinePlayers()) { player.hidePlayer(p); } } public void showAllPlayers(Player player) { for(Player p : Bukkit.getOnlinePlayers()) { player.showPlayer(p); } } }
true
dd60a563d97c4d95a3733cdb0fd7a5ea9ed08491
Java
kaajavi/TrackMyCar
/src/com/kaajavi/trackmycar/MainActivity.java
UTF-8
4,100
2.328125
2
[ "Apache-2.0" ]
permissive
package com.kaajavi.trackmycar; /*import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdSize; import com.google.android.gms.ads.AdView; */ import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.EditText; import android.widget.Toast; import android.widget.ToggleButton; import android.widget.Button; public class MainActivity extends Activity { private EditText txtPassword; private ToggleButton btnActivado; private ToggleButton btnActivarSms; private Button btnAccept; //private AdView adView; //private static final String MY_AD_UNIT_ID = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Publicidad // Crear adView. /*adView = new AdView(this); adView.setAdUnitId(MY_AD_UNIT_ID); adView.setAdSize(AdSize.BANNER); // Buscar LinearLayout suponiendo que se le ha asignado // el atributo android:id="@+id/mainLayout". FrameLayout layout = (FrameLayout)findViewById(R.id.adsLayout); // Añadirle adView. layout.addView(adView); // Iniciar una solicitud genérica. AdRequest adRequest = new AdRequest.Builder().build(); // Cargar adView con la solicitud de anuncio. adView.loadAd(adRequest); */ //Cargo texto de clave txtPassword = (EditText) findViewById(R.id.txtClave); //Cargo Botones btnActivado = (ToggleButton) findViewById(R.id.btnActivar); btnActivado.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Config.isPositionActive = btnActivado.isChecked(); btnActivarSms.setEnabled(Config.isPositionActive); btnActivarSms.setChecked(Config.isSmsActive && Config.isPositionActive); btnActivado.setChecked(Config.isPositionActive); writeToFile(); } }); btnActivarSms = (ToggleButton) findViewById(R.id.btnActivarSms); btnActivarSms.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Config.isSmsActive = btnActivarSms.isChecked(); btnActivarSms.setChecked(Config.isSmsActive); writeToFile(); } }); btnAccept = (Button) findViewById(R.id.btnAccept); btnAccept.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Config.code=txtPassword.getText().toString(); writeToFile(); Toast.makeText(getApplicationContext(), "Cambio de Código: " + Config.code, Toast.LENGTH_LONG).show(); } }); //Seteo opciones de visualización predeterminadas readFromFile(); txtPassword.setText(Config.code); btnActivado.setChecked(Config.isPositionActive); btnActivarSms.setChecked(Config.isSmsActive && Config.isPositionActive); btnActivarSms.setEnabled(Config.isPositionActive); } private void writeToFile() { try { SharedPreferences preferencias=getSharedPreferences("datos",Context.MODE_PRIVATE); Editor editor=preferencias.edit(); editor.putBoolean("isPositionActive", Config.isPositionActive); editor.putBoolean("isActive", Config.isSmsActive); editor.putString("code", Config.code); editor.commit(); Toast.makeText(getApplicationContext(), "Se Guardó la configuración", Toast.LENGTH_LONG).show(); } catch (Exception e) { System.out.println("Error: " + e.getLocalizedMessage()); } } private void readFromFile() { try { SharedPreferences preferencias=getSharedPreferences("datos",Context.MODE_PRIVATE); Config.code=preferencias.getString("code", ""); Config.isSmsActive = preferencias.getBoolean("isActive", false); Config.isPositionActive = preferencias.getBoolean("isPositionActive", false); System.out.println(Config.print()); } catch (Exception e) { System.out.println("Error: " + e.getLocalizedMessage()); } } }
true
a53d6e868d4424a43cd9fad0003a68023c03c55c
Java
egreen251/CSC2450
/app/src/main/java/com/mucsc2450/emma/checkbook/BankStatement.java
UTF-8
4,145
2.078125
2
[]
no_license
package com.mucsc2450.emma.checkbook; import android.content.Intent; import android.provider.MediaStore; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; public class BankStatement extends AppCompatActivity { private Button mSendButton, mGoBackButton; private EditText mEmailInput; private String mSubject; private RadioGroup mStatementType; private RadioButton mStatementChecking, mStatementSavings, mStatementTypeButton; private String mMessage = ""; private ListView mListView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_bank_statement); mSendButton = (Button) findViewById(R.id.sendbutton); mGoBackButton = (Button) findViewById(R.id.gobackbutton); mEmailInput = (EditText) findViewById(R.id.emailaddress); mStatementType = (RadioGroup) findViewById(R.id.BankStatementAccount); mStatementChecking = (RadioButton) findViewById(R.id.BankStatementChecking); mStatementSavings = (RadioButton) findViewById(R.id.BankStatementSavings); mSubject = "Bank Statement"; mSendButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int mStatementType_Id = mStatementType.getCheckedRadioButtonId(); mStatementTypeButton = (RadioButton) findViewById(mStatementType_Id); if (mStatementTypeButton == mStatementChecking) { final ArrayList<ListManager> itemList = ListManager.getList(); String[] listItems = new String[ListManager.getInstance().list.size()]; for (int i = 0; i < itemList.size(); i++) { ListManager item = itemList.get(i); mMessage += item.date + " " + item.description + " " + item.type + " $" + item.amount + " $" + item.balance+"\n "; } } if (mStatementTypeButton == mStatementSavings) { final ArrayList<SavingsListManager> savingsitemList = SavingsListManager.getList(); String[] savingslistItems = new String[SavingsListManager.getInstance().list.size()]; for (int i = 0; i < savingsitemList.size(); i++) { SavingsListManager item = savingsitemList.get(i); mMessage += item.date + " " + item.description + " " + item.type + " " + item.amount + " " + item.balance+"\n"; } } Intent i = new Intent(Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(Intent.EXTRA_EMAIL, new String[]{mEmailInput.getText().toString()}); i.putExtra(Intent.EXTRA_SUBJECT, mSubject); i.putExtra(Intent.EXTRA_TEXT, mMessage); if (i.resolveActivity(getPackageManager()) != null) { startActivity(i); finish(); } else { Toast.makeText(BankStatement.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show(); } } }); mGoBackButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i = new Intent(BankStatement.this, HomePage.class); startActivity(i); } }); } }
true
2a99bf3b0015282aa9a8467adb6abdfeddbb9d6b
Java
udaykirand/nuntius
/src/main/java/in/ukd/nuntius/model/AbstractResponse.java
UTF-8
1,287
2.5
2
[]
no_license
package in.ukd.nuntius.model; public abstract class AbstractResponse { protected ResponseStatus status = null; protected String message = null; protected ResponseErrorMessage error = null; protected AbstractResponse() { } protected AbstractResponse(ResponseStatus status, String message) { this.status = status; this.message = message; } protected AbstractResponse(ResponseErrorMessage error) { this.status = ResponseStatus.FAILURE; this.error = error; } protected AbstractResponse(String message) { this.message = message; } protected AbstractResponse(String message, ResponseErrorMessage error) { this.status = ResponseStatus.FAILURE; this.message = message; this.error = error; } public ResponseErrorMessage getError() { return error; } public void setError(ResponseErrorMessage error) { this.error = error; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public ResponseStatus getStatus() { return status; } public void setStatus(ResponseStatus status) { this.status = status; } }
true
f7ef5732108066fe2879249dd2c07f51a6e41949
Java
bmborges/NfeServicesV3
/src/br/com/nfe/util/DtSystem.java
UTF-8
1,026
2.734375
3
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package br.com.nfe.util; import java.text.SimpleDateFormat; import java.util.Date; /** * * @author supervisor */ public class DtSystem { public static void main(String[] args) { DtSystem d = new DtSystem(); System.out.println(d.getdhEvento()); } public static String getDate(){ SimpleDateFormat df = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss"); df.format(new Date(System.currentTimeMillis())); return df.getCalendar().getTime().toString(); } public static String getdhEvento(){ SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ"); //você pode usar outras máscaras Date y = new Date(); String dhEvento = sdf1.format(y); dhEvento = dhEvento.substring(0, 22); dhEvento = dhEvento.replace(" ", "T"); dhEvento = dhEvento+":00"; return dhEvento; } }
true
98231995a5866d19d65d2f51de08fa1e1b1e111e
Java
vigneshsankariyer1234567890/tp
/src/main/java/teletubbies/model/person/Uuid.java
UTF-8
893
3.015625
3
[ "MIT" ]
permissive
package teletubbies.model.person; import static java.util.Objects.requireNonNull; /** * Represents a Person's unique identifier in the address book. * Guarantees: immutable; unique */ public class Uuid { public final String uuid; /** * Constructs a {@code Uuid}. * * @param uuid Person's Uuid. */ public Uuid(String uuid) { requireNonNull(uuid); this.uuid = uuid; } @Override public String toString() { return uuid; } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof teletubbies.model.person.Uuid // instanceof handles nulls && uuid.equals(((teletubbies.model.person.Uuid) other).uuid)); // state check } @Override public int hashCode() { return uuid.hashCode(); } }
true
1bf7e6d1847a9c5f8c833b16c1872b3eff91968b
Java
Ricindigus/VictimizacionApp
/app/src/main/java/pe/gob/inei/victimizacionapp/Residentes.java
UTF-8
198
1.523438
2
[]
no_license
package pe.gob.inei.victimizacionapp; import java.util.ArrayList; /** * Created by RICARDO on 25/06/2017. */ public class Residentes { public static ArrayList<ResidenteHogar> residentes; }
true
24973a874dc26deb560e3749d762c967325cdc69
Java
thkmon/DDOC
/DDOC/src/main/java/com/thkmon/ddoc/doc/read/ReadModel.java
UTF-8
5,271
2.21875
2
[]
no_license
package com.thkmon.ddoc.doc.read; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.thkmon.webstd.common.prototype.BasicMap; import com.thkmon.webstd.common.prototype.BasicMapList; import com.thkmon.webstd.common.prototype.BasicModel; import com.thkmon.webstd.common.util.JsonUtil; import com.thkmon.webstd.common.util.StringUtil; @Controller public class ReadModel extends BasicModel { @RequestMapping(value = "/{userId}/{docId}", method = {RequestMethod.GET, RequestMethod.POST}) public String showReadDocPage(HttpServletRequest req, HttpServletResponse res, @PathVariable("userId") String userId, @PathVariable("docId") String docId) throws Exception { // DB에 붙어서 문서 row를 가져온다. BasicMapList result = new ReadDocController().readDoc(userId, docId); BasicMap oneDoc = result.get(0); oneDoc.setJsonBlackListKey("ip_address"); //System.out.println(oneDoc.toJson()); System.out.println(oneDoc.getKeyListText()); String valid = oneDoc.getString("valid"); if (valid == null || !valid.equals("1")) { throw new Exception("삭제된 문서입니다."); } // 키 목록 : // valid, update_time, regist_time, user_id, user_name, ip_address, title, doc_id, content_src, content // 본문 얻기 // String contentSrc = oneDoc.getString("content_src"); // String content = FileUtil.readFile(UploadUtil.getBasicFolderPath() + "/" + contentSrc); String content = oneDoc.getString("content"); // StringBuffer contentBuffer = new StringBuffer(); // // String oneChar = ""; // boolean open = false; // for (int i=0; i<content.length(); i++) { // oneChar = content.substring(i, i+1); // if (oneChar.equals("<")) { // open = true; // } else if (oneChar.equals(">")) { // open = false; // } // // if (open) // } content = content.replace("<", "&lt;"); content = content.replace(">", "&gt;"); content = content.replace(" ", "&nbsp;"); content = content.replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;"); content = content.replace("'", "&#39;"); // content = content.replace("\"", "&quot;"); content = content.replace("\\", "&#92;"); content = content.replace("&lt;img class", "<img onclick=\"clickedImg(this)\" style=\"max-width: 100%; width: 100%;\" class"); content = content.replace("_jpg\"&gt;", "_jpg\">"); content = content.replace("_jpg&quot;&gt;", "_jpg\">"); // content = content.replace("\"", "22"); // if (false) { //content.indexOf(">") > -1 || content.indexOf("<") > -1) { // // // 태그제거 // String oneChar = ""; // String preChar = ""; // // int contentLen = content.length(); // for (int i=0; i<contentLen; i++) { // oneChar = content.substring(i, i+1); // // // if (!preChar.equals("\\") && (oneChar.equals("<") || oneChar.equals(">"))) { // if (!preChar.equals("\\")) { // // if (oneChar.equals("<")) { // contentBuffer.append("&lt;"); // // } else if (oneChar.equals("<")) { // contentBuffer.append("&gt;"); // // } else { // contentBuffer.append(oneChar); // } // // // } else { // contentBuffer.append(oneChar); // } // // preChar = oneChar; // } // // } else { // contentBuffer.append(content); // } String oneDocJson = oneDoc.toJson("update_time", "regist_time", "user_id", "user_name", "title", "doc_id", "seq_num"); System.out.println("oneDocJson : " + oneDocJson); if (content != null && content.length() > 150) { System.out.println("content : " + StringUtil.toPrintString(content.substring(0, 150) + "...")); } else { System.out.println("content : " + StringUtil.toPrintString(content)); } oneDocJson = JsonUtil.getJsonAddingKeyValue(oneDocJson, "content", content); System.out.println("oneDocJson : " + oneDocJson); // bookId 파라미터로 받기 String paramBookId = req.getParameter("bookId"); if (paramBookId == null || paramBookId.length() == 0) { paramBookId = null; } else if (paramBookId.equalsIgnoreCase("all")) { paramBookId = null; } if (paramBookId != null && paramBookId.length() > 0) { req.setAttribute("bookId", paramBookId); } // 관리자 권한 있는지 체크해서 값을 내려준다. String sessionUserId = String.valueOf(req.getSession().getAttribute("userId")); if (sessionUserId != null && sessionUserId.equals("bb_")) { req.setAttribute("isAdmin", "true"); String modifyLinkText = "/m?docId=" + oneDoc.get("doc_id"); req.setAttribute("isAdmin", "true"); req.setAttribute("modifyLinkText", modifyLinkText); } req.setAttribute("json", oneDocJson); req.setAttribute("docId", oneDoc.get("doc_id")); req.setAttribute("seqNum", oneDoc.get("seq_num")); // forward("/ddoc/read/read.jsp"); return "/ddoc/read/read"; } }
true
dc6678ab4203bb4f18132c72163529e93fbfbaf5
Java
ClawHub/netty-rpc
/src/main/java/com/clawhub/nettyrpc/demo/ApiProvider.java
UTF-8
501
2.234375
2
[]
no_license
package com.clawhub.nettyrpc.demo; import org.springframework.stereotype.Component; /** * <Description>提供者<br> * * @author LiZhiming<br> * @version 1.0<br> * @taskId <br> * @CreateDate 2018/11/9 11:19 <br> */ @Component public class ApiProvider implements Api { @Override public String test(String param) { if ("ok".equals(param)) { return "你的入参是:" + param; } else { return "你要输入“ok”才行!"; } } }
true
6346845dfada6ef7e45f9b8f5077c09005c2d3fa
Java
epochArch/Kuroro
/kuroro-brokerserver/src/main/java/com/epocharch/kuroro/broker/leaderserver/LeaderClient.java
UTF-8
8,522
2.0625
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2017 EpochArch.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.epocharch.kuroro.broker.leaderserver; import com.epocharch.kuroro.common.inner.exceptions.NetException; import java.net.InetSocketAddress; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LeaderClient { private static final Logger LOG = LoggerFactory.getLogger(LeaderClient.class); private final Long DEFAULT_TIMEOUT = 10000L; private ClientBootstrap bootstrap; private Channel channel; private String host; private int port = 20000; private String address; private int connectTimeout = 3000; private String topicName; private volatile boolean active = true; private volatile boolean activeSetable = false; private LeaderClientManager clientManager; private Map<Long, CallbackFuture> requestMap = new ConcurrentHashMap<Long, CallbackFuture>(); //Compensation for asynchronous timeout messageId private ConcurrentHashMap<Long, MessageIDPair> removeTimeOutKeyMap = new ConcurrentHashMap<Long, MessageIDPair>(); public LeaderClient(String host, int port, LeaderClientManager clientManager, String topicName) { this.host = host; this.port = port; this.address = host + ":" + port; this.clientManager = clientManager; clientManager.getCycExecutorService().scheduleWithFixedDelay(new Runnable() { @Override public void run() { try { long now = System.currentTimeMillis(); if (requestMap != null && requestMap.size() > 0) { for (Long key : requestMap.keySet()) { CallbackFuture requestData = requestMap.get(key); if (requestData != null) { // 超时移除 if (requestData.getCreatedMillisTime() + DEFAULT_TIMEOUT < now) { requestMap.remove(key); LOG.warn("remove timeout key:" + key + " topicName:>>> " + requestData.getClient() .getTopicName()); } } } } } catch (Throwable t) { LOG.error(t.getMessage(), t); } } }, 1, 1, TimeUnit.SECONDS); this.topicName = topicName; LOG.info("LeaderClient-Topic-" + topicName + "--->" + host + ":" + port); } public String getTopicName() { return this.topicName; } public synchronized void connect() throws NetException { if (channel != null && channel.isConnected()) { return; } if (bootstrap == null) { this.bootstrap = new ClientBootstrap(clientManager.getNioClientSocketChannelFactory()); this.bootstrap.setPipelineFactory( new LeaderClientPipeLineFactory(this, this.clientManager.getClientResponseThreadPool())); bootstrap.setOption("tcpNoDelay", true); } try { ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); // 等待连接创建成功 if (future.awaitUninterruptibly(this.connectTimeout, TimeUnit.MILLISECONDS)) { if (future.isSuccess()) { LOG.info("Client is conneted to " + this.host + ":" + this.port); } else { LOG.warn("Client is not conneted to " + this.host + ":" + this.port); } } this.channel = future.getChannel(); LOG.info("Channel is " + this.channel.isConnected()); } catch (Exception e) { LOG.error("Connect error", e); } } public MessageIDPair sendTopicConsumer(WrapTopicConsumerIndex topicConsumerIndex) { try { CallbackFuture callback = new CallbackFuture(); callback.setCreatedMillisTime(System.currentTimeMillis()); write(callback, topicConsumerIndex); return callback.get(DEFAULT_TIMEOUT); } catch (NetException e) { LOG.error(e.getMessage(), e); } catch (InterruptedException e) { LOG.error(e.getMessage(), e); } return null; } public MessageIDPair sleepLeaderWork(String topicName) { try { CallbackFuture callback = new CallbackFuture(); callback.setCreatedMillisTime(System.currentTimeMillis()); WrapTopicConsumerIndex topicConsumer = new WrapTopicConsumerIndex(); topicConsumer.setTopicName(topicName); topicConsumer.setCommand("stop"); write(callback, topicConsumer); return callback.get(DEFAULT_TIMEOUT); } catch (NetException e) { LOG.error(e.getMessage(), e); } catch (InterruptedException e) { LOG.error(e.getMessage(), e); } return null; } private synchronized void write(CallbackFuture callback, WrapTopicConsumerIndex topicConsumerIndex) { if (channel == null) { LOG.error("channel:" + null + " ^^^^^^^^^^^^^^"); } else { LOG.debug("Write leader request from {} for topic:" + topicName, channel.getLocalAddress()); WrapTopicConsumerIndex topicConsumer = topicConsumerIndex; topicConsumer.setSquence(LeaderClientManager.sequence.getAndIncrement()); ChannelFuture future = channel.write(topicConsumer); future.addListener(new MsgWriteListener(topicConsumer)); callback.setFuture(future); callback.setClient(this); requestMap.put(topicConsumer.getSquence(), callback); } } public boolean isConnected() { return channel != null && channel.isConnected(); } public boolean isActive() { return active; } public void setActive(boolean active) { if (this.activeSetable) { this.active = active; } } public boolean isActiveSetable() { return activeSetable; } public void setActiveSetable(boolean activeSetable) { this.activeSetable = activeSetable; } public boolean isWritable() { return this.channel.isWritable(); } public String getHost() { return host; } public String getAddress() { return this.address; } public int getPort() { return this.port; } public void doMessageIDPair(MessageIDPair messageIDPair) { CallbackFuture callBack = requestMap.get(messageIDPair.getSequence()); if (callBack != null) { callBack.setMessageIDPair(messageIDPair); callBack.run(); this.requestMap.remove(messageIDPair.getSequence()); } else if (callBack == null && messageIDPair != null) { if (messageIDPair.getMinMessageId() != null && messageIDPair.getMaxMessageId() != null) { removeTimeOutKeyMap.put(messageIDPair.getSequence(), messageIDPair); LOG.warn("put messageIDPair to removeTimeOutKeyMap >>> " + messageIDPair); } } } public Channel getChannel() { return channel; } public boolean equals(Object obj) { if (obj instanceof LeaderClient) { LeaderClient nc = (LeaderClient) obj; return this.address.equals(nc.getAddress()); } else { return super.equals(obj); } } public int hashCode() { return address.hashCode(); } public void close() { if (channel != null && channel.isConnected()) { channel.close(); } LOG.info("Leader is closed"); } public ConcurrentHashMap<Long, MessageIDPair> getRemoveTimeOutKeyMap() { return removeTimeOutKeyMap; } public class MsgWriteListener implements ChannelFutureListener { private WrapTopicConsumerIndex wrapRet; public MsgWriteListener(WrapTopicConsumerIndex msg) { this.wrapRet = msg; } @Override public void operationComplete(ChannelFuture channelfuture) throws Exception { if (channelfuture.isSuccess()) { return; } MessageIDPair pa = new MessageIDPair(); pa.setSequence(wrapRet.getSquence()); pa.setTopicConsumerIndex(wrapRet.getTopicConsumerIndex()); pa.setMaxMessageId(null); pa.setMinMessageId(null); doMessageIDPair(pa); } } }
true
a4634cd00138793c8dd170d21a495719976a003a
Java
IHTSDO/ihtsdo-refset-management-service
/model/src/main/java/org/ihtsdo/otf/refset/MemoryEntry.java
UTF-8
1,728
2.609375
3
[ "Apache-2.0" ]
permissive
/** * Copyright 2015 West Coast Informatics, LLC */ package org.ihtsdo.otf.refset; import org.ihtsdo.otf.refset.helpers.HasId; import org.ihtsdo.otf.refset.helpers.HasName; /** * Represents an entry in a translation memory. This is the name and a frequency * indicator but can be more info in the future. It contains the name from the * language being translated and the name from the translated language. Lucene * searching can be used to findall of the translated names that exactly match a * given name from the origin language. * * Here, the frequency is the frequency of use of this entry (e.g. how many * times is there a concept in the translation where the prase from the origin * language exists and the indicated translation name is also present in the * concept). This has to be computed independently in order to be known - e.g. * by a background process. It could be used to order multiple results. */ public interface MemoryEntry extends HasName, HasId { /** * Returns the translated name. * * @return the translated name */ public String getTranslatedName(); /** * Sets the translated name. * * @param translatedName the translated name */ public void setTranslatedName(String translatedName); /** * Returns the frequency. * * @return the frequency */ public Integer getFrequency(); /** * Sets the frequency. * * @param frequency the frequency */ public void setFrequency(Integer frequency); /** * Returns the PhraseMemory * @return phraseMemory */ public PhraseMemory getPhraseMemory(); /** * Sets the PhraseMemory * @param phraseMemory */ public void setPhraseMemory(PhraseMemory phraseMemory); }
true
9b7e771555b68045f1d34caeb48988f4d222d21f
Java
laiguy00014/Bionime
/app/src/main/java/app/android/com/bionime/view/IAQICellView.java
UTF-8
1,298
1.515625
2
[]
no_license
package app.android.com.bionime.view; import android.view.View; import app.android.com.bionime.bean.DataBean; /** * Created by laiguanyu on 2019/4/19. */ public interface IAQICellView { public void setAllData(DataBean dataBean); public void setSiteName(String SiteName); public void setCounty(String County); public void setAQI(String AQI); public void setPollutant(String Pollutant); public void setStatus(String Status); public void setSO2(String SO2); public void setCO(String CO); public void setCO_8hr(String CO_8hr); public void setO3(String O3); public void setO3_8hr(String O3_8hr); public void setPM10(String PM10); public void setPM25(String PM25); public void setNO2(String NO2); public void setNOx(String NOx); public void setNO(String NO); public void setWindSpeed(String WindSpeed); public void setWindDirec(String WindDirec); public void setPublishTime(String PublishTime); public void setPM25_AVG(String PM25_AVG); public void setPM10_AVG(String PM10_AVG); public void setSO2_AVG(String SO2_AVG); public void setLongitude(String Longitude); public void setLatitude(String Latitude); public void setOnDeleteClick(View.OnClickListener onDeleteClick); }
true
04005274a6de0532a73437e390be66af78ea04b8
Java
davidswinegar/CS308-Springies
/spring13_compsci308_02_springies/src/simulation/listeners/GlobalForceListener.java
UTF-8
582
2.875
3
[]
no_license
package simulation.listeners; import simulation.globalforces.GlobalForce; /** * Listener used to toggle all global forces * * @author David Le * @author David Winegar */ public class GlobalForceListener implements Listener { private GlobalForce myGlobalForce; /** * Construct global force listener * * @param force to modify when triggered */ public GlobalForceListener (GlobalForce force) { myGlobalForce = force; } @Override public void takeAction () { myGlobalForce.toggle(); } }
true
8ab0be7645a0aabb8fddbc2a41fd97b172089e41
Java
ArtemVinokhodov/test_soks_site
/src/main/java/steps/OrdersStep.java
UTF-8
1,355
2.25
2
[]
no_license
package steps; import com.codeborne.selenide.Condition; import elements.MyOrders; import models.AddressBuilder; import org.jsoup.select.Evaluator; public class OrdersStep { MyOrders myOrders = new MyOrders(); AddressBuilder addressBuilder = new AddressBuilder(); public void myOrderStatus() { myOrders.status.should(Condition.exist); } public void viewButtonInOrders(){ myOrders.orderActionViewButton.waitUntil(Condition.visible,10000).click(); } /* public void checkExactHouseNumber() { myOrders.shippingAddressInOrder.shouldHave(Condition.exactText(addressBuilder.getHouseNumber())); //myOrders.shippingAddressInOrder.shouldHave(Condition.exactText(addressBuilder.houseNumber()); }*/ public void checkCompareShippingAddress() { //myOrders.shippingAddressTextInView.getText().contains("12", "asd", "Kyiv", "12123", "123"); //myOrders.shippingAddressTextInView.getText().contains("12 asd Kyiv 12123 123"); myOrders.shippingAddressTextInView.getText().contains("12"); myOrders.shippingAddressTextInView.getText().contains("asd"); myOrders.shippingAddressTextInView.getText().contains("Kyiv3"); myOrders.shippingAddressTextInView.getText().contains("12123"); myOrders.shippingAddressTextInView.getText().contains("123"); } }
true
d1b1affd570e551ec0f3d298ae8f6e45510a9308
Java
Seunghyun0606/lolbody
/back/mongoApi/src/main/java/com/ssafy/lolbody/dto/RankDto.java
UTF-8
1,098
2.640625
3
[]
no_license
package com.ssafy.lolbody.dto; public class RankDto { private String tier; private String rank; private int leaguePoints; private int wins; private int losses; private double winRate; public String getTier() { return tier; } public void setTier(String tier) { this.tier = tier; } public String getRank() { return rank; } public void setRank(String rank) { this.rank = rank; } public int getLeaguePoints() { return leaguePoints; } public void setLeaguePoints(int leaguePoints) { this.leaguePoints = leaguePoints; } public int getWins() { return wins; } public void setWins(int wins) { this.wins = wins; } public int getLosses() { return losses; } public void setLosses(int losses) { this.losses = losses; } public double getWinRate() { return winRate; } public void setWinRate(double winRate) { this.winRate = winRate; } @Override public String toString() { return "RankDto [tier=" + tier + ", rank=" + rank + ", leaguePoints=" + leaguePoints + ", wins=" + wins + ", losses=" + losses + ", winRate=" + winRate + "]"; } }
true
7e8b187ab783216eba2484a8f2d5cc41b608c49b
Java
shnizzedy/SM_openSMILE
/openSMILE_preprocessing/sound-resynthesis/src/ddf/minim/ugens/MoogFilter.java
UTF-8
2,251
2.515625
3
[ "Apache-2.0", "MIT" ]
permissive
package ddf.minim.ugens; import ddf.minim.ugens.UGen; // Moog 24 dB/oct resonant lowpass VCF // References: CSound source code, Stilson/Smith CCRMA paper. // Modified by [email protected] July 2000 // Java implementation by Damien Di Fede September 2010 public class MoogFilter extends UGen { public UGenInput audio; public UGenInput frequency; private float freq; public UGenInput resonance; private float res; private float coeff[][]; // filter buffers (beware denormals!) private float constrain( float number, float min, float max ) { return Math.max( min, Math.min( number, max ) ); } public MoogFilter( float frequencyInHz, float normalizedResonance ) { audio = new UGenInput( InputType.AUDIO ); frequency = new UGenInput( InputType.CONTROL ); resonance = new UGenInput( InputType.CONTROL ); freq = frequencyInHz; res = constrain( normalizedResonance, 0.f, 1.f ); // Working in stereo coeff = new float[2][5]; } protected void uGenerate( float[] channels ) { // Get freq and res from patching if necessary if ( frequency.isPatched() ) { freq = constrain( frequency.getLastValues()[0], 1.0f, (float) ( sampleRate()/2.0 ) ); } if ( resonance.isPatched() ) { res = constrain( resonance.getLastValues()[0], 0.f, 1.f ); } // Set coefficients given frequency & resonance [0.0...1.0] float t1, t2; // temporary buffers float normFreq = freq / ( sampleRate() * 0.5f ); float rez = res; float q = 1.0f - normFreq; float p = normFreq + 0.8f * normFreq * q; float f = p + p - 1.0f; q = rez * ( 1.0f + 0.5f * q * ( 1.0f - q + 5.6f * q * q ) ); if ( audio == null || !audio.isPatched() ) { for ( int i = 0; i < channels.length; i++ ) { channels[i] = 0.0f; } return; } float[] input = audio.getLastValues(); for ( int i = 0; i < channels.length; ++i ) { // Filter (in [-1.0...+1.0]) float[] b = coeff[i]; float in = input[i]; in -= q * b[4]; // feedback t1 = b[1]; b[1] = ( in + b[0] ) * p - b[1] * f; t2 = b[2]; b[2] = ( b[1] + t1 ) * p - b[2] * f; t1 = b[3]; b[3] = ( b[2] + t2 ) * p - b[3] * f; b[4] = ( b[3] + t1 ) * p - b[4] * f; b[4] = b[4] - b[4] * b[4] * b[4] * 0.166667f; // clipping b[0] = in; channels[i] = b[4]; } } }
true
65ad7eefbe0fbe3b4c9660e64ddb9ed56b403f12
Java
SaralaBhadraiah/ashok
/CoreJava/src/com/app/sample/collection/ArrayListDemo.java
UTF-8
856
3.765625
4
[]
no_license
package com.app.sample.collection; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class ArrayListDemo { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("Ashok"); list.add("Naveen"); list.add("Naresh"); list.add("RamyaAsh"); list.add("Ramya"); System.out.println("The List of Strings are "+list); System.out.println("The size of List "+list.size()); list.remove("Ramya"); System.out.println("The List of Strings are "+list); System.out.println("The size of List "+list.size()); /*ArrayList with Iterator*/ Iterator<String> itr = list.iterator(); while(itr.hasNext()) { System.out.println(itr.next()); } /*ArrayList with foreach*/ for(String s:list) { System.out.println("The List of Strings are "+s); } } }
true
93bc10566ca35622a5cfbe50e7da8779f09d6e62
Java
iitsoftware/swiftmq-ce
/swiftlets/sys_streams/src/main/java/com/swiftmq/impl/streams/comp/io/QueueInput.java
UTF-8
5,280
1.929688
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2019 IIT Software GmbH * * IIT Software GmbH licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.swiftmq.impl.streams.comp.io; import com.swiftmq.impl.streams.StreamContext; import com.swiftmq.impl.streams.comp.message.Message; import com.swiftmq.impl.streams.processor.QueueMessageProcessor; import com.swiftmq.mgmt.Entity; import com.swiftmq.mgmt.EntityList; import com.swiftmq.mgmt.EntityRemoveException; import com.swiftmq.ms.MessageSelector; import com.swiftmq.swiftlet.auth.ActiveLogin; import com.swiftmq.swiftlet.queue.QueueReceiver; /** * Consumes Messages from a Queue. * * @author IIT Software GmbH, Muenster/Germany, (c) 2016, All Rights Reserved */ public class QueueInput implements DestinationInput { StreamContext ctx; String name; String destinationName; String selector; Message current; InputCallback callback; QueueMessageProcessor messageProcessor; int msgsProcessed = 0; int totalMsg = 0; Entity usage = null; boolean started = false; QueueInput(StreamContext ctx, String name) { this.ctx = ctx; this.name = name; this.destinationName = name; try { EntityList inputList = (EntityList) ctx.usage.getEntity("inputs"); usage = inputList.createEntity(); usage.setName(name); usage.createCommands(); inputList.addEntity(usage); usage.getProperty("atype").setValue("Queue"); usage.getProperty("destinationname").setValue(destinationName); } catch (Exception e) { e.printStackTrace(); } } public QueueMessageProcessor getMessageProcessor() { return messageProcessor; } public void setMessageProcessor(QueueMessageProcessor messageProcessor) { this.messageProcessor = messageProcessor; } @Override public String getName() { return name; } public String getSelector() { return selector; } public DestinationInput selector(String selector) { this.selector = selector; return this; } @Override public DestinationInput destinationName(String destinationName) { this.destinationName = destinationName; try { usage.getProperty("destinationname").setValue(destinationName); } catch (Exception e) { } return this; } @Override public String destinationName() { return destinationName; } @Override public Input current(Message current) { this.current = current; return this; } @Override public Message current() { return current; } @Override public DestinationInput onInput(InputCallback callback) { this.callback = callback; return this; } @Override public void executeCallback() throws Exception { if (callback != null) { callback.execute(this); } msgsProcessed++; } @Override public void collect(long interval) { if ((long) totalMsg + (long) msgsProcessed > Integer.MAX_VALUE) totalMsg = 0; totalMsg += msgsProcessed; try { usage.getProperty("input-total-processed").setValue(totalMsg); usage.getProperty("input-processing-rate").setValue((int) (msgsProcessed / ((double) interval / 1000.0))); } catch (Exception e) { e.printStackTrace(); } msgsProcessed = 0; } @Override public void start() throws Exception { if (started) return; MessageSelector ms = null; if (selector != null) { ms = new MessageSelector(selector); ms.compile(); } QueueReceiver receiver = ctx.ctx.queueManager.createQueueReceiver(destinationName, (ActiveLogin) null, ms); messageProcessor = new QueueMessageProcessor(ctx, this, receiver, ms); messageProcessor.restart(); started = true; } @Override public void close() { try { if (usage != null) ctx.usage.getEntity("inputs").removeEntity(usage); } catch (EntityRemoveException e) { } if (started) { if (messageProcessor != null) { messageProcessor.deregister(); messageProcessor = null; } started = false; } ctx.stream.removeInput(this); } @Override public String toString() { return "QueueInput{" + "name='" + name + '\'' + ", destinationName='" + destinationName + '\'' + ", selector='" + selector + '\'' + '}'; } }
true
31b3657a2ff1c374fa9ebb98b3652d9c894588a3
Java
Mauperillar/Candy
/src/visualgame/ScorePane.java
UTF-8
1,865
2.8125
3
[]
no_license
package visualgame; import java.awt.GridBagLayout; import java.awt.GridBagConstraints; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JProgressBar; public class ScorePane extends JPanel { /** * */ private static final long serialVersionUID = 1L; private JLabel score, movements, name; private JProgressBar progressBar = new JProgressBar(); ScorePane(){ this.configPane(); this.initComponents(); } private void configPane(){ this.setLayout(new GridBagLayout()); } private void initComponents(){ this.configScorePane(); this.configProgressBar(); this.name = new JLabel("Jugador: Player1"); this.score = new JLabel("Puntaje: 0"); this.movements = new JLabel("Movimientos: 0"); this.add(name, new GridBagConstraints()); this.add(score, new GridBagConstraints()); this.add(movements, new GridBagConstraints()); this.add(this.progressBar, new GridBagConstraints()); } private void configScorePane(){ this.setBackground(new java.awt.Color(204, 255, 255)); java.awt.GridBagLayout scorePaneLayout = new java.awt.GridBagLayout(); scorePaneLayout.rowHeights = new int[] {1, 2, 1}; scorePaneLayout.columnWeights = new double[] {0.2, 0.2, 0.2}; this.setLayout(scorePaneLayout); } private void configProgressBar(){ // } public void setName(String newName){ this.name.setText(newName); } public void setValueScore(int newValue){ this.score.setText("Puntaje: "+newValue); } public void setValueMovements(int newValue){ this.movements.setText("Movimientos: "+newValue); } public void setValueProgressBar(int newValue){ this.progressBar.setValue(newValue); } }
true
95f6ede156ad7911a04bce3af2c8d1f50f51b30a
Java
jisang702/catdog
/catdog/src/main/java/com/sp/catdog/doctor/video/Video.java
UTF-8
2,275
1.929688
2
[]
no_license
package com.sp.catdog.doctor.video; import org.springframework.web.multipart.MultipartFile; public class Video { private int vidNum, listNum; private String userId, userName; private String vidSubject; private String vidCreated; private String vidContent; private String vidUrl; private String vidThumb; private int vidHitCount; private MultipartFile upload;//썸네일 역할 private int vidReplyCount; private int videoLikeCount; public int getVidNum() { return vidNum; } public void setVidNum(int vidNum) { this.vidNum = vidNum; } public int getListNum() { return listNum; } public void setListNum(int listNum) { this.listNum = listNum; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getVidSubject() { return vidSubject; } public void setVidSubject(String vidSubject) { this.vidSubject = vidSubject; } public String getVidCreated() { return vidCreated; } public void setVidCreated(String vidCreated) { this.vidCreated = vidCreated; } public String getVidContent() { return vidContent; } public void setVidContent(String vidContent) { this.vidContent = vidContent; } public String getVidUrl() { return vidUrl; } public void setVidUrl(String vidUrl) { this.vidUrl = vidUrl; } public String getVidThumb() { return vidThumb; } public void setVidThumb(String vidThumb) { this.vidThumb = vidThumb; } public int getVidHitCount() { return vidHitCount; } public void setVidHitCount(int vidHitCount) { this.vidHitCount = vidHitCount; } public MultipartFile getUpload() { return upload; } public void setUpload(MultipartFile upload) { this.upload = upload; } public int getVidReplyCount() { return vidReplyCount; } public void setVidReplyCount(int vidReplyCount) { this.vidReplyCount = vidReplyCount; } public int getVideoLikeCount() { return videoLikeCount; } public void setVideoLikeCount(int videoLikeCount) { this.videoLikeCount = videoLikeCount; } }
true
2bbfce39763a6e294572984de941290a8db6de27
Java
GlowstoneMC/Glowstone
/src/main/java/net/glowstone/block/itemtype/ItemEndCrystal.java
UTF-8
1,261
2.6875
3
[ "MIT" ]
permissive
package net.glowstone.block.itemtype; import net.glowstone.block.GlowBlock; import net.glowstone.entity.GlowPlayer; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.BlockFace; import org.bukkit.entity.EnderCrystal; import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.ItemStack; import org.bukkit.util.Vector; public class ItemEndCrystal extends ItemType { @Override public void rightClickBlock(GlowPlayer player, GlowBlock target, BlockFace face, ItemStack holding, Vector clickedLoc, EquipmentSlot hand) { if (target == null || (target.getType() != Material.BEDROCK && target.getType() != Material.OBSIDIAN)) { return; } Location location = target.getRelative(BlockFace.UP).getLocation(); // Spawn the crystal in the center of the block location.add(0.5, 0, 0.5); EnderCrystal crystal = player.getWorld().spawn(location, EnderCrystal.class); // "Defaults to false when placing by hand [..] // http://minecraft.gamepedia.com/End_Crystal#Data_values crystal.setShowingBottom(false); super.rightClickBlock(player, target, face, holding, clickedLoc, hand); } }
true
423da87748cbecf0bbc2e0b1fd1d3497ed3ef3cd
Java
tingyu/Leetcode
/Subsets II/SubsetsII.java
UTF-8
7,487
3.859375
4
[]
no_license
/** Subsets II Given a collection of integers that might contain duplicates, S, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets. For example, If S = [1,2,2], a solution is: [ [2], [1], [1,2,2], [2,2], [1,2], [] ] */ //a right solution /* 这题解法跟Subset很类似。采用的是iterative的解法 因为要按照递增的顺序排列,所以需要先把原来数组sort下,这样按顺序添加的每个子数组会是递增的 有Duplicates和没有Duplicate的最大的区别体现在两个方面 1, 单个元素的数组:只添加第一次出现,后面出现就不添加 2. 比如如果有[1, 2]后面有相同的时候就不要再加上[1, 2]了。 所以如果是重复的时候,如果给tmp加上res,那么里面有一部分就会重复。比如开始有 1)iteration1: 最后res = [[1]] 2)iteration2: 这次iteration, res全部拷贝给tmp = [[1]], tmp再加上当前的,tmp更新为[[1, 2],[2]]。 这里的tmp加到原来的res中。最后res = [[1], [1, 2], [2]] 3) iteration3: 重复的2出现,如果这次跟上个iteration一样处理。那么就是tmp = [[1], [1, 2], [2]],再分别加上2 那么就会tmp =[[1, 2], [1, 2, 2], [2, 2]]这样和res中的[1, 2]重复了。 所以这种有重复的需要特殊处理。 不重复的时候,是把tmp全部new,然后全部复制res里面所有元素 如果重复的话,那么就处理一下,不要重新copy,就在一次iteration的基础上叠加就行了。 记得在每次iteration之后,都要把tmp里面的元素都加到res里面。然后下一次iteration,根据是否重复来更新或者不变 如何判断是不是重复:if(i == 0 || num[i] != num[i-1]) 最后记得要加上空的情况 */ public class Solution { public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] num) { ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); if(num == null) return res; Arrays.sort(num); ArrayList<ArrayList<Integer>> tmp = new ArrayList<ArrayList<Integer>>(); for(int i = 0; i < num.length; i++){ //get existing sets if(i == 0 || num[i] != num[i-1]){ tmp = new ArrayList<ArrayList<Integer>>(); for(ArrayList<Integer> a: res){ tmp.add(new ArrayList<Integer>(a)); } } //add current number to each element of set for(ArrayList<Integer> a: tmp){ a.add(num[i]); } if(i == 0 || num[i] != num[i-1]){ ArrayList<Integer> t = new ArrayList<Integer>(); t.add(num[i]); tmp.add(t); } //add all set created in this iteration for(ArrayList<Integer> t: tmp){ res.add(new ArrayList<Integer>(t)); } } res.add(new ArrayList<Integer>()); return res; } } public class Solution { //public List<List<Integer>> subsetsWithDup(int[] num) { public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] num) { if(num ==null || num.length ==0) return null; Arrays.sort(num); ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); ArrayList<ArrayList<Integer>> prev = new ArrayList<ArrayList<Integer>>(); for(int i = num.length -1; i >= 0; i--){ //get existing sets //if(i == num.length -1 || num[i] !=num[i+1] || prev.size() == 0){ if(i == num.length -1 || num[i] !=num[i+1]){ prev = new ArrayList<ArrayList<Integer>>(); for(int j = 0; j < result.size(); j++){ prev.add(new ArrayList<Integer>(result.get(j))); } } //add current number to each element of set for(ArrayList<Integer> temp: prev){ temp.add(0, num[i]); } if(i == num.length - 1|| num[i] !=num[i+1]){ ArrayList<Integer> temp = new ArrayList<Integer>(); temp.add(num[i]); prev.add(temp); } //add all set created in this iteration for(ArrayList<Integer> temp: prev){ result.add(new ArrayList<Integer>(temp)); } //result.addAll(prev); this is wrong } result.add(new ArrayList<Integer>()); return result; } } //wrong solution public class Solution { //public List<List<Integer>> subsetsWithDup(int[] num) { public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] num) { if(num == null) return null; Arrays.sort(num); ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); for(int i = 0; i < num.length; i++){ ArrayList<ArrayList<Integer>> temp = new ArrayList<ArrayList<Integer>>(); if(i==0 || (i > 0 && num[i] != num[i-1])){ temp = new ArrayList<ArrayList<Integer>>(); //copy all arraylist in result to temp for(ArrayList<Integer> a: result){ temp.add(new ArrayList<Integer>(a)); } } //append s[i] to the arraylist of temp for(ArrayList<Integer> a: temp){ a.add(num[i]); } //append s[i] to the arraylist of temp for(ArrayList<Integer> a: temp){ a.add(num[i]); } if(i==0 || ( i > 0 && num[i-1]!=num[i])){ //add single num[i] as arraylist ArrayList<Integer> single = new ArrayList<Integer>(); single.add(num[i]); temp.add(single); } result.addAll(temp); } result.add(new ArrayList<Integer>()); return result; } } //another wrong solutionpublic class Solution { public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] num) { ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); if(num == null || num.length == 0) return res; Arrays.sort(num); //ArrayList<ArrayList<Integer>> prev = new int pre = num[0]; for(int i = 0; i < num.length; i++){ ArrayList<ArrayList<Integer>> tmp = new ArrayList<ArrayList<Integer>>(); for(ArrayList<Integer> a: res){ tmp.add(a); } for(ArrayList<Integer> a: tmp){ if(pre != num[i] || a.size() == num.length - 1){ a.add(num[i]); } } if(num[i] != pre){ ArrayList<Integer> single = new ArrayList<Integer>(); single.add(num[i]); tmp.add(single); } pre = num[i]; res.addAll(tmp); } res.add(new ArrayList<Integer>()); return res; } }
true
e22434871b8b8a591a183a7b745f55f7651fde3a
Java
MUKUL47/LOGICS
/Linkedlist/delete.java
UTF-8
570
2.421875
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Linkedlist; import java.util.LinkedList; /** * * @author admin */ public class delete { public static void main(String[] args) { delete d = new delete(); LinkedList<Integer> ll = new LinkedList<>(); int a[]; ll.add(2); ll.add(1); ll.toArray(); System.out.println(ll); } int sort(int ll[]){ } }
true
8d94253b42478b595687c3e84a9fabe79dae62e4
Java
lj790115264/jenkins
/client/src/main/java/com/chinacaring/peixian/patient/client/dto/his/response/price/DataType.java
UTF-8
10,239
1.578125
2
[]
no_license
package com.chinacaring.peixian.patient.client.dto.his.response.price; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>dataType complex type�� Java �ࡣ * * <p>����ģʽƬ��ָ�������ڴ����е�Ԥ�����ݡ� * * <pre> * &lt;complexType name="dataType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="BOARD_STYLE" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="ITEM_NAME"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="�����ͼ�ı���-Y"/> * &lt;enumeration value="������ѧ��Ӱ"/> * &lt;enumeration value="���澭ʳ�ܳ����Ķ�ͼ"/> * &lt;enumeration value="���о�ʳ�ܳ����Ķ�ͼ"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="ITEM_CODE"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="220800008-Y"/> * &lt;enumeration value="220302010"/> * &lt;enumeration value="220600005"/> * &lt;enumeration value="220600006"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="ITEM_PRICE"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="15"/> * &lt;enumeration value="65"/> * &lt;enumeration value="200"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="ITEM_CATEGORY" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="ITEM_MEASURE_UNIT" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="MANUFACTORY" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="INSTRUCTIONS" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="FORMATS"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value=""/> * &lt;enumeration value="����������ѧ��Ӱ"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="REMARK"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="�����۲�B��"/> * &lt;enumeration value=""/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="CREATE_TIME"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="2015/5/30 10:16:05"/> * &lt;enumeration value="2011/7/1 11:09:21"/> * &lt;enumeration value="2011/6/9 14:32:47"/> * &lt;enumeration value="2011/6/9 14:33:17"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "dataType", propOrder = { "boardstyle", "itemname", "itemcode", "itemprice", "itemcategory", "itemmeasureunit", "manufactory", "instructions", "formats", "remark", "createtime" }) public class DataType { @XmlElement(name = "BOARD_STYLE", required = true) protected String boardstyle; @XmlElement(name = "ITEM_NAME", required = true) protected String itemname; @XmlElement(name = "ITEM_CODE", required = true) protected String itemcode; @XmlElement(name = "ITEM_PRICE", required = true) protected String itemprice; @XmlElement(name = "ITEM_CATEGORY", required = true) protected String itemcategory; @XmlElement(name = "ITEM_MEASURE_UNIT", required = true) protected String itemmeasureunit; @XmlElement(name = "MANUFACTORY", required = true) protected String manufactory; @XmlElement(name = "INSTRUCTIONS", required = true) protected String instructions; @XmlElement(name = "FORMATS", required = true) protected String formats; @XmlElement(name = "REMARK", required = true) protected String remark; @XmlElement(name = "CREATE_TIME", required = true) protected String createtime; /** * ��ȡboardstyle���Ե�ֵ�� * * @return * possible object is * {@link String } * */ public String getBOARDSTYLE() { return boardstyle; } /** * ����boardstyle���Ե�ֵ�� * * @param value * allowed object is * {@link String } * */ public void setBOARDSTYLE(String value) { this.boardstyle = value; } /** * ��ȡitemname���Ե�ֵ�� * * @return * possible object is * {@link String } * */ public String getITEMNAME() { return itemname; } /** * ����itemname���Ե�ֵ�� * * @param value * allowed object is * {@link String } * */ public void setITEMNAME(String value) { this.itemname = value; } /** * ��ȡitemcode���Ե�ֵ�� * * @return * possible object is * {@link String } * */ public String getITEMCODE() { return itemcode; } /** * ����itemcode���Ե�ֵ�� * * @param value * allowed object is * {@link String } * */ public void setITEMCODE(String value) { this.itemcode = value; } /** * ��ȡitemprice���Ե�ֵ�� * * @return * possible object is * {@link String } * */ public String getITEMPRICE() { return itemprice; } /** * ����itemprice���Ե�ֵ�� * * @param value * allowed object is * {@link String } * */ public void setITEMPRICE(String value) { this.itemprice = value; } /** * ��ȡitemcategory���Ե�ֵ�� * * @return * possible object is * {@link String } * */ public String getITEMCATEGORY() { return itemcategory; } /** * ����itemcategory���Ե�ֵ�� * * @param value * allowed object is * {@link String } * */ public void setITEMCATEGORY(String value) { this.itemcategory = value; } /** * ��ȡitemmeasureunit���Ե�ֵ�� * * @return * possible object is * {@link String } * */ public String getITEMMEASUREUNIT() { return itemmeasureunit; } /** * ����itemmeasureunit���Ե�ֵ�� * * @param value * allowed object is * {@link String } * */ public void setITEMMEASUREUNIT(String value) { this.itemmeasureunit = value; } /** * ��ȡmanufactory���Ե�ֵ�� * * @return * possible object is * {@link String } * */ public String getMANUFACTORY() { return manufactory; } /** * ����manufactory���Ե�ֵ�� * * @param value * allowed object is * {@link String } * */ public void setMANUFACTORY(String value) { this.manufactory = value; } /** * ��ȡinstructions���Ե�ֵ�� * * @return * possible object is * {@link String } * */ public String getINSTRUCTIONS() { return instructions; } /** * ����instructions���Ե�ֵ�� * * @param value * allowed object is * {@link String } * */ public void setINSTRUCTIONS(String value) { this.instructions = value; } /** * ��ȡformats���Ե�ֵ�� * * @return * possible object is * {@link String } * */ public String getFORMATS() { return formats; } /** * ����formats���Ե�ֵ�� * * @param value * allowed object is * {@link String } * */ public void setFORMATS(String value) { this.formats = value; } /** * ��ȡremark���Ե�ֵ�� * * @return * possible object is * {@link String } * */ public String getREMARK() { return remark; } /** * ����remark���Ե�ֵ�� * * @param value * allowed object is * {@link String } * */ public void setREMARK(String value) { this.remark = value; } /** * ��ȡcreatetime���Ե�ֵ�� * * @return * possible object is * {@link String } * */ public String getCREATETIME() { return createtime; } /** * ����createtime���Ե�ֵ�� * * @param value * allowed object is * {@link String } * */ public void setCREATETIME(String value) { this.createtime = value; } }
true
35fb176624ab30cf2298805db297d2d273abd138
Java
sanjuthomas/marklogic-module-deployer
/src/main/java/org/sanju/ml/deployer/RestExtensionDeployer.java
UTF-8
2,680
2.5625
3
[ "MIT" ]
permissive
package org.sanju.ml.deployer; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Properties; import org.apache.commons.io.FilenameUtils; import org.sanju.ml.payload.RestExtensionPayload; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.marklogic.client.DatabaseClient; import com.marklogic.client.admin.ExtensionMetadata; import com.marklogic.client.admin.MethodType; import com.marklogic.client.admin.ResourceExtensionsManager; import com.marklogic.client.admin.ResourceExtensionsManager.MethodParameters; import com.marklogic.client.io.FileHandle; /** * Deployer implementation to deploy all rest extension files to MarkLogic module database. * * @author Sanju Thomas * */ public class RestExtensionDeployer implements Deployer<RestExtensionPayload>{ private static final Logger logger = LoggerFactory.getLogger(RestExtensionDeployer.class); private final DatabaseClient databaseClient; private final List<RestExtensionPayload> payloads = new ArrayList<>(); /** * Create an instance of the RestExtensionDeployer class. * * @param databaseClient * @param properties * @throws IOException * @see {@link DatabaseClient} * @see {@link Properties} * @see {@link IOException} */ public RestExtensionDeployer(final DatabaseClient databaseClient, final Properties properties) throws IOException{ this.databaseClient = databaseClient; final List<File> files = ModuleUtils.loadAssets(properties.getProperty(ModuleTypes.REST_EXT.getSourceLocation())); files.forEach(file -> this.payloads.add(new RestExtensionPayload(file))); } /** * Deploy a given instance of the RestExtensionPayload into MarkLogic module database. * * @param restExtensionPayload */ @Override public void deploy(final RestExtensionPayload t) { logger.info("Deploying {} ", t.getFile().getName()); final ResourceExtensionsManager resourceExtensionsManager = this.databaseClient.newServerConfigManager().newResourceExtensionsManager(); final File file = t.getFile(); final ExtensionMetadata extensionMetadata = new ExtensionMetadata(); extensionMetadata.setScriptLanguage(t.getScriptLanguage()); resourceExtensionsManager.writeServices(FilenameUtils.removeExtension(file.getName()), new FileHandle(file), extensionMetadata, new MethodParameters(MethodType.PUT)); } /** * Deploy all the instances of the RestExtensionPayload available to the MarkLogic module database. * See the constructor of this class to see how the RestExtensionPayload instances are created. * */ @Override public void deploy() { payloads.forEach(payload -> this.deploy(payload)); } }
true
9ff876ade18fb677c1c345f7d1e297a558615ed9
Java
jcyojr/cyber_ap
/src/com/uc/bs/cyber/batch/txbt5000/Txbt5000_process.java
UHC
4,534
1.875
2
[]
no_license
/** * ֽý۸ : λû ̹ 漼û * : * : * Ŭ ID : Txbt5000.process * ̷ : * ------------------------------------------------------------------------ * ۼ Ҽ Tag * ------------------------------------------------------------------------ * ä 2012.04.27 %01% ۼ */ package com.uc.bs.cyber.batch.txbt5000; import java.util.ArrayList; import org.apache.commons.logging.LogFactory; import org.springframework.context.ApplicationContext; import org.springframework.dao.DuplicateKeyException; import com.uc.bs.cyber.daemon.Codm_BaseProcess; import com.uc.bs.cyber.daemon.Codm_interface; import com.uc.core.MapForm; import com.uc.core.spring.service.UcContextHolder; /** * @author Administrator * */ public class Txbt5000_process extends Codm_BaseProcess implements Codm_interface { private MapForm dataMap = null; private int loop_cnt = 0, insert_cnt = 0, update_cnt = 0, del_cnt = 0; /** * */ public Txbt5000_process() { // TODO Auto-generated constructor stub super(); log = LogFactory.getLog(this.getClass()); } /*Context Կ*/ public void setApp(ApplicationContext context) { this.context = context; } /*μ */ @Override public void runProcess() throws Exception { // TODO Auto-generated method stub /*Ʈ */ mainTransProcess(); } /*Context Կ*/ @Override public void setDatasrc(String datasrc) { // TODO Auto-generated method stub this.dataSource = datasrc; } @Override public void transactionJob() { // TODO Auto-generated method stub txbt5000_JobProcess(); } /*Ʈ ϱ Լ.*/ private void mainTransProcess() { try { setContext(appContext); setApp(appContext); UcContextHolder.setCustomerType(this.dataSource); dataMap = new MapForm(); // ʱȭ dataMap.setMap("SGG_COD", this.c_slf_org); // ûڵ dataMap.setMap("TRN_YN", "0"); // this.startJob(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } /*ڷ */ private int txbt5000_JobProcess() { /* Context DB */ this.context = appContext; UcContextHolder.setCustomerType(this.dataSource); log.info("====================================================================="); log.info("=" + this.getClass().getName()+ " txbt5000_JobProcess() [漼 ȯޱ ó LOG] Start ="); log.info("= govid["+this.govId+"], orgcd["+this.c_slf_org+"], orgcd["+this.c_slf_org_nm+"]"); log.info("====================================================================="); int LevyCnt = 0; loop_cnt = 0; insert_cnt = 0; update_cnt = 0; del_cnt = 0; MapForm mpSupplyingList = new MapForm(); try { ArrayList<MapForm> alFixedLevyList = govService.queryForList("TXBT5000.select_supplying_list", dataMap); LevyCnt = alFixedLevyList.size(); if (LevyCnt > 0) { for (int i = 0; i < LevyCnt; i++) { mpSupplyingList = alFixedLevyList.get(i); if (mpSupplyingList == null || mpSupplyingList.isEmpty()) { continue; } loop_cnt++; /* ó */ if (mpSupplyingList.getMap("CHG_TYPE").equals("3")) { if (cyberService.queryForUpdate("TXBT5000.delete_tx4111_tb", mpSupplyingList) > 0) { del_cnt++; } } else { try { cyberService.queryForInsert("TXBT5000.insert_tx4111_tb", mpSupplyingList); insert_cnt++; } catch (Exception e) { if (e instanceof DuplicateKeyException) { cyberService.queryForUpdate("TXBT5000.update_tx4111_tb", mpSupplyingList); update_cnt++; } else { log.info("߻ = " + mpSupplyingList.getMaps()); //e.printStackTrace(); //throw (RuntimeException) e; continue; } } } govService.queryForUpdate("TXBT5000.update_complete", mpSupplyingList); } } log.info("ѰǼ= [" + loop_cnt + "]"); } catch (Exception e) { e.printStackTrace(); } return LevyCnt; } }
true
55cbc471373f86d72288f81160745ab34b3b403a
Java
ScottSmalley/PunnettMe
/src/punnettme/PunnettMeGUI.java
UTF-8
74,031
2.75
3
[]
no_license
/** * Punnett Me is an app to use for Punnett Squares for Genetic Trait Calculations. * You can calculate up to 5 different traits at once. * You can quickly change from Homozygous parents and Heterozygous parents * for comparisons. * * Uses Design by Contract programming style. * * Scott Smalley, BS Software Engineering student at Utah Valley University * Fall 2020 expected graduation * [email protected] * * @author Scott Smalley */ package punnettme; import javax.swing.JFrame; import java.awt.GridBagLayout; import javax.swing.JPanel; import java.awt.GridBagConstraints; import java.awt.Color; import java.awt.Font; import java.awt.Insets; import javax.swing.AbstractButton; import javax.swing.ButtonGroup; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.plaf.ColorUIResource; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JButton; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import javax.swing.JTextArea; import java.awt.Dimension; import javax.swing.JComboBox; public class PunnettMeGUI implements Runnable, MouseListener, ItemListener { //*********** GUI Globals *********** private JFrame window; /* *Variable Breakdown: *geneOne = Gene One *POne = Parent One *Combo = drop down menu(JComboBox<String>) *Rad = Radio Button(JRadioButton) for each allele type *BG = ButtonGroup (Radio Buttons only) *HomoD = Homozygous Dominant (Gene trait) *Hetero = Heterozygous(Gene trait) *HomoR = Homozygous Recessive (Gene trait) */ //Parent One - JComboBox to select the letter //to represent the gene. private JComboBox<String> geneOnePOneCombo; private JComboBox<String> geneTwoPOneCombo; private JComboBox<String> geneThreePOneCombo; private JComboBox<String> geneFourPOneCombo; private JComboBox<String> geneFivePOneCombo; //Parent One Gene Labels private JLabel geneTwoPOneLabel; private JLabel geneThreePOneLabel; private JLabel geneFourPOneLabel; private JLabel geneFivePOneLabel; //Parent One ButtonGroups for JRadioButtons //representing Allele types (AA, Aa, aa) private ButtonGroup geneOnePOneBG; private ButtonGroup geneTwoPOneBG; private ButtonGroup geneThreePOneBG; private ButtonGroup geneFourPOneBG; private ButtonGroup geneFivePOneBG; //Parent One each JRadioButton that //will be added to the corresponding //ButtonGroup above. private JRadioButton geneOnePOneRadHomoD; private JRadioButton geneOnePOneRadHetero; private JRadioButton geneOnePOneRadHomoR; private JRadioButton geneTwoPOneRadHomoD; private JRadioButton geneTwoPOneRadHetero; private JRadioButton geneTwoPOneRadHomoR; private JRadioButton geneThreePOneRadHomoD; private JRadioButton geneThreePOneRadHetero; private JRadioButton geneThreePOneRadHomoR; private JRadioButton geneFourPOneRadHomoD; private JRadioButton geneFourPOneRadHetero; private JRadioButton geneFourPOneRadHomoR; private JRadioButton geneFivePOneRadHomoD; private JRadioButton geneFivePOneRadHetero; private JRadioButton geneFivePOneRadHomoR; //Parent Two - JComboBox to select the letter //to represent the gene. private JComboBox<String> geneOnePTwoCombo; private JComboBox<String> geneTwoPTwoCombo; private JComboBox<String> geneThreePTwoCombo; private JComboBox<String> geneFourPTwoCombo; private JComboBox<String> geneFivePTwoCombo; //Parent Two Gene Labels private JLabel geneOnePTwoLabel; private JLabel geneTwoPTwoLabel; private JLabel geneThreePTwoLabel; private JLabel geneFourPTwoLabel; private JLabel geneFivePTwoLabel; //Parent One ButtonGroups for JRadioButtons //representing Allele types (AA, Aa, aa) private ButtonGroup geneOnePTwoBG; private ButtonGroup geneTwoPTwoBG; private ButtonGroup geneThreePTwoBG; private ButtonGroup geneFourPTwoBG; private ButtonGroup geneFivePTwoBG; //Parent One each JRadioButton that //will be added to the corresponding //ButtonGroup above. private JRadioButton geneOnePTwoRadHomoD; private JRadioButton geneOnePTwoRadHetero; private JRadioButton geneOnePTwoRadHomoR; private JRadioButton geneTwoPTwoRadHomoD; private JRadioButton geneTwoPTwoRadHetero; private JRadioButton geneTwoPTwoRadHomoR; private JRadioButton geneThreePTwoRadHomoD; private JRadioButton geneThreePTwoRadHetero; private JRadioButton geneThreePTwoRadHomoR; private JRadioButton geneFourPTwoRadHomoD; private JRadioButton geneFourPTwoRadHetero; private JRadioButton geneFourPTwoRadHomoR; private JRadioButton geneFivePTwoRadHomoD; private JRadioButton geneFivePTwoRadHetero; private JRadioButton geneFivePTwoRadHomoR; //List of JComboBoxes for each Parent. //List of ParentOne and ParentTwo Labels. //List of ButtonGroups for ParentOne and ParentTwo. private List<JComboBox<String>> comboBoxPOneList; private List<JComboBox<String>> comboBoxPTwoList; private List<JLabel> geneLabelList; private List<ButtonGroup> buttonGroupList; //Parent One and Two Buttons for initiating Calculations //and resetting the JComboBoxes, JRadioButtons, JLabels, //and the results JTextArea. private JButton resetButton; private JButton calcButton; //Results private JPanel resultsPanel; private JTextArea resultsJTA; // //Default GUI Colors // private Color textColor = Color.decode("#E3E7FF"); // private Color backgroundColor = Color.decode("#404047"); // private Color textFieldColor = Color.decode("#837676"); //Default GUI Colors private Color textColor = Color.decode("#DCDDD8"); private Color backgroundColor = Color.decode("#354B5E"); private Color textFieldColor = Color.decode("#475F77"); private Color disabledColor = Color.decode("#D74B4B"); // //Default GUI Colors // private Color textColor = Color.WHITE; // private Color backgroundColor = Color.DARK_GRAY; // private Color textFieldColor = Color.GRAY; //JComboBoxes options. private String[] geneOptions = {"Select Symbol","A","B","C","D","E", "F","G","H","I","J","K", "L","M","N","O","P","Q", "R","S","T","U","V","W", "X","Y","Z"}; private String defaultComboItem = "Select Symbol"; //*PunnettMe Globals private PunnettMeCalculations pm; //Debug Switch private boolean inDebugMode = false; public static void main (String[] args) { SwingUtilities.invokeLater(new PunnettMeGUI()); } //Outward facing run method for calling private start method. public void run() { start(); } /** * Builds the GUI. Initializes the PunnettMe Object and * ArrayLists. * * GUI variable layout breakdown: * Ex: geneOnePOneLabel * * geneOne = First Gene identifier * POne = Parent One identifier * Label == Description of the Object */ private void start() { //*********** PunnettMe Code init *********** pm = new PunnettMeCalculations(); comboBoxPOneList = new ArrayList<>(); comboBoxPTwoList = new ArrayList<>(); geneLabelList = new ArrayList<>(); buttonGroupList = new ArrayList<>(); //*********** GUI START *********** //Window window = new JFrame(); window.setBackground(Color.DARK_GRAY); window.setTitle("PunnettMe"); window.setBounds(100, 100, 800, 600); window.setMinimumSize(new Dimension(825, 600)); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); GridBagLayout gridBagLayout = new GridBagLayout(); gridBagLayout.columnWidths = new int[]{0, 0}; gridBagLayout.rowHeights = new int[]{0, 0, 0}; gridBagLayout.columnWeights = new double[]{1.0, Double.MIN_VALUE}; gridBagLayout.rowWeights = new double[]{1.0, 1.0, Double.MIN_VALUE}; window.getContentPane().setLayout(gridBagLayout); //Main Content Panel (includes everything) JPanel content = new JPanel(); content.setBackground(backgroundColor); content.setForeground(textColor); GridBagConstraints gbc_content = new GridBagConstraints(); gbc_content.fill = GridBagConstraints.BOTH; gbc_content.gridwidth = 0; gbc_content.gridheight = 0; gbc_content.weighty = 1.0; gbc_content.weightx = 1.0; gbc_content.gridx = 0; gbc_content.gridy = 0; window.getContentPane().add(content, gbc_content); GridBagLayout gbl_content = new GridBagLayout(); gbl_content.columnWidths = new int[]{196, 196, 196, 0}; gbl_content.rowHeights = new int[]{547, 0}; gbl_content.columnWeights = new double[]{0.0, 0.0, 0.0, Double.MIN_VALUE}; gbl_content.rowWeights = new double[]{0.0, Double.MIN_VALUE}; content.setLayout(gbl_content); //Parent One Column JPanel parentOnePanel = new JPanel(); parentOnePanel.setBackground(backgroundColor); parentOnePanel.setForeground(backgroundColor); GridBagConstraints gbc_parentOne = new GridBagConstraints(); gbc_parentOne.insets = new Insets(0, 5, 0, 0); gbc_parentOne.weighty = 1.0; gbc_parentOne.weightx = 0.2; gbc_parentOne.fill = GridBagConstraints.BOTH; gbc_parentOne.gridx = 0; gbc_parentOne.gridy = 0; content.add(parentOnePanel, gbc_parentOne); GridBagLayout gbl_parentOne = new GridBagLayout(); gbl_parentOne.columnWidths = new int[]{0, 0, 0, 0, 0}; gbl_parentOne.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; gbl_parentOne.columnWeights = new double[]{1.0, 1.0, 0.0, 0.0, Double.MIN_VALUE}; gbl_parentOne.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE}; parentOnePanel.setLayout(gbl_parentOne); //Parent One Label JLabel parentOneLabel = new JLabel("Parent One"); parentOneLabel.setHorizontalAlignment(SwingConstants.CENTER); parentOneLabel.setBackground(backgroundColor); parentOneLabel.setForeground(textColor); GridBagConstraints gbc_parentOneLabel = new GridBagConstraints(); gbc_parentOneLabel.anchor = GridBagConstraints.NORTH; gbc_parentOneLabel.gridwidth = 4; gbc_parentOneLabel.insets = new Insets(0, 0, 5, 0); gbc_parentOneLabel.weightx = 1.0; gbc_parentOneLabel.fill = GridBagConstraints.BOTH; gbc_parentOneLabel.gridx = 0; gbc_parentOneLabel.gridy = 0; parentOnePanel.add(parentOneLabel, gbc_parentOneLabel); //Gene One Parent One Label JLabel geneOnePOneLabel = new JLabel("Gene 1"); geneOnePOneLabel.setHorizontalAlignment(SwingConstants.CENTER); geneOnePOneLabel.setBackground(backgroundColor); geneOnePOneLabel.setForeground(textColor); GridBagConstraints gbc_geneOnePOneLabel = new GridBagConstraints(); gbc_geneOnePOneLabel.gridwidth = 4; gbc_geneOnePOneLabel.insets = new Insets(0, 0, 5, 0); gbc_geneOnePOneLabel.weightx = 1.0; gbc_geneOnePOneLabel.fill = GridBagConstraints.BOTH; gbc_geneOnePOneLabel.gridx = 0; gbc_geneOnePOneLabel.gridy = 2; parentOnePanel.add(geneOnePOneLabel, gbc_geneOnePOneLabel); //Gene One Parent One Combo geneOnePOneCombo = new JComboBox<String>(); geneOnePOneCombo.setMaximumRowCount(26); for (int init = 0; init < geneOptions.length; init++) { geneOnePOneCombo.addItem(geneOptions[init]); } geneOnePOneCombo.setBackground(textFieldColor); geneOnePOneCombo.setForeground(textColor); geneOnePOneCombo.addItemListener(this); comboBoxPOneList.add(geneOnePOneCombo); GridBagConstraints gbc_geneOnePOneCombo = new GridBagConstraints(); gbc_geneOnePOneCombo.insets = new Insets(0, 0, 5, 5); gbc_geneOnePOneCombo.weightx = 0.25; gbc_geneOnePOneCombo.fill = GridBagConstraints.BOTH; gbc_geneOnePOneCombo.gridx = 0; gbc_geneOnePOneCombo.gridy = 3; parentOnePanel.add(geneOnePOneCombo, gbc_geneOnePOneCombo); //Gene One Parent One Radio HomoD geneOnePOneRadHomoD = new JRadioButton("AA"); geneOnePOneRadHomoD.setHorizontalAlignment(SwingConstants.CENTER); geneOnePOneRadHomoD.setBackground(backgroundColor); geneOnePOneRadHomoD.setForeground(textColor); geneOnePOneRadHomoD.setEnabled(inDebugMode); GridBagConstraints gbc_geneOnePOneRadHomoD = new GridBagConstraints(); gbc_geneOnePOneRadHomoD.insets = new Insets(0, 0, 5, 5); gbc_geneOnePOneRadHomoD.weightx = 0.25; gbc_geneOnePOneRadHomoD.fill = GridBagConstraints.BOTH; gbc_geneOnePOneRadHomoD.gridx = 1; gbc_geneOnePOneRadHomoD.gridy = 3; parentOnePanel.add(geneOnePOneRadHomoD, gbc_geneOnePOneRadHomoD); //Gene One Parent One Radio Hetero geneOnePOneRadHetero = new JRadioButton("Aa"); geneOnePOneRadHetero.setHorizontalAlignment(SwingConstants.CENTER); geneOnePOneRadHetero.setBackground(backgroundColor); geneOnePOneRadHetero.setForeground(textColor); geneOnePOneRadHetero.setEnabled(inDebugMode); GridBagConstraints gbc_geneOnePOneRadHetero = new GridBagConstraints(); gbc_geneOnePOneRadHetero.insets = new Insets(0, 0, 5, 5); gbc_geneOnePOneRadHetero.weightx = 0.25; gbc_geneOnePOneRadHetero.fill = GridBagConstraints.BOTH; gbc_geneOnePOneRadHetero.gridx = 2; gbc_geneOnePOneRadHetero.gridy = 3; parentOnePanel.add(geneOnePOneRadHetero, gbc_geneOnePOneRadHetero); //Gene One Parent One Radio HomoR geneOnePOneRadHomoR = new JRadioButton("aa"); geneOnePOneRadHomoR.setHorizontalAlignment(SwingConstants.CENTER); geneOnePOneRadHomoR.setBackground(backgroundColor); geneOnePOneRadHomoR.setForeground(textColor); geneOnePOneRadHomoR.setEnabled(inDebugMode); GridBagConstraints gbc_geneOnePOneRadHomoR = new GridBagConstraints(); gbc_geneOnePOneRadHomoR.insets = new Insets(0, 0, 5, 0); gbc_geneOnePOneRadHomoR.weightx = 0.25; gbc_geneOnePOneRadHomoR.fill = GridBagConstraints.BOTH; gbc_geneOnePOneRadHomoR.gridx = 3; gbc_geneOnePOneRadHomoR.gridy = 3; parentOnePanel.add(geneOnePOneRadHomoR, gbc_geneOnePOneRadHomoR); //Gene Two Parent One Label geneTwoPOneLabel = new JLabel("Gene 2"); geneTwoPOneLabel.setHorizontalAlignment(SwingConstants.CENTER); geneTwoPOneLabel.setBackground(backgroundColor); geneTwoPOneLabel.setForeground(textColor); geneTwoPOneLabel.setEnabled(inDebugMode); geneLabelList.add(geneTwoPOneLabel); GridBagConstraints gbc_geneTwoPOneLabel = new GridBagConstraints(); gbc_geneTwoPOneLabel.gridwidth = 4; gbc_geneTwoPOneLabel.insets = new Insets(0, 0, 5, 0); gbc_geneTwoPOneLabel.weightx = 1.0; gbc_geneTwoPOneLabel.fill = GridBagConstraints.BOTH; gbc_geneTwoPOneLabel.gridx = 0; gbc_geneTwoPOneLabel.gridy = 5; parentOnePanel.add(geneTwoPOneLabel, gbc_geneTwoPOneLabel); //Gene Two Parent One Combo geneTwoPOneCombo = new JComboBox<String>(); geneTwoPOneCombo.setMaximumRowCount(26); for (int init = 0; init < geneOptions.length; init++) { geneTwoPOneCombo.addItem(geneOptions[init]); } geneTwoPOneCombo.setBackground(textFieldColor); geneTwoPOneCombo.setForeground(textColor); geneTwoPOneCombo.setEnabled(inDebugMode); comboBoxPOneList.add(geneTwoPOneCombo); GridBagConstraints gbc_geneTwoPOneCombo = new GridBagConstraints(); gbc_geneTwoPOneCombo.insets = new Insets(0, 0, 5, 5); gbc_geneTwoPOneCombo.fill = GridBagConstraints.HORIZONTAL; gbc_geneTwoPOneCombo.gridx = 0; gbc_geneTwoPOneCombo.gridy = 6; parentOnePanel.add(geneTwoPOneCombo, gbc_geneTwoPOneCombo); //Gene Two Parent One Radio HomoD geneTwoPOneRadHomoD = new JRadioButton("AA"); geneTwoPOneRadHomoD.setHorizontalAlignment(SwingConstants.CENTER); geneTwoPOneRadHomoD.setBackground(backgroundColor); geneTwoPOneRadHomoD.setForeground(textColor); geneTwoPOneRadHomoD.setEnabled(inDebugMode); GridBagConstraints gbc_geneTwoPOneRadHomoD = new GridBagConstraints(); gbc_geneTwoPOneRadHomoD.insets = new Insets(0, 0, 5, 5); gbc_geneTwoPOneRadHomoD.weightx = 0.25; gbc_geneTwoPOneRadHomoD.fill = GridBagConstraints.BOTH; gbc_geneTwoPOneRadHomoD.gridx = 1; gbc_geneTwoPOneRadHomoD.gridy = 6; parentOnePanel.add(geneTwoPOneRadHomoD, gbc_geneTwoPOneRadHomoD); //Gene Two Parent One Radio Hetero geneTwoPOneRadHetero = new JRadioButton("Aa"); geneTwoPOneRadHetero.setHorizontalAlignment(SwingConstants.CENTER); geneTwoPOneRadHetero.setBackground(backgroundColor); geneTwoPOneRadHetero.setForeground(textColor); geneTwoPOneRadHetero.setEnabled(inDebugMode); GridBagConstraints gbc_geneTwoPOneRadHetero = new GridBagConstraints(); gbc_geneTwoPOneRadHetero.insets = new Insets(0, 0, 5, 5); gbc_geneTwoPOneRadHetero.weightx = 0.25; gbc_geneTwoPOneRadHetero.fill = GridBagConstraints.BOTH; gbc_geneTwoPOneRadHetero.gridx = 2; gbc_geneTwoPOneRadHetero.gridy = 6; parentOnePanel.add(geneTwoPOneRadHetero, gbc_geneTwoPOneRadHetero); //Gene Two Parent One Radio HomoR geneTwoPOneRadHomoR = new JRadioButton("aa"); geneTwoPOneRadHomoR.setHorizontalAlignment(SwingConstants.CENTER); geneTwoPOneRadHomoR.setBackground(backgroundColor); geneTwoPOneRadHomoR.setForeground(textColor); geneTwoPOneRadHomoR.setEnabled(inDebugMode); GridBagConstraints gbc_geneTwoPOneRadHomoR = new GridBagConstraints(); gbc_geneTwoPOneRadHomoR.insets = new Insets(0, 0, 5, 0); gbc_geneTwoPOneRadHomoR.weightx = 0.25; gbc_geneTwoPOneRadHomoR.fill = GridBagConstraints.BOTH; gbc_geneTwoPOneRadHomoR.gridx = 3; gbc_geneTwoPOneRadHomoR.gridy = 6; parentOnePanel.add(geneTwoPOneRadHomoR, gbc_geneTwoPOneRadHomoR); //Gene Three Parent One Label geneThreePOneLabel = new JLabel("Gene 3"); geneThreePOneLabel.setHorizontalAlignment(SwingConstants.CENTER); geneThreePOneLabel.setBackground(backgroundColor); geneThreePOneLabel.setForeground(textColor); geneThreePOneLabel.setEnabled(inDebugMode); geneLabelList.add(geneThreePOneLabel); GridBagConstraints gbc_geneThreePOneLabel = new GridBagConstraints(); gbc_geneThreePOneLabel.gridwidth = 4; gbc_geneThreePOneLabel.insets = new Insets(0, 0, 5, 0); gbc_geneThreePOneLabel.weightx = 1.0; gbc_geneThreePOneLabel.fill = GridBagConstraints.BOTH; gbc_geneThreePOneLabel.gridx = 0; gbc_geneThreePOneLabel.gridy = 8; parentOnePanel.add(geneThreePOneLabel, gbc_geneThreePOneLabel); //Gene Three Parent One Combo geneThreePOneCombo = new JComboBox<String>(); geneThreePOneCombo.setMaximumRowCount(26); for (int init = 0; init < geneOptions.length; init++) { geneThreePOneCombo.addItem(geneOptions[init]); } geneThreePOneCombo.setBackground(textFieldColor); geneThreePOneCombo.setForeground(textColor); geneThreePOneCombo.setEnabled(inDebugMode); comboBoxPOneList.add(geneThreePOneCombo); GridBagConstraints gbc_geneThreePOneCombo = new GridBagConstraints(); gbc_geneThreePOneCombo.insets = new Insets(0, 0, 5, 5); gbc_geneThreePOneCombo.fill = GridBagConstraints.HORIZONTAL; gbc_geneThreePOneCombo.gridx = 0; gbc_geneThreePOneCombo.gridy = 9; parentOnePanel.add(geneThreePOneCombo, gbc_geneThreePOneCombo); //Gene Three Parent One Radio HomoD geneThreePOneRadHomoD = new JRadioButton("AA"); geneThreePOneRadHomoD.setHorizontalAlignment(SwingConstants.CENTER); geneThreePOneRadHomoD.setBackground(backgroundColor); geneThreePOneRadHomoD.setForeground(textColor); geneThreePOneRadHomoD.setEnabled(inDebugMode); GridBagConstraints gbc_geneThreePOneRadHomoD = new GridBagConstraints(); gbc_geneThreePOneRadHomoD.insets = new Insets(0, 0, 5, 5); gbc_geneThreePOneRadHomoD.weightx = 0.25; gbc_geneThreePOneRadHomoD.fill = GridBagConstraints.BOTH; gbc_geneThreePOneRadHomoD.gridx = 1; gbc_geneThreePOneRadHomoD.gridy = 9; parentOnePanel.add(geneThreePOneRadHomoD, gbc_geneThreePOneRadHomoD); //Gene Three Parent One Radio Hetero geneThreePOneRadHetero = new JRadioButton("Aa"); geneThreePOneRadHetero.setHorizontalAlignment(SwingConstants.CENTER); geneThreePOneRadHetero.setBackground(backgroundColor); geneThreePOneRadHetero.setForeground(textColor); geneThreePOneRadHetero.setEnabled(inDebugMode); GridBagConstraints gbc_geneThreePOneRadHetero = new GridBagConstraints(); gbc_geneThreePOneRadHetero.insets = new Insets(0, 0, 5, 5); gbc_geneThreePOneRadHetero.weightx = 0.25; gbc_geneThreePOneRadHetero.fill = GridBagConstraints.BOTH; gbc_geneThreePOneRadHetero.gridx = 2; gbc_geneThreePOneRadHetero.gridy = 9; parentOnePanel.add(geneThreePOneRadHetero, gbc_geneThreePOneRadHetero); //Gene Three Parent One Radio HomoR geneThreePOneRadHomoR = new JRadioButton("aa"); geneThreePOneRadHomoR.setHorizontalAlignment(SwingConstants.CENTER); geneThreePOneRadHomoR.setBackground(backgroundColor); geneThreePOneRadHomoR.setForeground(textColor); geneThreePOneRadHomoR.setEnabled(inDebugMode); GridBagConstraints gbc_geneThreePOneRadHomoR = new GridBagConstraints(); gbc_geneThreePOneRadHomoR.insets = new Insets(0, 0, 5, 0); gbc_geneThreePOneRadHomoR.weightx = 0.25; gbc_geneThreePOneRadHomoR.fill = GridBagConstraints.BOTH; gbc_geneThreePOneRadHomoR.gridx = 3; gbc_geneThreePOneRadHomoR.gridy = 9; parentOnePanel.add(geneThreePOneRadHomoR, gbc_geneThreePOneRadHomoR); //Gene Four Parent One Label geneFourPOneLabel = new JLabel("Gene 4"); geneFourPOneLabel.setHorizontalAlignment(SwingConstants.CENTER); geneFourPOneLabel.setBackground(backgroundColor); geneFourPOneLabel.setForeground(textColor); geneFourPOneLabel.setEnabled(inDebugMode); geneLabelList.add(geneFourPOneLabel); GridBagConstraints gbc_geneFourPOneLabel = new GridBagConstraints(); gbc_geneFourPOneLabel.gridwidth = 4; gbc_geneFourPOneLabel.insets = new Insets(0, 0, 5, 0); gbc_geneFourPOneLabel.fill = GridBagConstraints.BOTH; gbc_geneFourPOneLabel.gridx = 0; gbc_geneFourPOneLabel.gridy = 11; parentOnePanel.add(geneFourPOneLabel, gbc_geneFourPOneLabel); //Gene Four Parent One Combo geneFourPOneCombo = new JComboBox<String>(); geneFourPOneCombo.setMaximumRowCount(26); for (int init = 0; init < geneOptions.length; init++) { geneFourPOneCombo.addItem(geneOptions[init]); } geneFourPOneCombo.setBackground(textFieldColor); geneFourPOneCombo.setForeground(textColor); geneFourPOneCombo.setEnabled(inDebugMode); comboBoxPOneList.add(geneFourPOneCombo); GridBagConstraints gbc_geneFourPOneCombo = new GridBagConstraints(); gbc_geneFourPOneCombo.insets = new Insets(0, 0, 5, 5); gbc_geneFourPOneCombo.fill = GridBagConstraints.HORIZONTAL; gbc_geneFourPOneCombo.gridx = 0; gbc_geneFourPOneCombo.gridy = 12; parentOnePanel.add(geneFourPOneCombo, gbc_geneFourPOneCombo); //Gene Four Parent One Radio HomoD geneFourPOneRadHomoD = new JRadioButton("AA"); geneFourPOneRadHomoD.setHorizontalAlignment(SwingConstants.CENTER); geneFourPOneRadHomoD.setBackground(backgroundColor); geneFourPOneRadHomoD.setForeground(textColor); geneFourPOneRadHomoD.setEnabled(inDebugMode); GridBagConstraints gbc_geneFourPOneRadHomoD = new GridBagConstraints(); gbc_geneFourPOneRadHomoD.insets = new Insets(0, 0, 5, 5); gbc_geneFourPOneRadHomoD.weightx = 0.25; gbc_geneFourPOneRadHomoD.fill = GridBagConstraints.BOTH; gbc_geneFourPOneRadHomoD.gridx = 1; gbc_geneFourPOneRadHomoD.gridy = 12; parentOnePanel.add(geneFourPOneRadHomoD, gbc_geneFourPOneRadHomoD); //Gene Four Parent One Radio Hetero geneFourPOneRadHetero = new JRadioButton("Aa"); geneFourPOneRadHetero.setHorizontalAlignment(SwingConstants.CENTER); geneFourPOneRadHetero.setBackground(backgroundColor); geneFourPOneRadHetero.setForeground(textColor); geneFourPOneRadHetero.setEnabled(inDebugMode); GridBagConstraints gbc_geneFourPOneRadHetero = new GridBagConstraints(); gbc_geneFourPOneRadHetero.insets = new Insets(0, 0, 5, 5); gbc_geneFourPOneRadHetero.weightx = 0.25; gbc_geneFourPOneRadHetero.fill = GridBagConstraints.BOTH; gbc_geneFourPOneRadHetero.gridx = 2; gbc_geneFourPOneRadHetero.gridy = 12; parentOnePanel.add(geneFourPOneRadHetero, gbc_geneFourPOneRadHetero); //Gene Four Parent One Radio HomoR geneFourPOneRadHomoR = new JRadioButton("aa"); geneFourPOneRadHomoR.setHorizontalAlignment(SwingConstants.CENTER); geneFourPOneRadHomoR.setBackground(backgroundColor); geneFourPOneRadHomoR.setForeground(textColor); geneFourPOneRadHomoR.setEnabled(inDebugMode); GridBagConstraints gbc_geneFourPOneRadHomoR = new GridBagConstraints(); gbc_geneFourPOneRadHomoR.insets = new Insets(0, 0, 5, 0); gbc_geneFourPOneRadHomoR.weightx = 0.25; gbc_geneFourPOneRadHomoR.fill = GridBagConstraints.BOTH; gbc_geneFourPOneRadHomoR.gridx = 3; gbc_geneFourPOneRadHomoR.gridy = 12; parentOnePanel.add(geneFourPOneRadHomoR, gbc_geneFourPOneRadHomoR); //Gene Five Parent One Label geneFivePOneLabel = new JLabel("Gene 5"); geneFivePOneLabel.setHorizontalAlignment(SwingConstants.CENTER); geneFivePOneLabel.setBackground(backgroundColor); geneFivePOneLabel.setForeground(textColor); geneFivePOneLabel.setEnabled(inDebugMode); geneLabelList.add(geneFivePOneLabel); GridBagConstraints gbc_geneFivePOneLabel = new GridBagConstraints(); gbc_geneFivePOneLabel.gridwidth = 4; gbc_geneFivePOneLabel.insets = new Insets(0, 0, 5, 0); gbc_geneFivePOneLabel.fill = GridBagConstraints.BOTH; gbc_geneFivePOneLabel.gridx = 0; gbc_geneFivePOneLabel.gridy = 14; parentOnePanel.add(geneFivePOneLabel, gbc_geneFivePOneLabel); //Gene Five Parent One Combo geneFivePOneCombo = new JComboBox<String>(); geneFivePOneCombo.setMaximumRowCount(26); for (int init = 0; init < geneOptions.length; init++) { geneFivePOneCombo.addItem(geneOptions[init]); } geneFivePOneCombo.setBackground(textFieldColor); geneFivePOneCombo.setForeground(textColor); geneFivePOneCombo.setEnabled(inDebugMode); comboBoxPOneList.add(geneFivePOneCombo); GridBagConstraints gbc_geneFivePOneCombo = new GridBagConstraints(); gbc_geneFivePOneCombo.insets = new Insets(0, 0, 5, 5); gbc_geneFivePOneCombo.fill = GridBagConstraints.HORIZONTAL; gbc_geneFivePOneCombo.gridx = 0; gbc_geneFivePOneCombo.gridy = 15; parentOnePanel.add(geneFivePOneCombo, gbc_geneFivePOneCombo); //Gene Five Parent One Radio HomoD geneFivePOneRadHomoD = new JRadioButton("AA"); geneFivePOneRadHomoD.setHorizontalAlignment(SwingConstants.CENTER); geneFivePOneRadHomoD.setBackground(backgroundColor); geneFivePOneRadHomoD.setForeground(textColor); geneFivePOneRadHomoD.setEnabled(inDebugMode); GridBagConstraints gbc_geneFivePOneRadHomoD = new GridBagConstraints(); gbc_geneFivePOneRadHomoD.insets = new Insets(0, 0, 5, 5); gbc_geneFivePOneRadHomoD.weightx = 0.25; gbc_geneFivePOneRadHomoD.fill = GridBagConstraints.BOTH; gbc_geneFivePOneRadHomoD.gridx = 1; gbc_geneFivePOneRadHomoD.gridy = 15; parentOnePanel.add(geneFivePOneRadHomoD, gbc_geneFivePOneRadHomoD); //Gene Five Parent One Radio Hetero geneFivePOneRadHetero = new JRadioButton("Aa"); geneFivePOneRadHetero.setHorizontalAlignment(SwingConstants.CENTER); geneFivePOneRadHetero.setBackground(backgroundColor); geneFivePOneRadHetero.setForeground(textColor); geneFivePOneRadHetero.setEnabled(inDebugMode); GridBagConstraints gbc_geneFivePOneRadHetero = new GridBagConstraints(); gbc_geneFivePOneRadHetero.insets = new Insets(0, 0, 5, 5); gbc_geneFivePOneRadHetero.weightx = 0.25; gbc_geneFivePOneRadHetero.fill = GridBagConstraints.BOTH; gbc_geneFivePOneRadHetero.gridx = 2; gbc_geneFivePOneRadHetero.gridy = 15; parentOnePanel.add(geneFivePOneRadHetero, gbc_geneFivePOneRadHetero); //Gene Five Parent One Radio HomoR geneFivePOneRadHomoR = new JRadioButton("aa"); geneFivePOneRadHomoR.setHorizontalAlignment(SwingConstants.CENTER); geneFivePOneRadHomoR.setBackground(backgroundColor); geneFivePOneRadHomoR.setForeground(textColor); geneFivePOneRadHomoR.setEnabled(inDebugMode); GridBagConstraints gbc_geneFivePOneRadHomoR = new GridBagConstraints(); gbc_geneFivePOneRadHomoR.insets = new Insets(0, 0, 5, 0); gbc_geneFivePOneRadHomoR.weightx = 0.25; gbc_geneFivePOneRadHomoR.fill = GridBagConstraints.BOTH; gbc_geneFivePOneRadHomoR.gridx = 3; gbc_geneFivePOneRadHomoR.gridy = 15; parentOnePanel.add(geneFivePOneRadHomoR, gbc_geneFivePOneRadHomoR); //Parent One Calculation Button calcButton = new JButton("Calculate"); calcButton.setBackground(backgroundColor); calcButton.setForeground(textColor); calcButton.setEnabled(inDebugMode); calcButton.setEnabled(true); calcButton.addMouseListener(this); GridBagConstraints gbc_calcButton = new GridBagConstraints(); gbc_calcButton.gridwidth = 4; gbc_calcButton.weightx = 1.0; gbc_calcButton.fill = GridBagConstraints.BOTH; gbc_calcButton.gridx = 0; gbc_calcButton.gridy = 20; parentOnePanel.add(calcButton, gbc_calcButton); //Adding all Parent One radio buttons to their corresponding ButtonGroups //Gene One Parent One geneOnePOneBG = new ButtonGroup(); geneOnePOneBG.add(geneOnePOneRadHomoD); geneOnePOneBG.add(geneOnePOneRadHetero); geneOnePOneBG.add(geneOnePOneRadHomoR); buttonGroupList.add(geneOnePOneBG); //Gene Two Parent One geneTwoPOneBG = new ButtonGroup(); geneTwoPOneBG.add(geneTwoPOneRadHomoD); geneTwoPOneBG.add(geneTwoPOneRadHetero); geneTwoPOneBG.add(geneTwoPOneRadHomoR); buttonGroupList.add(geneTwoPOneBG); //Gene Three Parent One geneThreePOneBG = new ButtonGroup(); geneThreePOneBG.add(geneThreePOneRadHomoD); geneThreePOneBG.add(geneThreePOneRadHetero); geneThreePOneBG.add(geneThreePOneRadHomoR); buttonGroupList.add(geneThreePOneBG); //Gene Four Parent One geneFourPOneBG = new ButtonGroup(); geneFourPOneBG.add(geneFourPOneRadHomoD); geneFourPOneBG.add(geneFourPOneRadHetero); geneFourPOneBG.add(geneFourPOneRadHomoR); buttonGroupList.add(geneFourPOneBG); //Gene Five Parent One geneFivePOneBG = new ButtonGroup(); geneFivePOneBG.add(geneFivePOneRadHomoD); geneFivePOneBG.add(geneFivePOneRadHetero); geneFivePOneBG.add(geneFivePOneRadHomoR); buttonGroupList.add(geneFivePOneBG); //Parent Two Column JPanel parentTwoPanel = new JPanel(); parentTwoPanel.setBackground(backgroundColor); GridBagConstraints gbc_parentTwo = new GridBagConstraints(); gbc_parentTwo.insets = new Insets(0, 5, 0, 0); gbc_parentTwo.weighty = 1.0; gbc_parentTwo.weightx = 0.2; gbc_parentTwo.fill = GridBagConstraints.BOTH; gbc_parentTwo.gridx = 1; gbc_parentTwo.gridy = 0; content.add(parentTwoPanel, gbc_parentTwo); GridBagLayout gbl_parentTwo = new GridBagLayout(); gbl_parentTwo.columnWidths = new int[]{0, 0, 0, 0, 0}; gbl_parentTwo.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; gbl_parentTwo.columnWeights = new double[]{1.0, 1.0, 0.0, 0.0, Double.MIN_VALUE}; gbl_parentTwo.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE}; parentTwoPanel.setLayout(gbl_parentTwo); //Parent Two Label JLabel parentTwoLabel = new JLabel("Parent Two"); parentTwoLabel.setHorizontalAlignment(SwingConstants.CENTER); parentTwoLabel.setBackground(backgroundColor); parentTwoLabel.setForeground(textColor); GridBagConstraints gbc_parentTwoLabel = new GridBagConstraints(); gbc_parentTwoLabel.anchor = GridBagConstraints.NORTH; gbc_parentTwoLabel.gridwidth = 4; gbc_parentTwoLabel.weightx = 1.0; gbc_parentTwoLabel.fill = GridBagConstraints.BOTH; gbc_parentTwoLabel.insets = new Insets(0, 0, 5, 0); gbc_parentTwoLabel.gridx = 0; gbc_parentTwoLabel.gridy = 0; parentTwoPanel.add(parentTwoLabel, gbc_parentTwoLabel); //Gene One Parent Two Label geneOnePTwoLabel = new JLabel("Gene 1"); geneOnePTwoLabel.setHorizontalAlignment(SwingConstants.CENTER); geneOnePTwoLabel.setBackground(backgroundColor); geneOnePTwoLabel.setForeground(textColor); geneOnePTwoLabel.setEnabled(inDebugMode); geneLabelList.add(geneOnePTwoLabel); GridBagConstraints gbc_geneOnePTwoLabel = new GridBagConstraints(); gbc_geneOnePTwoLabel.gridwidth = 4; gbc_geneOnePTwoLabel.weightx = 1.0; gbc_geneOnePTwoLabel.fill = GridBagConstraints.BOTH; gbc_geneOnePTwoLabel.insets = new Insets(0, 0, 5, 0); gbc_geneOnePTwoLabel.gridx = 0; gbc_geneOnePTwoLabel.gridy = 2; parentTwoPanel.add(geneOnePTwoLabel, gbc_geneOnePTwoLabel); //Gene One Parent Two Combo geneOnePTwoCombo = new JComboBox<String>(); geneOnePTwoCombo.setMaximumRowCount(26); for (int init = 0; init < geneOptions.length; init++) { geneOnePTwoCombo.addItem(geneOptions[init]); } geneOnePTwoCombo.setBackground(textFieldColor); geneOnePTwoCombo.setForeground(textColor); geneOnePTwoCombo.setEnabled(inDebugMode); comboBoxPTwoList.add(geneOnePTwoCombo); GridBagConstraints gbc_geneOnePTwoCombo = new GridBagConstraints(); gbc_geneOnePTwoCombo.insets = new Insets(0, 0, 5, 5); gbc_geneOnePTwoCombo.fill = GridBagConstraints.HORIZONTAL; gbc_geneOnePTwoCombo.gridx = 0; gbc_geneOnePTwoCombo.gridy = 3; parentTwoPanel.add(geneOnePTwoCombo, gbc_geneOnePTwoCombo); //Gene One Parent Two Radio HomoD geneOnePTwoRadHomoD = new JRadioButton("AA"); geneOnePTwoRadHomoD.setHorizontalAlignment(SwingConstants.CENTER); geneOnePTwoRadHomoD.setBackground(backgroundColor); geneOnePTwoRadHomoD.setForeground(textColor); geneOnePTwoRadHomoD.setEnabled(inDebugMode); GridBagConstraints gbc_geneOnePTwoRadHomoD = new GridBagConstraints(); gbc_geneOnePTwoRadHomoD.weightx = 0.25; gbc_geneOnePTwoRadHomoD.fill = GridBagConstraints.BOTH; gbc_geneOnePTwoRadHomoD.insets = new Insets(0, 0, 5, 5); gbc_geneOnePTwoRadHomoD.gridx = 1; gbc_geneOnePTwoRadHomoD.gridy = 3; parentTwoPanel.add(geneOnePTwoRadHomoD, gbc_geneOnePTwoRadHomoD); //Gene One Parent Two Radio Hetero geneOnePTwoRadHetero = new JRadioButton("Aa"); geneOnePTwoRadHetero.setHorizontalAlignment(SwingConstants.CENTER); geneOnePTwoRadHetero.setBackground(backgroundColor); geneOnePTwoRadHetero.setForeground(textColor); geneOnePTwoRadHetero.setEnabled(inDebugMode); GridBagConstraints gbc_geneOnePTwoRadHetero = new GridBagConstraints(); gbc_geneOnePTwoRadHetero.weightx = 0.25; gbc_geneOnePTwoRadHetero.fill = GridBagConstraints.BOTH; gbc_geneOnePTwoRadHetero.insets = new Insets(0, 0, 5, 5); gbc_geneOnePTwoRadHetero.gridx = 2; gbc_geneOnePTwoRadHetero.gridy = 3; parentTwoPanel.add(geneOnePTwoRadHetero, gbc_geneOnePTwoRadHetero); //Gene One Parent Two Radio HomoR geneOnePTwoRadHomoR = new JRadioButton("aa"); geneOnePTwoRadHomoR.setHorizontalAlignment(SwingConstants.CENTER); geneOnePTwoRadHomoR.setBackground(backgroundColor); geneOnePTwoRadHomoR.setForeground(textColor); geneOnePTwoRadHomoR.setEnabled(inDebugMode); GridBagConstraints gbc_geneOnePTwoRadHomoR = new GridBagConstraints(); gbc_geneOnePTwoRadHomoR.weightx = 0.25; gbc_geneOnePTwoRadHomoR.fill = GridBagConstraints.BOTH; gbc_geneOnePTwoRadHomoR.insets = new Insets(0, 0, 5, 0); gbc_geneOnePTwoRadHomoR.gridx = 3; gbc_geneOnePTwoRadHomoR.gridy = 3; parentTwoPanel.add(geneOnePTwoRadHomoR, gbc_geneOnePTwoRadHomoR); //Gene Two Parent Two Label geneTwoPTwoLabel = new JLabel("Gene 2"); geneTwoPTwoLabel.setHorizontalAlignment(SwingConstants.CENTER); geneTwoPTwoLabel.setBackground(backgroundColor); geneTwoPTwoLabel.setForeground(textColor); geneTwoPTwoLabel.setEnabled(inDebugMode); geneLabelList.add(geneTwoPTwoLabel); GridBagConstraints gbc_geneTwoPTwoLabel = new GridBagConstraints(); gbc_geneTwoPTwoLabel.gridwidth = 4; gbc_geneTwoPTwoLabel.weightx = 1.0; gbc_geneTwoPTwoLabel.fill = GridBagConstraints.BOTH; gbc_geneTwoPTwoLabel.insets = new Insets(0, 0, 5, 0); gbc_geneTwoPTwoLabel.gridx = 0; gbc_geneTwoPTwoLabel.gridy = 5; parentTwoPanel.add(geneTwoPTwoLabel, gbc_geneTwoPTwoLabel); //Gene Two Parent Two Combo geneTwoPTwoCombo = new JComboBox<String>(); geneTwoPTwoCombo.setMaximumRowCount(26); for (int init = 0; init < geneOptions.length; init++) { geneTwoPTwoCombo.addItem(geneOptions[init]); } geneTwoPTwoCombo.setBackground(textFieldColor); geneTwoPTwoCombo.setForeground(textColor); geneTwoPTwoCombo.setEnabled(inDebugMode); comboBoxPTwoList.add(geneTwoPTwoCombo); GridBagConstraints gbc_geneTwoPTwoCombo = new GridBagConstraints(); gbc_geneTwoPTwoCombo.insets = new Insets(0, 0, 5, 5); gbc_geneTwoPTwoCombo.fill = GridBagConstraints.HORIZONTAL; gbc_geneTwoPTwoCombo.gridx = 0; gbc_geneTwoPTwoCombo.gridy = 6; parentTwoPanel.add(geneTwoPTwoCombo, gbc_geneTwoPTwoCombo); //Gene Two Parent Two Radio HomoD geneTwoPTwoRadHomoD = new JRadioButton("AA"); geneTwoPTwoRadHomoD.setHorizontalAlignment(SwingConstants.CENTER); geneTwoPTwoRadHomoD.setBackground(backgroundColor); geneTwoPTwoRadHomoD.setForeground(textColor); geneTwoPTwoRadHomoD.setEnabled(inDebugMode); GridBagConstraints gbc_geneTwoPTwoRadHomoD = new GridBagConstraints(); gbc_geneTwoPTwoRadHomoD.weightx = 0.25; gbc_geneTwoPTwoRadHomoD.fill = GridBagConstraints.BOTH; gbc_geneTwoPTwoRadHomoD.insets = new Insets(0, 0, 5, 5); gbc_geneTwoPTwoRadHomoD.gridx = 1; gbc_geneTwoPTwoRadHomoD.gridy = 6; parentTwoPanel.add(geneTwoPTwoRadHomoD, gbc_geneTwoPTwoRadHomoD); //Gene Two Parent Two Radio Hetero geneTwoPTwoRadHetero = new JRadioButton("Aa"); geneTwoPTwoRadHetero.setHorizontalAlignment(SwingConstants.CENTER); geneTwoPTwoRadHetero.setBackground(backgroundColor); geneTwoPTwoRadHetero.setForeground(textColor); geneTwoPTwoRadHetero.setEnabled(inDebugMode); GridBagConstraints gbc_geneTwoPTwoRadHetero = new GridBagConstraints(); gbc_geneTwoPTwoRadHetero.weightx = 0.25; gbc_geneTwoPTwoRadHetero.fill = GridBagConstraints.BOTH; gbc_geneTwoPTwoRadHetero.insets = new Insets(0, 0, 5, 5); gbc_geneTwoPTwoRadHetero.gridx = 2; gbc_geneTwoPTwoRadHetero.gridy = 6; parentTwoPanel.add(geneTwoPTwoRadHetero, gbc_geneTwoPTwoRadHetero); //Gene Two Parent Two Radio HomoR geneTwoPTwoRadHomoR = new JRadioButton("aa"); geneTwoPTwoRadHomoR.setHorizontalAlignment(SwingConstants.CENTER); geneTwoPTwoRadHomoR.setBackground(backgroundColor); geneTwoPTwoRadHomoR.setForeground(textColor); geneTwoPTwoRadHomoR.setEnabled(inDebugMode); GridBagConstraints gbc_geneTwoPTwoRadHomoR = new GridBagConstraints(); gbc_geneTwoPTwoRadHomoR.weightx = 0.25; gbc_geneTwoPTwoRadHomoR.fill = GridBagConstraints.BOTH; gbc_geneTwoPTwoRadHomoR.insets = new Insets(0, 0, 5, 0); gbc_geneTwoPTwoRadHomoR.gridx = 3; gbc_geneTwoPTwoRadHomoR.gridy = 6; parentTwoPanel.add(geneTwoPTwoRadHomoR, gbc_geneTwoPTwoRadHomoR); //Gene Three Parent Two Label geneThreePTwoLabel = new JLabel("Gene 3"); geneThreePTwoLabel.setHorizontalAlignment(SwingConstants.CENTER); geneThreePTwoLabel.setBackground(backgroundColor); geneThreePTwoLabel.setForeground(textColor); geneThreePTwoLabel.setEnabled(inDebugMode); geneLabelList.add(geneThreePTwoLabel); GridBagConstraints gbc_geneThreePTwoLabel = new GridBagConstraints(); gbc_geneThreePTwoLabel.gridwidth = 4; gbc_geneThreePTwoLabel.weightx = 1.0; gbc_geneThreePTwoLabel.fill = GridBagConstraints.BOTH; gbc_geneThreePTwoLabel.insets = new Insets(0, 0, 5, 0); gbc_geneThreePTwoLabel.gridx = 0; gbc_geneThreePTwoLabel.gridy = 8; parentTwoPanel.add(geneThreePTwoLabel, gbc_geneThreePTwoLabel); //Gene Three Parent Two Combo geneThreePTwoCombo = new JComboBox<String>(); geneThreePTwoCombo.setMaximumRowCount(26); for (int init = 0; init < geneOptions.length; init++) { geneThreePTwoCombo.addItem(geneOptions[init]); } geneThreePTwoCombo.setBackground(textFieldColor); geneThreePTwoCombo.setForeground(textColor); geneThreePTwoCombo.setEnabled(inDebugMode); comboBoxPTwoList.add(geneThreePTwoCombo); GridBagConstraints gbc_geneThreePTwoCombo = new GridBagConstraints(); gbc_geneThreePTwoCombo.insets = new Insets(0, 0, 5, 5); gbc_geneThreePTwoCombo.fill = GridBagConstraints.HORIZONTAL; gbc_geneThreePTwoCombo.gridx = 0; gbc_geneThreePTwoCombo.gridy = 9; parentTwoPanel.add(geneThreePTwoCombo, gbc_geneThreePTwoCombo); //Gene Three Parent Two Radio HomoD geneThreePTwoRadHomoD = new JRadioButton("AA"); geneThreePTwoRadHomoD.setHorizontalAlignment(SwingConstants.CENTER); geneThreePTwoRadHomoD.setBackground(backgroundColor); geneThreePTwoRadHomoD.setForeground(textColor); geneThreePTwoRadHomoD.setEnabled(inDebugMode); GridBagConstraints gbc_geneThreePTwoRadHomoD = new GridBagConstraints(); gbc_geneThreePTwoRadHomoD.weightx = 0.25; gbc_geneThreePTwoRadHomoD.fill = GridBagConstraints.BOTH; gbc_geneThreePTwoRadHomoD.insets = new Insets(0, 0, 5, 5); gbc_geneThreePTwoRadHomoD.gridx = 1; gbc_geneThreePTwoRadHomoD.gridy = 9; parentTwoPanel.add(geneThreePTwoRadHomoD, gbc_geneThreePTwoRadHomoD); //Gene Three Parent Two Radio Hetero geneThreePTwoRadHetero = new JRadioButton("Aa"); geneThreePTwoRadHetero.setHorizontalAlignment(SwingConstants.CENTER); geneThreePTwoRadHetero.setBackground(backgroundColor); geneThreePTwoRadHetero.setForeground(textColor); geneThreePTwoRadHetero.setEnabled(inDebugMode); GridBagConstraints gbc_geneThreePTwoRadHetero = new GridBagConstraints(); gbc_geneThreePTwoRadHetero.weightx = 0.25; gbc_geneThreePTwoRadHetero.fill = GridBagConstraints.BOTH; gbc_geneThreePTwoRadHetero.insets = new Insets(0, 0, 5, 5); gbc_geneThreePTwoRadHetero.gridx = 2; gbc_geneThreePTwoRadHetero.gridy = 9; parentTwoPanel.add(geneThreePTwoRadHetero, gbc_geneThreePTwoRadHetero); //Gene Three Parent Two Radio HomoR geneThreePTwoRadHomoR = new JRadioButton("aa"); geneThreePTwoRadHomoR.setHorizontalAlignment(SwingConstants.CENTER); geneThreePTwoRadHomoR.setBackground(backgroundColor); geneThreePTwoRadHomoR.setForeground(textColor); geneThreePTwoRadHomoR.setEnabled(inDebugMode); GridBagConstraints gbc_geneThreePTwoRadHomoR = new GridBagConstraints(); gbc_geneThreePTwoRadHomoR.weightx = 0.25; gbc_geneThreePTwoRadHomoR.fill = GridBagConstraints.BOTH; gbc_geneThreePTwoRadHomoR.insets = new Insets(0, 0, 5, 0); gbc_geneThreePTwoRadHomoR.gridx = 3; gbc_geneThreePTwoRadHomoR.gridy = 9; parentTwoPanel.add(geneThreePTwoRadHomoR, gbc_geneThreePTwoRadHomoR); //Gene Four Parent Two Label geneFourPTwoLabel = new JLabel("Gene 4"); geneFourPTwoLabel.setHorizontalAlignment(SwingConstants.CENTER); geneFourPTwoLabel.setBackground(backgroundColor); geneFourPTwoLabel.setForeground(textColor); geneFourPTwoLabel.setEnabled(inDebugMode); geneLabelList.add(geneFourPTwoLabel); GridBagConstraints gbc_geneFourPTwoLabel = new GridBagConstraints(); gbc_geneFourPTwoLabel.gridwidth = 4; gbc_geneFourPTwoLabel.fill = GridBagConstraints.BOTH; gbc_geneFourPTwoLabel.insets = new Insets(0, 0, 5, 0); gbc_geneFourPTwoLabel.gridx = 0; gbc_geneFourPTwoLabel.gridy = 11; parentTwoPanel.add(geneFourPTwoLabel, gbc_geneFourPTwoLabel); //Gene Four Parent Two Combo geneFourPTwoCombo = new JComboBox<String>(); geneFourPTwoCombo.setMaximumRowCount(26); for (int init = 0; init < geneOptions.length; init++) { geneFourPTwoCombo.addItem(geneOptions[init]); } geneFourPTwoCombo.setBackground(textFieldColor); geneFourPTwoCombo.setForeground(textColor); geneFourPTwoCombo.setEnabled(inDebugMode); comboBoxPTwoList.add(geneFourPTwoCombo); GridBagConstraints gbc_geneFourPTwoCombo = new GridBagConstraints(); gbc_geneFourPTwoCombo.insets = new Insets(0, 0, 5, 5); gbc_geneFourPTwoCombo.fill = GridBagConstraints.HORIZONTAL; gbc_geneFourPTwoCombo.gridx = 0; gbc_geneFourPTwoCombo.gridy = 12; parentTwoPanel.add(geneFourPTwoCombo, gbc_geneFourPTwoCombo); //Gene Four Parent Two Radio HomoD geneFourPTwoRadHomoD = new JRadioButton("AA"); geneFourPTwoRadHomoD.setHorizontalAlignment(SwingConstants.CENTER); geneFourPTwoRadHomoD.setBackground(backgroundColor); geneFourPTwoRadHomoD.setForeground(textColor); geneFourPTwoRadHomoD.setEnabled(inDebugMode); GridBagConstraints gbc_geneFourPTwoRadHomoD = new GridBagConstraints(); gbc_geneFourPTwoRadHomoD.weightx = 0.25; gbc_geneFourPTwoRadHomoD.fill = GridBagConstraints.BOTH; gbc_geneFourPTwoRadHomoD.insets = new Insets(0, 0, 5, 5); gbc_geneFourPTwoRadHomoD.gridx = 1; gbc_geneFourPTwoRadHomoD.gridy = 12; parentTwoPanel.add(geneFourPTwoRadHomoD, gbc_geneFourPTwoRadHomoD); //Gene Four Parent Two Radio Hetero geneFourPTwoRadHetero = new JRadioButton("Aa"); geneFourPTwoRadHetero.setHorizontalAlignment(SwingConstants.CENTER); geneFourPTwoRadHetero.setBackground(backgroundColor); geneFourPTwoRadHetero.setForeground(textColor); geneFourPTwoRadHetero.setEnabled(inDebugMode); GridBagConstraints gbc_geneFourPTwoRadHetero = new GridBagConstraints(); gbc_geneFourPTwoRadHetero.weightx = 0.25; gbc_geneFourPTwoRadHetero.fill = GridBagConstraints.BOTH; gbc_geneFourPTwoRadHetero.insets = new Insets(0, 0, 5, 5); gbc_geneFourPTwoRadHetero.gridx = 2; gbc_geneFourPTwoRadHetero.gridy = 12; parentTwoPanel.add(geneFourPTwoRadHetero, gbc_geneFourPTwoRadHetero); //Gene Four Parent Two Radio HomoR geneFourPTwoRadHomoR = new JRadioButton("aa"); geneFourPTwoRadHomoR.setHorizontalAlignment(SwingConstants.CENTER); geneFourPTwoRadHomoR.setBackground(backgroundColor); geneFourPTwoRadHomoR.setForeground(textColor); geneFourPTwoRadHomoR.setEnabled(inDebugMode); GridBagConstraints gbc_geneFourPTwoRadHomoR = new GridBagConstraints(); gbc_geneFourPTwoRadHomoR.weightx = 0.25; gbc_geneFourPTwoRadHomoR.fill = GridBagConstraints.BOTH; gbc_geneFourPTwoRadHomoR.insets = new Insets(0, 0, 5, 0); gbc_geneFourPTwoRadHomoR.gridx = 3; gbc_geneFourPTwoRadHomoR.gridy = 12; parentTwoPanel.add(geneFourPTwoRadHomoR, gbc_geneFourPTwoRadHomoR); //Gene Five Parent Two Label geneFivePTwoLabel = new JLabel("Gene 5"); geneFivePTwoLabel.setHorizontalAlignment(SwingConstants.CENTER); geneFivePTwoLabel.setBackground(backgroundColor); geneFivePTwoLabel.setForeground(textColor); geneFivePTwoLabel.setEnabled(inDebugMode); geneLabelList.add(geneFivePTwoLabel); GridBagConstraints gbc_geneFivePTwoLabel = new GridBagConstraints(); gbc_geneFivePTwoLabel.gridwidth = 4; gbc_geneFivePTwoLabel.fill = GridBagConstraints.BOTH; gbc_geneFivePTwoLabel.insets = new Insets(0, 0, 5, 0); gbc_geneFivePTwoLabel.gridx = 0; gbc_geneFivePTwoLabel.gridy = 14; parentTwoPanel.add(geneFivePTwoLabel, gbc_geneFivePTwoLabel); //Gene Five Parent Two Combo geneFivePTwoCombo = new JComboBox<String>(); geneFivePTwoCombo.setMaximumRowCount(26); for (int init = 0; init < geneOptions.length; init++) { geneFivePTwoCombo.addItem(geneOptions[init]); } geneFivePTwoCombo.setBackground(textFieldColor); geneFivePTwoCombo.setForeground(textColor); geneFivePTwoCombo.setEnabled(inDebugMode); comboBoxPTwoList.add(geneFivePTwoCombo); GridBagConstraints gbc_geneFivePTwoCombo = new GridBagConstraints(); gbc_geneFivePTwoCombo.insets = new Insets(0, 0, 5, 5); gbc_geneFivePTwoCombo.fill = GridBagConstraints.HORIZONTAL; gbc_geneFivePTwoCombo.gridx = 0; gbc_geneFivePTwoCombo.gridy = 15; parentTwoPanel.add(geneFivePTwoCombo, gbc_geneFivePTwoCombo); //Gene Five Parent Two Radio HomoD geneFivePTwoRadHomoD = new JRadioButton("AA"); geneFivePTwoRadHomoD.setHorizontalAlignment(SwingConstants.CENTER); geneFivePTwoRadHomoD.setBackground(backgroundColor); geneFivePTwoRadHomoD.setForeground(textColor); geneFivePTwoRadHomoD.setEnabled(inDebugMode); GridBagConstraints gbc_geneFivePTwoRadHomoD = new GridBagConstraints(); gbc_geneFivePTwoRadHomoD.weightx = 0.25; gbc_geneFivePTwoRadHomoD.fill = GridBagConstraints.BOTH; gbc_geneFivePTwoRadHomoD.insets = new Insets(0, 0, 5, 5); gbc_geneFivePTwoRadHomoD.gridx = 1; gbc_geneFivePTwoRadHomoD.gridy = 15; parentTwoPanel.add(geneFivePTwoRadHomoD, gbc_geneFivePTwoRadHomoD); //Gene Five Parent Two Radio Hetero geneFivePTwoRadHetero = new JRadioButton("Aa"); geneFivePTwoRadHetero.setHorizontalAlignment(SwingConstants.CENTER); geneFivePTwoRadHetero.setBackground(backgroundColor); geneFivePTwoRadHetero.setForeground(textColor); geneFivePTwoRadHetero.setEnabled(inDebugMode); GridBagConstraints gbc_geneFivePTwoRadHetero = new GridBagConstraints(); gbc_geneFivePTwoRadHetero.weightx = 0.25; gbc_geneFivePTwoRadHetero.fill = GridBagConstraints.BOTH; gbc_geneFivePTwoRadHetero.insets = new Insets(0, 0, 5, 5); gbc_geneFivePTwoRadHetero.gridx = 2; gbc_geneFivePTwoRadHetero.gridy = 15; parentTwoPanel.add(geneFivePTwoRadHetero, gbc_geneFivePTwoRadHetero); //Gene Five Parent Two Radio HomoR geneFivePTwoRadHomoR = new JRadioButton("aa"); geneFivePTwoRadHomoR.setHorizontalAlignment(SwingConstants.CENTER); geneFivePTwoRadHomoR.setBackground(backgroundColor); geneFivePTwoRadHomoR.setForeground(textColor); geneFivePTwoRadHomoR.setEnabled(inDebugMode); GridBagConstraints gbc_geneFivePTwoRadHomoR = new GridBagConstraints(); gbc_geneFivePTwoRadHomoR.weightx = 0.25; gbc_geneFivePTwoRadHomoR.fill = GridBagConstraints.BOTH; gbc_geneFivePTwoRadHomoR.insets = new Insets(0, 0, 5, 0); gbc_geneFivePTwoRadHomoR.gridx = 3; gbc_geneFivePTwoRadHomoR.gridy = 15; parentTwoPanel.add(geneFivePTwoRadHomoR, gbc_geneFivePTwoRadHomoR); //Reset Button resetButton = new JButton("Reset"); resetButton.setBackground(backgroundColor); resetButton.setForeground(textColor); resetButton.addMouseListener(this); GridBagConstraints gbc_resetButton = new GridBagConstraints(); gbc_resetButton.gridwidth = 4; gbc_resetButton.weightx = 1.0; gbc_resetButton.fill = GridBagConstraints.BOTH; gbc_resetButton.gridx = 0; gbc_resetButton.gridy = 20; parentTwoPanel.add(resetButton, gbc_resetButton); //Adding all Parent Two radio buttons to their corresponding ButtonGroups //Gene One Parent Two geneOnePTwoBG = new ButtonGroup(); geneOnePTwoBG.add(geneOnePTwoRadHomoD); geneOnePTwoBG.add(geneOnePTwoRadHetero); geneOnePTwoBG.add(geneOnePTwoRadHomoR); buttonGroupList.add(geneOnePTwoBG); //Gene Two Parent Two geneTwoPTwoBG = new ButtonGroup(); geneTwoPTwoBG.add(geneTwoPTwoRadHomoD); geneTwoPTwoBG.add(geneTwoPTwoRadHetero); geneTwoPTwoBG.add(geneTwoPTwoRadHomoR); buttonGroupList.add(geneTwoPTwoBG); //Gene Three Parent Two geneThreePTwoBG = new ButtonGroup(); geneThreePTwoBG.add(geneThreePTwoRadHomoD); geneThreePTwoBG.add(geneThreePTwoRadHetero); geneThreePTwoBG.add(geneThreePTwoRadHomoR); buttonGroupList.add(geneThreePTwoBG); //Gene Four Parent Two geneFourPTwoBG = new ButtonGroup(); geneFourPTwoBG.add(geneFourPTwoRadHomoD); geneFourPTwoBG.add(geneFourPTwoRadHetero); geneFourPTwoBG.add(geneFourPTwoRadHomoR); buttonGroupList.add(geneFourPTwoBG); //Gene Five Parent Two geneFivePTwoBG = new ButtonGroup(); geneFivePTwoBG.add(geneFivePTwoRadHomoD); geneFivePTwoBG.add(geneFivePTwoRadHetero); geneFivePTwoBG.add(geneFivePTwoRadHomoR); buttonGroupList.add(geneFivePTwoBG); //Results Column resultsPanel = new JPanel(); resultsPanel.setBackground(backgroundColor); resultsPanel.setForeground(textColor); GridBagConstraints gbc_resultsPanel = new GridBagConstraints(); gbc_resultsPanel.insets = new Insets(0, 5, 0, 5); gbc_resultsPanel.gridwidth = 1; gbc_resultsPanel.weighty = 1.0; gbc_resultsPanel.weightx = 0.6; gbc_resultsPanel.fill = GridBagConstraints.BOTH; gbc_resultsPanel.gridx = 2; gbc_resultsPanel.gridy = 0; content.add(resultsPanel, gbc_resultsPanel); GridBagLayout gbl_resultsPanel = new GridBagLayout(); gbl_resultsPanel.columnWidths = new int[]{265, 0, 0, 0, 0, 0}; gbl_resultsPanel.rowHeights = new int[]{14, 525, 22, 0}; gbl_resultsPanel.columnWeights = new double[]{1.0, 0.0, 1.0, 0.0, 0.0, 0.0}; gbl_resultsPanel.rowWeights = new double[]{0.0, 1.0, 1.0, Double.MIN_VALUE}; resultsPanel.setLayout(gbl_resultsPanel); //Results Label JLabel resultsLabel = new JLabel("Results"); resultsLabel.setBackground(backgroundColor); resultsLabel.setForeground(textColor); resultsLabel.setHorizontalAlignment(SwingConstants.CENTER); GridBagConstraints gbc_lblResults = new GridBagConstraints(); gbc_lblResults.gridwidth = 3; gbc_lblResults.insets = new Insets(0, 0, 5, 5); gbc_lblResults.anchor = GridBagConstraints.NORTH; gbc_lblResults.weighty = 0.01; gbc_lblResults.fill = GridBagConstraints.BOTH; gbc_lblResults.gridx = 0; gbc_lblResults.gridy = 0; resultsPanel.add(resultsLabel, gbc_lblResults); //Results JTextArea resultsJTA = new JTextArea(); resultsJTA.setBackground(textFieldColor); resultsJTA.setForeground(textColor); resultsJTA.setEditable(false); resultsJTA.setColumns(1); resultsJTA.setLineWrap(false); resultsJTA.setFont(new Font(javax.swing.UIManager.getDefaults().getFont("Label.font").getFontName(), Font.PLAIN, 14)); GridBagConstraints gbc_resultsJTA = new GridBagConstraints(); gbc_resultsJTA.fill = GridBagConstraints.BOTH; gbc_resultsJTA.gridwidth = 3; gbc_resultsJTA.weightx = 1.0; gbc_resultsJTA.weighty = 1.0; gbc_resultsJTA.gridx = 0; gbc_resultsJTA.gridy = 1; JScrollPane jsp = new JScrollPane(resultsJTA, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); resultsPanel.add(jsp, gbc_resultsJTA); //Error Message Colors UIManager.put("OptionPane.background", new ColorUIResource(215,75,75)); UIManager.put("OptionPane.messageForeground", textColor); UIManager.put("Panel.background", new ColorUIResource(215,75,75)); UIManager.put("JComboBox.disabledBackground", new ColorUIResource(215, 75, 75)); window.pack(); window.setVisible(true); } /** * For Calculate and Reset Buttons. * If event came from the Calculate button, it will run errorCheckGenes() * to verify all selected genes are assigned a symbol and selected alleles * from both parents. * * Reset button will clear all symbol JComboBoxes and ButtonGroups to default. * * @param e MouseEvent */ public void mouseClicked(MouseEvent e) { //Calculation Button if (e.getSource().equals(calcButton)) { //If error checking comes back true, calculate. if (errorCheckGenes()) { startCalculation(); } } //Reset Button else if (e.getSource().equals(resetButton)) { //Resets all JComboBoxes and ButtonGroups to unselected. resetAll(); } } public void mouseEntered(MouseEvent arg0){} public void mouseExited(MouseEvent arg0) {} public void mousePressed(MouseEvent arg0){} public void mouseReleased(MouseEvent arg0){} //For ComboBoxes' selection changes and Radio Button Selections. /** * Activates when a user changes the selected item in a JComboBox. * Depending on the Gene Row it's on, it will enable the JComboBox * of the Gene Row below it. Additionally, it will activate the * current row's ButtonGroups to select a corresponding allele type. * * @param e ItemEvent */ public void itemStateChanged(ItemEvent e) { /* * ItemStateChanged fires twice, one for the deselect of * the default item, and the selection of the new item. * Currently we have no relevant use for the deselect. * So we only care about the even that was a selection. */ if (e.getStateChange() == ItemEvent.SELECTED) { /* * JRadioButton's activate itemStateChanged() as well. * We have a separate method to deal with those and * the ButtonGroups they're assigned to, so we ignore them. */ if (e.getSource() instanceof JComboBox) { //Gene One if (e.getSource().equals(geneOnePOneCombo)) { //If the current item is the default item, don't activate anything as //they need to make their selection in the JComboBox before anything else. if (!(e.getItem().equals(defaultComboItem))) { //If the next JComboBox is disabled(which is should be), call the //JComboBox and ButtonGroups to be enabled. if (!geneTwoPOneCombo.isEnabled()) { geneOnePTwoLabel.setEnabled(true); geneTwoPOneLabel.setEnabled(true); toggleButtonGroup(geneOnePOneBG); toggleButtonGroup(geneOnePTwoBG); toggleNextComboBox(geneTwoPOneCombo); } //Update the ButtonGroup's to reflect the symbol that was selected. updateParentTwoComboBox(geneOnePTwoCombo, geneOnePOneCombo.getSelectedIndex()); updateButtonGroup((String)geneOnePOneCombo.getSelectedItem(), geneOnePOneBG); updateButtonGroup((String)geneOnePOneCombo.getSelectedItem(), geneOnePTwoBG); } //If the JComboBox below the itemEvent is enabled, disable it. //Used to toggle on and off the ButtonGroups as well. else { geneOnePTwoLabel.setEnabled(false); geneTwoPOneLabel.setEnabled(false); toggleButtonGroup(geneOnePOneBG); toggleButtonGroup(geneOnePTwoBG); toggleNextComboBox(geneTwoPOneCombo); updateParentTwoComboBox(geneOnePTwoCombo, geneOnePOneCombo.getSelectedIndex()); updateButtonGroup((String)geneOnePOneCombo.getSelectedItem(), geneOnePOneBG); updateButtonGroup((String)geneOnePOneCombo.getSelectedItem(), geneOnePTwoBG); } } //Gene Two - Same Comments as above, just for GeneTwo instead of GeneOne else if (e.getSource().equals(geneTwoPOneCombo)) { if (!(e.getItem().equals(defaultComboItem))) { if (!geneThreePOneCombo.isEnabled()) { geneTwoPTwoLabel.setEnabled(true); geneThreePOneLabel.setEnabled(true); toggleButtonGroup(geneTwoPOneBG); toggleButtonGroup(geneTwoPTwoBG); toggleNextComboBox(geneThreePOneCombo); } updateParentTwoComboBox(geneTwoPTwoCombo, geneTwoPOneCombo.getSelectedIndex()); updateButtonGroup((String)geneTwoPOneCombo.getSelectedItem(), geneTwoPOneBG); updateButtonGroup((String)geneTwoPOneCombo.getSelectedItem(), geneTwoPTwoBG); } else { geneTwoPTwoLabel.setEnabled(false); geneThreePOneLabel.setEnabled(false); toggleButtonGroup(geneTwoPOneBG); toggleButtonGroup(geneTwoPTwoBG); toggleNextComboBox(geneThreePOneCombo); updateParentTwoComboBox(geneTwoPTwoCombo, geneTwoPOneCombo.getSelectedIndex()); updateButtonGroup((String)geneTwoPOneCombo.getSelectedItem(), geneTwoPOneBG); updateButtonGroup((String)geneTwoPOneCombo.getSelectedItem(), geneTwoPTwoBG); } } //Gene Three - Same Comments as above, just for GeneThree instead of GeneTwo else if (e.getSource().equals(geneThreePOneCombo)) { if (!(e.getItem().equals(defaultComboItem))) { if (!geneFourPOneCombo.isEnabled()) { geneThreePTwoLabel.setEnabled(true); geneFourPOneLabel.setEnabled(true); toggleButtonGroup(geneThreePOneBG); toggleButtonGroup(geneThreePTwoBG); toggleNextComboBox(geneFourPOneCombo); } updateParentTwoComboBox(geneThreePTwoCombo, geneThreePOneCombo.getSelectedIndex()); updateButtonGroup((String)geneThreePOneCombo.getSelectedItem(), geneThreePOneBG); updateButtonGroup((String)geneThreePOneCombo.getSelectedItem(), geneThreePTwoBG); } else { geneThreePTwoLabel.setEnabled(false); geneFourPOneLabel.setEnabled(false); toggleButtonGroup(geneThreePOneBG); toggleButtonGroup(geneThreePTwoBG); toggleNextComboBox(geneFourPOneCombo); updateParentTwoComboBox(geneThreePTwoCombo, geneThreePOneCombo.getSelectedIndex()); updateButtonGroup((String)geneThreePOneCombo.getSelectedItem(), geneThreePOneBG); updateButtonGroup((String)geneThreePOneCombo.getSelectedItem(), geneThreePTwoBG); } } //Gene Four - Same Comments as above, just for GeneFour instead of GeneThree else if (e.getSource().equals(geneFourPOneCombo)) { if (!(e.getItem().equals(defaultComboItem))) { if (!geneFivePOneCombo.isEnabled()) { geneFourPTwoLabel.setEnabled(true); geneFivePOneLabel.setEnabled(true); toggleButtonGroup(geneFourPOneBG); toggleButtonGroup(geneFourPTwoBG); toggleNextComboBox(geneFivePOneCombo); } updateParentTwoComboBox(geneFourPTwoCombo, geneFourPOneCombo.getSelectedIndex()); updateButtonGroup((String)geneFourPOneCombo.getSelectedItem(), geneFourPOneBG); updateButtonGroup((String)geneFourPOneCombo.getSelectedItem(), geneFourPTwoBG); } else { geneFourPTwoLabel.setEnabled(false); geneFivePOneLabel.setEnabled(false); toggleButtonGroup(geneFourPOneBG); toggleButtonGroup(geneFourPTwoBG); toggleNextComboBox(geneFivePOneCombo); updateParentTwoComboBox(geneFourPTwoCombo, geneFourPOneCombo.getSelectedIndex()); updateButtonGroup((String)geneFourPOneCombo.getSelectedItem(), geneFourPOneBG); updateButtonGroup((String)geneFourPOneCombo.getSelectedItem(), geneFourPTwoBG); } } //Gene Five - Same Comments as above, just for GeneFive instead of GeneFour //Except this method has no method below it, so it only concerns itself with //its own ButtonGroup and JComboBoxes. else if (e.getSource().equals(geneFivePOneCombo)) { if (!(e.getItem().equals(defaultComboItem))) { if (geneFivePTwoLabel.isEnabled() == false) { geneFivePTwoLabel.setEnabled(true); toggleButtonGroup(geneFivePOneBG); toggleButtonGroup(geneFivePTwoBG); } updateParentTwoComboBox(geneFivePTwoCombo, geneFivePOneCombo.getSelectedIndex()); updateButtonGroup((String)geneFivePOneCombo.getSelectedItem(), geneFivePOneBG); updateButtonGroup((String)geneFivePOneCombo.getSelectedItem(), geneFivePTwoBG); } else { geneFivePTwoLabel.setEnabled(false); toggleButtonGroup(geneFivePOneBG); toggleButtonGroup(geneFivePTwoBG); updateParentTwoComboBox(geneFivePTwoCombo, geneFivePOneCombo.getSelectedIndex()); updateButtonGroup((String)geneFivePOneCombo.getSelectedItem(), geneFivePOneBG); updateButtonGroup((String)geneFivePOneCombo.getSelectedItem(), geneFivePTwoBG); } } } } } /** * Acts as a toggle switch for ButtonGroups. * Takes in a JRadioButton ButtonGroup, * cycles through the list and if they * are enabled with ItemListeners, disable them. * Otherwise enable them. * * @param buttonGroup ButtonGroup */ private void toggleButtonGroup(ButtonGroup buttonGroup) { //Build Enumeration of the ButtonGroup parameter for use in method. Enumeration<AbstractButton> currentBG = buttonGroup.getElements(); //Cycle through the Enumeration, check each item if they're enabled //and don't have any ItemListeners. If so, enable them. If they //are enabled and have ItemListeners, disable them. while (currentBG.hasMoreElements()) { JRadioButton currentButton = (JRadioButton)currentBG.nextElement(); if (currentButton.isEnabled() && currentButton.getItemListeners().length > 0) { //Makes JRadioButtons to show unselected. buttonGroup.clearSelection(); currentButton.setEnabled(false); currentButton.removeItemListener(this); } else { currentButton.setEnabled(true); currentButton.addItemListener(this); } } } /** * Acts like a switch to toggle the JComboBox * enabled or disabled. If enabled with ItemListeners * remove them, disable the JComboBox, and set the * selected item in the list to the first item(default item) * * @param comboBox JComboBox */ private void toggleNextComboBox(JComboBox<String> comboBox) { if (comboBox.isEnabled() && comboBox.getItemListeners().length > 0) { comboBox.setSelectedIndex(0); comboBox.setEnabled(false); comboBox.removeItemListener(this); } else { comboBox.setEnabled(true); comboBox.addItemListener(this); } } /** * To update ParentTwo's disabled JComboBox. * Takes in a JComboBox, and an int value related to an index position * in the JComboBox. It enables the JComboBox, sets the selected index * to the corresponding index number passed, and disables the JComboBox * again. * * @param comboBox JComboBox * @param indexPos integer */ private void updateParentTwoComboBox(JComboBox<String> comboBox, int indexPos) { comboBox.setEnabled(true); comboBox.setSelectedIndex(indexPos); comboBox.setEnabled(false); } /** * Updates each JRadioButton's Label text in the ButtonGroup given. * The newText parameter must be capitalized. * If this method was called in lieu of deactivating its * ButtonGroup, it will turn the label texts into A equivalents. * * @param labelText String * @param buttonGroup ButtonGroup */ private void updateButtonGroup(String labelText, ButtonGroup buttonGroup) { //If default selected item, use this default text. //Else use what's in newText as the new text for each radio button. if (labelText.equals(defaultComboItem)) { labelText = "A"; } String newTextLowerCase = labelText.toLowerCase(); //Building Enumeration to use on the current ButtonGroup Enumeration<AbstractButton> currentBG = buttonGroup.getElements(); int buttonCtr = 0; //Counter used to make sure the first Button displays //two Uppercase letters, second one Uppercase and one Lowercase, //and finally the third will be both Lowercase letters. while (currentBG.hasMoreElements() && buttonCtr < 3) { JRadioButton currentButton = (JRadioButton)currentBG.nextElement(); if (buttonCtr == 0) { currentButton.setText(labelText + labelText); } else if (buttonCtr == 1) { currentButton.setText(labelText + newTextLowerCase); } else if (buttonCtr == 2) { currentButton.setText(newTextLowerCase + newTextLowerCase); } buttonCtr++; } } /** * Resets the first JComboBox to default, which * cascades through all five potentially active * JComboBoxes to reset them. Also resets the * JTextArea where results are shown. */ private void resetAll() { //Uses ItemListener's Deselect ActionListener to toggle //the JComboBoxes and ButtonGroups geneOnePOneCombo.setSelectedIndex(0); resultsJTA.setText(""); } /** * Checks to see which Gene Rows are enabled. * If enabled, verify they have a selected symbol, * and in each parent's ButtonGroup has a selected * JRadioButton(allele). Otherwise it will add to * the error message, and set the boolean to flag * to false. If the boolean was flagged, it'll * call a error pop-up message to display * which lines have errors. * * @return noErrors boolean */ private boolean errorCheckGenes() { boolean hasNoErrors = true; int numberOfInactiveGenes = 0; //Starter error message. String errorMsg = "ERROR: Please select an allele type for the following:\n"; //Cycles through the five potentially active JComboBoxes to verify //if they're active and if they have ButtonGroups selected. //Used for loop so if we add new JComboBoxes in the future, we can //simply add them to the list, and create an if statement. for (int geneCheck = 0; geneCheck < comboBoxPOneList.size(); geneCheck++) { JComboBox<String> currentComboBox = comboBoxPOneList.get(geneCheck); if (currentComboBox.isEnabled() && currentComboBox.getSelectedIndex() != 0) { //Gene One if (geneCheck == 0) { if (!hasButtonSelected(geneOnePOneBG)) { errorMsg += "Parent One Gene One\n"; hasNoErrors = false; } if (!hasButtonSelected(geneOnePTwoBG)) { errorMsg += "Parent Two Gene One\n"; hasNoErrors = false; } } //Gene Two else if (geneCheck == 1) { if (!hasButtonSelected(geneTwoPOneBG)) { errorMsg += "Parent One Gene Two\n"; hasNoErrors = false; } if (!hasButtonSelected(geneTwoPTwoBG)) { errorMsg += "Parent Two Gene Two\n"; hasNoErrors = false; } } //Gene Three else if (geneCheck == 2) { if (!hasButtonSelected(geneThreePOneBG)) { errorMsg += "Parent One Gene Three\n"; hasNoErrors = false; } if (!hasButtonSelected(geneThreePTwoBG)) { errorMsg += "Parent Two Gene Three\n"; hasNoErrors = false; } } //Gene Four else if (geneCheck == 3) { if (!hasButtonSelected(geneFourPOneBG)) { errorMsg += "Parent One Gene Four\n"; hasNoErrors = false; } if (!hasButtonSelected(geneFourPTwoBG)) { errorMsg += "Parent Two Gene Four\n"; hasNoErrors = false; } } //Gene Five else if (geneCheck == 4) { if (!hasButtonSelected(geneFivePOneBG)) { errorMsg += "Parent One Gene Five\n"; hasNoErrors = false; } if (!hasButtonSelected(geneFivePTwoBG)) { errorMsg += "Parent Two Gene Five\n"; hasNoErrors = false; } } } else { numberOfInactiveGenes++; } } //No genes have been selected. //At least one gene must be used to Calculate. if (numberOfInactiveGenes > 4) { hasNoErrors = false; JOptionPane.showMessageDialog(window, "Please select a gene symbol to calculate."); } //Show error message if the error boolean was flagged. else if (!hasNoErrors) { JOptionPane.showMessageDialog(window, errorMsg); } return hasNoErrors; } /** * This method checks to see if one of the * ButtonGroup's JRadioButtons are selected. * If it finds one, it returns true, otherwise * it returns false. * * @param buttonGroup ButtonGroup * @return isButtonSelected boolean */ private boolean hasButtonSelected(ButtonGroup buttonGroup) { //To cycle through the ButtonGroup parameter. Enumeration<AbstractButton> currentBG = buttonGroup.getElements(); boolean hasOneSelected = false; while (currentBG.hasMoreElements()) { JRadioButton currentButton = (JRadioButton)currentBG.nextElement(); if (currentButton.isSelected()) { hasOneSelected = true; } } return hasOneSelected; } /** * Builds the Genes by checking all five relevant * JComboBoxes. Then gets the boolean value from each * of the corresponding buttons in Parent One and Parent * Two's ButtonGroups. Two parent objects are built with the Genes, * and sent to build the punnett square. Finally, after * built it displays the results. */ private void startCalculation() { Gene[] rawGenePOne = new Gene[5]; Gene[] rawGenePTwo = new Gene[5]; //Gene One if (geneOnePOneCombo.getSelectedIndex() != 0) { //Parent One rawGenePOne[0] = new Gene(geneOnePOneCombo.getSelectedItem().toString(), geneOnePOneRadHetero.isSelected(), geneOnePOneRadHomoD.isSelected(), geneOnePOneRadHomoR.isSelected()); //Parent Two rawGenePTwo[0] = new Gene(geneOnePOneCombo.getSelectedItem().toString(), geneOnePTwoRadHetero.isSelected(), geneOnePTwoRadHomoD.isSelected(), geneOnePTwoRadHomoR.isSelected()); } //Gene Two if (geneTwoPOneCombo.getSelectedIndex() != 0) { //Parent One rawGenePOne[1] = new Gene(geneTwoPOneCombo.getSelectedItem().toString(), geneTwoPOneRadHetero.isSelected(), geneTwoPOneRadHomoD.isSelected(), geneTwoPOneRadHomoR.isSelected()); //Parent Two rawGenePTwo[1] = new Gene(geneTwoPOneCombo.getSelectedItem().toString(), geneTwoPTwoRadHetero.isSelected(), geneTwoPTwoRadHomoD.isSelected(), geneTwoPTwoRadHomoR.isSelected()); } //Gene Three if (geneThreePOneCombo.getSelectedIndex() != 0) { //Parent One rawGenePOne[2] = new Gene(geneThreePOneCombo.getSelectedItem().toString(), geneThreePOneRadHetero.isSelected(), geneThreePOneRadHomoD.isSelected(), geneThreePOneRadHomoR.isSelected()); //Parent Two rawGenePTwo[2] = new Gene(geneThreePOneCombo.getSelectedItem().toString(), geneThreePTwoRadHetero.isSelected(), geneThreePTwoRadHomoD.isSelected(), geneThreePTwoRadHomoR.isSelected()); } //Gene Four if (geneFourPOneCombo.getSelectedIndex() != 0) { //Parent One rawGenePOne[3] = new Gene(geneFourPOneCombo.getSelectedItem().toString(), geneFourPOneRadHetero.isSelected(), geneFourPOneRadHomoD.isSelected(), geneFourPOneRadHomoR.isSelected()); //Parent Two rawGenePTwo[3] = new Gene(geneFourPOneCombo.getSelectedItem().toString(), geneFourPTwoRadHetero.isSelected(), geneFourPTwoRadHomoD.isSelected(), geneFourPTwoRadHomoR.isSelected()); } //Gene Five if (geneFivePOneCombo.getSelectedIndex() != 0) { //Parent One rawGenePOne[4] = new Gene(geneFivePOneCombo.getSelectedItem().toString(), geneFivePOneRadHetero.isSelected(), geneFivePOneRadHomoD.isSelected(), geneFivePOneRadHomoR.isSelected()); //Parent Two rawGenePTwo[4] = new Gene(geneFivePOneCombo.getSelectedItem().toString(), geneFivePTwoRadHetero.isSelected(), geneFivePTwoRadHomoD.isSelected(), geneFivePTwoRadHomoR.isSelected()); } //Build parents, and set their Genes. Parent parentOne = new Parent(); parentOne.setRawGenes(rawGenePOne); Parent parentTwo = new Parent(); parentTwo.setRawGenes(rawGenePTwo); //Send to PunnettMe for Calculating. pm.build(parentOne, parentTwo); //Output the results to the results JTextArea. outputResults(pm.getResults()); } /** * Takes the ArrayList of offspring results, * and outputs them line by line to the results JTextArea * * @param results List */ private void outputResults(List<String> results) { //To reset the JTextArea to start from empty. resultsJTA.setText(""); //Cycles through offspring to output to JTextArea. for (int output = results.size()-1; output >= 0 ; output--) { resultsJTA.append(results.get(output) + "\n"); } //Outputs the size of the ArrayList as the total offspring accounted for. resultsJTA.append(results.size() + " total offspring"); //Sets the viewing area of the JTextArea to be the very beginning. //As you append to the JTextArea, it will set the position to the //end of the list. This way it starts at the top. resultsJTA.setCaretPosition(0); } }
true
deb3519f91914361963c8dd1cd184051cea808c4
Java
degrize/jhipster-sample-application
/src/main/java/com/mycompany/myapp/domain/enumeration/Sexe.java
UTF-8
117
1.789063
2
[]
no_license
package com.mycompany.myapp.domain.enumeration; /** * The Sexe enumeration. */ public enum Sexe { F, M, }
true
778d4610c6c3fc498a206cfe1b78b8064f23330b
Java
vel-adr/moop-final-test
/app/src/main/java/com/example/moop_uas/MainActivity.java
UTF-8
2,682
2.046875
2
[]
no_license
package com.example.moop_uas; import androidx.appcompat.app.AppCompatActivity; import androidx.room.Room; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; public class MainActivity extends AppCompatActivity { Button btn_next, btn_show; Spinner spinner_bangsal, spinner_penyakit; public static PasienDatabase db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Mendapatkan semua komponen yang dibutuhkan btn_next = findViewById(R.id.btn_next); btn_show = findViewById(R.id.btn_show); spinner_bangsal = findViewById(R.id.spinner_bangsal); spinner_penyakit = findViewById(R.id.spinner_penyakit); //Inisialisasi database db = Room.databaseBuilder(getApplicationContext(), PasienDatabase.class, "uasmoop").allowMainThreadQueries().build(); //Mengisi pilihan spinner ArrayAdapter<CharSequence> adapterBangsal = ArrayAdapter.createFromResource(this, R.array.spinner_bangsal_item, android.R.layout.simple_spinner_item); adapterBangsal.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner_bangsal.setAdapter(adapterBangsal); ArrayAdapter<CharSequence> adapterPenyakit = ArrayAdapter.createFromResource(this, R.array.spinner_penyakit_item, android.R.layout.simple_spinner_item); adapterPenyakit.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner_penyakit.setAdapter(adapterPenyakit); //Menambahkan onClickListener untuk button btn_next.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBtnClick(v); } }); btn_show.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onShowBtnClick(v); } }); } public void onBtnClick(View view){ String bangsal = spinner_bangsal.getSelectedItem().toString(); String penyakit = spinner_penyakit.getSelectedItem().toString(); Intent i = new Intent(this, ChecklistFormActivity.class); i.putExtra("bangsal", bangsal); i.putExtra("penyakit", penyakit); startActivity(i); } public void onShowBtnClick(View view){ Intent i = new Intent(this, ListPasienActivity.class); startActivity(i); } }
true
205baef3aa60b1b2fbe4fea57480a12ce42ede33
Java
qaamishra/CoreJava
/src/main/java/problems/simple/LoopPerfect.java
UTF-8
658
3.75
4
[]
no_license
package problems.simple; import java.util.Scanner; public class LoopPerfect { private static Scanner scanner; public static void main(String[] args) { scanner = new Scanner(System.in); System.out.println("Enter a range to list perfect numbers :"); int range = scanner.nextInt(); //Enter 6 for (int num = 1; num <= range; num++) { int sum = 0; for (int z = 1; z <= num; z++) { if (num % z == 0) sum = sum + z; } if (sum == (2 * num)) System.out.println(num + " is a perfect number"); } } }
true
15f3ebba76b25267cd720977ff909d6df3a21a84
Java
AzureHanChen/AdvantageBedwars
/src/main/java/me/faintcloudy/bedwars/utils/BukkitReflection.java
UTF-8
20,409
2.015625
2
[ "Apache-2.0" ]
permissive
/* */ package me.faintcloudy.bedwars.utils; /* */ /* */ import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Server; import org.bukkit.Sound; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public class BukkitReflection /* */ { /* */ private static final String CRAFT_BUKKIT_PACKAGE; /* */ private static final String NET_MINECRAFT_SERVER_PACKAGE; /* */ private static final Class CRAFT_SERVER_CLASS; /* */ private static final Method CRAFT_SERVER_GET_HANDLE_METHOD; /* */ private static final Class PLAYER_LIST_CLASS; /* */ private static final Field PLAYER_LIST_MAX_PLAYERS_FIELD; /* */ private static final Class CRAFT_PLAYER_CLASS; /* */ private static final Method CRAFT_PLAYER_GET_HANDLE_METHOD; /* */ private static final Class ENTITY_PLAYER_CLASS; /* */ private static final Field ENTITY_PLAYER_PING_FIELD; /* */ private static final Class CRAFT_ITEM_STACK_CLASS; /* */ private static final Method CRAFT_ITEM_STACK_AS_NMS_COPY_METHOD; /* */ /* */ public static void sendLightning(Player p, Location l) { /* 32 */ Class<?> light = getNMSClass("EntityLightning"); /* */ /* */ try { /* 35 */ assert light != null; /* 36 */ Constructor<?> constu = light.getConstructor(new Class[] { getNMSClass("World"), double.class, double.class, double.class, boolean.class, boolean.class }); /* 37 */ Object wh = p.getWorld().getClass().getMethod("getHandle", new Class[0]).invoke(p.getWorld(), new Object[0]); /* 38 */ Object lighobj = constu.newInstance(new Object[] { wh, Double.valueOf(l.getX()), Double.valueOf(l.getY()), Double.valueOf(l.getZ()), Boolean.valueOf(true), Boolean.valueOf(true) }); /* 39 */ Object obj = getNMSClass("PacketPlayOutSpawnEntityWeather").getConstructor(new Class[] { getNMSClass("Entity") }).newInstance(new Object[] { lighobj }); /* 40 */ sendPacket(p, obj); /* 41 */ p.playSound(p.getLocation(), Sound.AMBIENCE_THUNDER, 100.0F, 1.0F); /* 42 */ } catch (SecurityException|IllegalAccessException|IllegalArgumentException|InvocationTargetException|InstantiationException|NoSuchMethodException var7) { /* 43 */ var7.printStackTrace(); /* */ } /* */ } /* */ /* */ /* */ public static Class<?> getNMSClass(String name) { /* 49 */ String version = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3]; /* */ /* */ try { /* 52 */ return Class.forName("net.minecraft.server." + version + "." + name); /* 53 */ } catch (ClassNotFoundException var3) { /* 54 */ var3.printStackTrace(); /* 55 */ return null; /* */ } /* */ } /* */ /* */ public static void sendPacket(Player player, Object packet) { /* */ try { /* 61 */ Object handle = player.getClass().getMethod("getHandle", new Class[0]).invoke(player, new Object[0]); /* 62 */ Object playerConnection = handle.getClass().getField("playerConnection").get(handle); /* 63 */ playerConnection.getClass().getMethod("sendPacket", new Class[] { getNMSClass("Packet") }).invoke(playerConnection, new Object[] { packet }); /* 64 */ } catch (Exception var4) { /* 65 */ var4.printStackTrace(); /* */ } /* */ } /* */ /* */ /* */ public static int getPing(Player player) { /* */ try { /* 72 */ int ping = ENTITY_PLAYER_PING_FIELD.getInt(CRAFT_PLAYER_GET_HANDLE_METHOD.invoke(player, new Object[0])); /* 73 */ return Math.max(ping, 0); /* 74 */ } catch (Exception var2) { /* 75 */ return 1; /* */ } /* */ } /* */ /* */ public static void setMaxPlayers(Server server, int slots) { /* */ try { /* 81 */ PLAYER_LIST_MAX_PLAYERS_FIELD.set(CRAFT_SERVER_GET_HANDLE_METHOD.invoke(server, new Object[0]), Integer.valueOf(slots)); /* 82 */ } catch (Exception var3) { /* 83 */ var3.printStackTrace(); /* */ } /* */ } /* */ /* */ /* */ public static String getItemStackName(ItemStack itemStack) { /* */ try { /* 90 */ return (String)CRAFT_ITEM_STACK_AS_NMS_COPY_METHOD.invoke(itemStack, new Object[] { itemStack }); /* 91 */ } catch (Exception var2) { /* 92 */ var2.printStackTrace(); /* 93 */ return ""; /* */ } /* */ } /* */ public static Class<?> getClass(String name) { /* 97 */ String version = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3]; /* */ try { /* 99 */ return Class.forName("org.bukkit.craftbukkit." + version + "." + name); /* 100 */ } catch (Exception e) { /* 101 */ e.printStackTrace(); /* 102 */ return null; /* */ } /* */ } /* */ /* */ public static Constructor<?> getConstructor(Class<?> clazz, Class<?>... parameterTypes) throws NoSuchMethodException { /* 107 */ Class<?>[] primitiveTypes = DataType.getPrimitive(parameterTypes); /* 108 */ for (Constructor<?> constructor : clazz.getConstructors()) { /* 109 */ if (DataType.compare(DataType.getPrimitive(constructor.getParameterTypes()), primitiveTypes)) /* 110 */ return constructor; /* */ } /* 112 */ throw new NoSuchMethodException("There is no such constructor in this class with the specified parameter types"); /* */ } /* */ /* */ /* */ /* */ public static Constructor<?> getConstructor(String className, PackageType packageType, Class<?>... parameterTypes) throws NoSuchMethodException, ClassNotFoundException { /* 118 */ return getConstructor(packageType.getClass(className), parameterTypes); /* */ } /* */ /* */ /* */ public static Object instantiateObject(Class<?> clazz, Object... arguments) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException { /* 123 */ return getConstructor(clazz, DataType.getPrimitive(arguments)).newInstance(arguments); /* */ } /* */ /* */ /* */ /* */ public static Object instantiateObject(String className, PackageType packageType, Object... arguments) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException { /* 129 */ return instantiateObject(packageType.getClass(className), arguments); /* */ } /* */ /* */ /* */ public static Method getMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes) throws NoSuchMethodException { /* 134 */ Class<?>[] primitiveTypes = DataType.getPrimitive(parameterTypes); /* 135 */ for (Method method : clazz.getMethods()) { /* 136 */ if (method.getName().equals(methodName) && /* 137 */ DataType.compare(DataType.getPrimitive(method.getParameterTypes()), primitiveTypes)) /* 138 */ return method; /* */ } /* 140 */ throw new NoSuchMethodException("There is no such method in this class with the specified name and parameter types"); /* */ } /* */ /* */ /* */ /* */ public static Method getMethod(String className, PackageType packageType, String methodName, Class<?>... parameterTypes) throws NoSuchMethodException, ClassNotFoundException { /* 146 */ return getMethod(packageType.getClass(className), methodName, parameterTypes); /* */ } /* */ /* */ /* */ public static Object invokeMethod(Object instance, String methodName, Object... arguments) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException { /* 151 */ return getMethod(instance.getClass(), methodName, DataType.getPrimitive(arguments)).invoke(instance, arguments); /* */ } /* */ /* */ /* */ public static Object invokeMethod(Object instance, Class<?> clazz, String methodName, Object... arguments) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException { /* 156 */ return getMethod(clazz, methodName, DataType.getPrimitive(arguments)).invoke(instance, arguments); /* */ } /* */ /* */ /* */ /* */ public static Object invokeMethod(Object instance, String className, PackageType packageType, String methodName, Object... arguments) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException { /* 162 */ return invokeMethod(instance, packageType.getClass(className), methodName, arguments); /* */ } /* */ /* */ /* */ public static Field getField(Class<?> clazz, boolean declared, String fieldName) throws NoSuchFieldException, SecurityException { /* 167 */ Field field = declared ? clazz.getDeclaredField(fieldName) : clazz.getField(fieldName); /* 168 */ field.setAccessible(true); /* 169 */ return field; /* */ } /* */ /* */ /* */ public static Field getField(String className, PackageType packageType, boolean declared, String fieldName) throws NoSuchFieldException, SecurityException, ClassNotFoundException { /* 174 */ return getField(packageType.getClass(className), declared, fieldName); /* */ } /* */ /* */ /* */ public static Object getValue(Object instance, Class<?> clazz, boolean declared, String fieldName) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { /* 179 */ return getField(clazz, declared, fieldName).get(instance); /* */ } /* */ /* */ /* */ /* */ public static Object getValue(Object instance, String className, PackageType packageType, boolean declared, String fieldName) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException, ClassNotFoundException { /* 185 */ return getValue(instance, packageType.getClass(className), declared, fieldName); /* */ } /* */ /* */ /* */ public static Object getValue(Object instance, boolean declared, String fieldName) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { /* 190 */ return getValue(instance, instance.getClass(), declared, fieldName); /* */ } /* */ /* */ /* */ public static void setValue(Object instance, Class<?> clazz, boolean declared, String fieldName, Object value) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { /* 195 */ getField(clazz, declared, fieldName).set(instance, value); /* */ } /* */ /* */ /* */ /* */ public static void setValue(Object instance, String className, PackageType packageType, boolean declared, String fieldName, Object value) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException, ClassNotFoundException { /* 201 */ setValue(instance, packageType.getClass(className), declared, fieldName, value); /* */ } /* */ /* */ /* */ public static void setValue(Object instance, boolean declared, String fieldName, Object value) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { /* 206 */ setValue(instance, instance.getClass(), declared, fieldName, value); /* */ } /* */ /* */ public enum PackageType { /* 210 */ MINECRAFT_SERVER("net.minecraft.server." + getServerVersion()), CRAFTBUKKIT("org.bukkit.craftbukkit." + /* 211 */ getServerVersion() + "."), CRAFTBUKKIT_BLOCK(CRAFTBUKKIT.getPath() + "block"), CRAFTBUKKIT_CHUNKIO(CRAFTBUKKIT.getPath() + "chunkio"), /* 212 */ CRAFTBUKKIT_COMMAND(CRAFTBUKKIT.getPath() + "command"), CRAFTBUKKIT_CONVERSATIONS(CRAFTBUKKIT.getPath() + "conversations"), /* 213 */ CRAFTBUKKIT_ENCHANTMENS(CRAFTBUKKIT.getPath() + "enchantments"), /* 214 */ CRAFTBUKKIT_ENTITY(CRAFTBUKKIT.getPath() + "entity"), CRAFTBUKKIT_EVENT(CRAFTBUKKIT.getPath() + "event"), /* 215 */ CRAFTBUKKIT_GENERATOR(CRAFTBUKKIT.getPath() + "generator"), /* 216 */ CRAFTBUKKIT_HELP(CRAFTBUKKIT.getPath() + "help"), /* 217 */ CRAFTBUKKIT_INVENTORY(CRAFTBUKKIT.getPath() + "inventory"), /* 218 */ CRAFTBUKKIT_MAP(CRAFTBUKKIT.getPath() + "map"), /* 219 */ CRAFTBUKKIT_METADATA(CRAFTBUKKIT.getPath() + "metadata"), /* */ /* 221 */ CRAFTBUKKIT_POTION(CRAFTBUKKIT.getPath() + "potion"), /* */ /* 223 */ CRAFTBUKKIT_PROJECTILES(CRAFTBUKKIT.getPath() + "projectiles"), /* */ /* 225 */ CRAFTBUKKIT_SCHEDULER(CRAFTBUKKIT.getPath() + "scheduler"), /* */ /* 227 */ CRAFTBUKKIT_SCOREBOARD(CRAFTBUKKIT.getPath() + "scoreboard"), /* */ /* 229 */ CRAFTBUKKIT_UPDATER(CRAFTBUKKIT.getPath() + "updater"), /* */ /* 231 */ CRAFTBUKKIT_UTIL(CRAFTBUKKIT.getPath() + "util"); /* */ /* */ /* */ private final String path; /* */ /* */ /* */ PackageType(String path) { /* 238 */ this.path = path; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ public String getPath() { /* 246 */ return this.path; /* */ } /* */ /* */ public Class<?> getClass(String className) throws ClassNotFoundException { /* 250 */ return Class.forName(this + "." + className); /* */ } /* */ /* */ /* */ public String toString() { /* 255 */ return this.path; /* */ } /* */ /* */ public static String getServerVersion() { /* 259 */ return Bukkit.getServer().getClass().getPackage().getName().substring(23); /* */ } /* */ } /* */ /* */ public enum DataType { /* 264 */ BYTE(byte.class, Byte.class), SHORT(short.class, Short.class), INTEGER(int.class, Integer.class), LONG(long.class, Long.class), /* 265 */ CHARACTER(char.class, Character.class), FLOAT(float.class, Float.class), /* 266 */ DOUBLE(double.class, Double.class), BOOLEAN(boolean.class, Boolean.class); /* */ /* */ /* */ /* */ /* */ /* */ /* 273 */ private static final Map<Class<?>, DataType> CLASS_MAP = new HashMap<>(); private final Class<?> primitive; static { /* 274 */ for (DataType type : values()) { /* 275 */ CLASS_MAP.put(type.primitive, type); /* 276 */ CLASS_MAP.put(type.reference, type); /* */ } /* */ } /* */ private final Class<?> reference; /* */ DataType(Class<?> primitive, Class<?> reference) { /* 281 */ this.primitive = primitive; /* 282 */ this.reference = reference; /* */ } /* */ /* */ public Class<?> getPrimitive() { /* 286 */ return this.primitive; /* */ } /* */ /* */ public Class<?> getReference() { /* 290 */ return this.reference; /* */ } /* */ /* */ public static DataType fromClass(Class<?> clazz) { /* 294 */ return CLASS_MAP.get(clazz); /* */ } /* */ /* */ public static Class<?> getPrimitive(Class<?> clazz) { /* 298 */ DataType type = fromClass(clazz); /* 299 */ return (type == null) ? clazz : type.getPrimitive(); /* */ } /* */ /* */ public static Class<?> getReference(Class<?> clazz) { /* 303 */ DataType type = fromClass(clazz); /* 304 */ return (type == null) ? clazz : type.getReference(); /* */ } /* */ /* */ public static Class<?>[] getPrimitive(Class<?>[] classes) { /* 308 */ int length = (classes == null) ? 0 : classes.length; /* 309 */ Class<?>[] types = new Class[length]; /* 310 */ for (int index = 0; index < length; index++) { /* 311 */ types[index] = getPrimitive(classes[index]); /* */ } /* 313 */ return types; /* */ } /* */ /* */ public static Class<?>[] getReference(Class<?>[] classes) { /* 317 */ int length = (classes == null) ? 0 : classes.length; /* 318 */ Class<?>[] types = new Class[length]; /* 319 */ for (int index = 0; index < length; index++) { /* 320 */ types[index] = getReference(classes[index]); /* */ } /* 322 */ return types; /* */ } /* */ /* */ public static Class<?>[] getPrimitive(Object[] objects) { /* 326 */ int length = (objects == null) ? 0 : objects.length; /* 327 */ Class<?>[] types = new Class[length]; /* 328 */ for (int index = 0; index < length; index++) { /* 329 */ types[index] = getPrimitive(objects[index].getClass()); /* */ } /* 331 */ return types; /* */ } /* */ /* */ public static Class<?>[] getReference(Object[] objects) { /* 335 */ int length = (objects == null) ? 0 : objects.length; /* 336 */ Class<?>[] types = new Class[length]; /* 337 */ for (int index = 0; index < length; index++) { /* 338 */ types[index] = getReference(objects[index].getClass()); /* */ } /* 340 */ return types; /* */ } /* */ /* */ public static boolean compare(Class<?>[] primary, Class<?>[] secondary) { /* 344 */ if (primary == null || secondary == null || primary.length != secondary.length) /* 345 */ return false; /* 346 */ for (int index = 0; index < primary.length; index++) { /* 347 */ Class<?> primaryClass = primary[index]; /* 348 */ Class<?> secondaryClass = secondary[index]; /* 349 */ if (!primaryClass.equals(secondaryClass) && !primaryClass.isAssignableFrom(secondaryClass)) /* 350 */ return false; /* */ } /* 352 */ return true; /* */ } } /* */ /* */ static { /* */ try { /* 357 */ String version = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; /* 358 */ CRAFT_BUKKIT_PACKAGE = "org.bukkit.craftbukkit." + version + "."; /* 359 */ NET_MINECRAFT_SERVER_PACKAGE = "net.minecraft.server." + version + "."; /* 360 */ CRAFT_SERVER_CLASS = Class.forName(CRAFT_BUKKIT_PACKAGE + "CraftServer"); /* 361 */ CRAFT_SERVER_GET_HANDLE_METHOD = CRAFT_SERVER_CLASS.getDeclaredMethod("getHandle", new Class[0]); /* 362 */ CRAFT_SERVER_GET_HANDLE_METHOD.setAccessible(true); /* 363 */ PLAYER_LIST_CLASS = Class.forName(NET_MINECRAFT_SERVER_PACKAGE + "PlayerList"); /* 364 */ PLAYER_LIST_MAX_PLAYERS_FIELD = PLAYER_LIST_CLASS.getDeclaredField("maxPlayers"); /* 365 */ PLAYER_LIST_MAX_PLAYERS_FIELD.setAccessible(true); /* 366 */ CRAFT_PLAYER_CLASS = Class.forName(CRAFT_BUKKIT_PACKAGE + "entity.CraftPlayer"); /* 367 */ CRAFT_PLAYER_GET_HANDLE_METHOD = CRAFT_PLAYER_CLASS.getDeclaredMethod("getHandle", new Class[0]); /* 368 */ CRAFT_PLAYER_GET_HANDLE_METHOD.setAccessible(true); /* 369 */ ENTITY_PLAYER_CLASS = Class.forName(NET_MINECRAFT_SERVER_PACKAGE + "EntityPlayer"); /* 370 */ ENTITY_PLAYER_PING_FIELD = ENTITY_PLAYER_CLASS.getDeclaredField("ping"); /* 371 */ ENTITY_PLAYER_PING_FIELD.setAccessible(true); /* 372 */ CRAFT_ITEM_STACK_CLASS = Class.forName(CRAFT_BUKKIT_PACKAGE + "inventory.CraftItemStack"); /* 373 */ CRAFT_ITEM_STACK_AS_NMS_COPY_METHOD = CRAFT_ITEM_STACK_CLASS.getDeclaredMethod("asNMSCopy", new Class[] { ItemStack.class }); /* 374 */ CRAFT_ITEM_STACK_AS_NMS_COPY_METHOD.setAccessible(true); /* 375 */ } catch (Exception var1) { /* 376 */ var1.printStackTrace(); /* 377 */ throw new RuntimeException("Failed to initialize Bukkit/NMS Reflection"); /* */ } /* */ } /* */ } /* Location: C:\Users\Administrator\Desktop\IBedwars-1.0-SNAPSHOT.jar!\me\huanmeng\ibedwar\\utils\BukkitReflection.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
true
a3522ac40061ea56a45b206af8930a0cc33cf7bd
Java
dasmanas/practice_ws
/src/main/java/com/practice/sort/InsertionSort.java
UTF-8
977
3.71875
4
[]
no_license
package com.practice.sort; public class InsertionSort { public void sort(int arr[]){ int arrLength = arr.length; for (int i = 0; i < arrLength; i++) { int valueOnLeftShift = arr[i]; int compareIndex = i-1; while (compareIndex >= 0 && (valueOnLeftShift < arr[compareIndex])){ arr[compareIndex+1] = arr[compareIndex]; arr[compareIndex] = valueOnLeftShift; compareIndex --; } showArray(arr); } } public void showArray(int arr[]){ int arrLen = arr.length; for (int i = 0; i < arrLen; i++) { System.out.print(arr[i]+", "); } System.out.println(); } public static void main(String args[]){ InsertionSort insertionSortObj = new InsertionSort(); int arr[] = {2, 8, 5, 3, 9, 4}; insertionSortObj.showArray(arr); insertionSortObj.sort(arr); } }
true
35cdb3508880f601202aa584fb372d2f7594366a
Java
quarkusio/quarkus
/extensions/smallrye-graphql/deployment/src/test/java/io/quarkus/smallrye/graphql/deployment/InjectRoutingContextTest.java
UTF-8
1,627
2.203125
2
[ "Apache-2.0" ]
permissive
package io.quarkus.smallrye.graphql.deployment; import static org.hamcrest.Matchers.containsString; import jakarta.inject.Inject; import org.eclipse.microprofile.graphql.GraphQLApi; import org.eclipse.microprofile.graphql.Query; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import io.quarkus.test.QuarkusUnitTest; import io.restassured.RestAssured; import io.vertx.ext.web.RoutingContext; /** * Make sure that it is possible to inject and use the RoutingContext * when processing GraphQL queries. */ public class InjectRoutingContextTest extends AbstractGraphQLTest { @RegisterExtension static QuarkusUnitTest test = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClass(InjectRoutingContext.class) .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")); @Test public void verifyRoutingContextCanBeInjected() { String query = getPayload("{ foo }"); RestAssured.given() .body(query) .header("Tenant-Id", "123456") .contentType(MEDIATYPE_JSON) .post("/graphql") .then() .assertThat() .statusCode(200) .body(containsString("123456")); } @GraphQLApi public static class InjectRoutingContext { @Inject RoutingContext routingContext; @Query public String foo() { return routingContext.request().getHeader("Tenant-Id"); } } }
true
7a965837044bdd40cdfc97a152d381df31184c5d
Java
nitinnatural/NoteApp-Dagger2
/app/src/main/java/com/example/stayabode/presentation/di/component/AppComponent.java
UTF-8
908
1.789063
2
[]
no_license
package com.example.stayabode.presentation.di.component; import com.example.stayabode.data.source.NotesRepository; import com.example.stayabode.presentation.StayAbodeApplication; import com.example.stayabode.presentation.di.AppScope; import com.example.stayabode.presentation.di.modules.AppModule; import com.example.stayabode.presentation.screens.edit_note.EditNoteActivity; import com.example.stayabode.presentation.screens.new_note.NewNoteActivity; import com.example.stayabode.presentation.screens.notes_list.NotesListActivity; import dagger.Component; /** * Created by Prakhar on 11/30/2017. */ @AppScope @Component(modules = {AppModule.class}) public interface AppComponent { void inject(StayAbodeApplication perpuleApplication); void inject(NotesListActivity notesListActivity); void inject(NewNoteActivity newNoteActivity); void inject(EditNoteActivity editNoteActivity); }
true
d4f20ba38714c469d8960d6fed2fc0572fa462d7
Java
hansy0122/day15
/Stream/GroupingAndReductionExample.java
UTF-8
1,680
3.59375
4
[]
no_license
package day15.Stream; import java.util.*; import java.util.stream.Collectors; public class GroupingAndReductionExample { public static void main(String ar[]){ List<Student_E> totalList =Arrays.asList(new Student_E("A",10,Student_E.Sex.MALE), new Student_E("B",6,Student_E.Sex.MALE),new Student_E("C",18,Student_E.Sex.FEMALE), new Student_E("D",9,Student_E.Sex.FEMALE)); // key:sex value: avg Map<Student_E.Sex, Double> mapBySex =totalList.stream(). collect(Collectors.groupingBy(Student_E::getSex, Collectors.averagingDouble(Student_E::getScore))); System.out.println("average of male="+mapBySex.get(Student_E.Sex.MALE)); System.out.println("average of female="+mapBySex.get(Student_E.Sex.FEMALE)); // key: sex value: String(name, name, name) Map<Student_E.Sex,String> mapByName = totalList.stream().collect( Collectors.groupingByConcurrent(Student_E::getSex, Collectors.mapping(Student_E::getName, Collectors.joining(",")))); System.out.println("name of male="+ mapByName.get(Student_E.Sex.MALE)); System.out.println("name of female="+ mapByName.get(Student_E.Sex.FEMALE)); } } class Student_E{ public enum Sex {MALE,FEMALE} public enum City{Seoul,pusan} private String name; private int score; private Sex sex; private City city; public Student_E(String n,int s,Sex sex){ this.name=n; this.score=s; this.sex=sex; } public Student_E(String n,int s,Sex sex,City city){ this.name=n; this.score=s; this.sex=sex; this.city=city; } public Sex getSex() { return sex; } public City getCity() { return city; } public String getName() { return name; } public int getScore() { return score; } }
true
eb044f22bbffe8ad28f95528096c13933316d539
Java
timothyhahn/DrexelEXP
/src/main/java/com/drexelexp/user/User.java
UTF-8
2,992
3.046875
3
[]
no_license
package com.drexelexp.user; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Model for the User object * @author Timothy Hahn * */ public class User { private int id; private String email; private String name = ""; private String password = ""; private String confPassword = ""; private String university; private boolean active; private boolean moderator; /** * Default Constructor * Purpose: Should never be used */ public User() { this.setId(-1); this.setEmail(""); this.setUniversity(""); this.setActive(true); this.setModerator(false); } /** * Minimal Constructor * Purpose: The bare minimum for an active user * @param id Auto generated ID * @param email User's e-mail */ public User(int id, String email, boolean isModerator) { this.setId(id); this.setEmail(email); this.setUniversity(findUniversity(email)); this.setActive(true); this.setModerator(isModerator); } /** * Helper Functions */ /** * Finds the university name from the e-mail given. * @param email * @return */ private String findUniversity(String email) { return ""; } /** * Accesors and Mutators */ public int getId() { return id; } public void setId(int id) { this.id = id; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUniversity() { return university; } public void setUniversity(String university) { this.university = university; } public boolean getModerator() { return moderator; } public void setModerator(boolean moderator) { this.moderator = moderator; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } public void create() { } public String getConfPassword() { return confPassword; } public void setConfPassword(String confPassword) { this.confPassword = confPassword; } public String isValid() { //Check email is valid final String email_regex = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; Pattern emailPattern = Pattern.compile(email_regex); Matcher emailMatcher = emailPattern.matcher(email); if(!emailMatcher.matches()) { return "Your e-mail is not valid. Please check your e-mail for any errors."; } //Check password exists if(password.isEmpty()) { return "Please input a password."; } //Check conf password exists if(confPassword.isEmpty()) { return "Please confirm your password below."; } //Check passwords match if(!password.equals(confPassword)) { return "Your passwords do not match. Please ensure your confirmation password matches."; } return ""; } }
true
883a51580cfdc85e36ebcbb6e8e12c591ecb0074
Java
MarinaBekavac/Java
/src/main/java/sample/DodavanjeNoveBolestiController.java
UTF-8
2,940
2.5
2
[]
no_license
package main.java.sample; import hr.java.covidportal.load.BazaPodataka; import hr.java.covidportal.model.Bolest; import hr.java.covidportal.model.Simptom; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.control.*; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import static hr.java.covidportal.load.Loaders.dodajBolestUDatoteku; import static hr.java.covidportal.load.Loaders.ucitajSimptome; public class DodavanjeNoveBolestiController { @FXML private TextField nazivBolestiField; @FXML ListView<Simptom> simptomiBolestiList; @FXML public void initialize(){ //ObservableList<Simptom> listaSimptoma = FXCollections.observableList(ucitajSimptome()); ObservableList<Simptom> listaSimptoma = null; try { listaSimptoma = FXCollections. observableList(BazaPodataka.dohvatiSveSimptome()); } catch (SQLException throwables) { throwables.printStackTrace(); } //simptomiBolestiList.setItems(listaSimptoma); simptomiBolestiList.getItems().setAll(listaSimptoma); simptomiBolestiList.getSelectionModel(). setSelectionMode(SelectionMode.MULTIPLE); } @FXML public void dodajBolest(){ String naziv = nazivBolestiField.getText(); ObservableList<Simptom> odabraniSimptomi = simptomiBolestiList. getSelectionModel().getSelectedItems(); List<Simptom> listaOdabranihSimptoma = new ArrayList<>(); for(Simptom s : odabraniSimptomi) listaOdabranihSimptoma.add(s); Bolest b = new Bolest(naziv,listaOdabranihSimptoma,PretragaBolestiController.getId()); //int correct = dodajBolestUDatoteku(b); int correct = 1; if(naziv.equals("")) correct = 0; if(correct==1) { Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle("Alert window"); alert.setHeaderText("Uspjesno dodavanje bolesti;"); alert.setContentText("Vasa bolest je uspjesno dodana u listu bolesti"); alert.showAndWait(); //dodajBolestUDatoteku(b); try { BazaPodataka.spremiNovuBolest(b); } catch (SQLException throwables) { throwables.printStackTrace(); } } else{ Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle("Alert window"); alert.setHeaderText("Neuspjesno dodavanje bolesti;"); alert.setContentText("Vasa bolest NIJE uspjesno dodana u listu bolesti"); alert.showAndWait(); } PretragaBolestiController.dodajBolest(b); } }
true
2605a003ad20cb53a94f268932baa40c9487172f
Java
kelu124/pyS3
/org/apache/poi/ddf/EscherShapePathProperty.java
UTF-8
471
1.875
2
[ "MIT" ]
permissive
package org.apache.poi.ddf; public class EscherShapePathProperty extends EscherSimpleProperty { public static final int CLOSED_CURVES = 3; public static final int CLOSED_POLYGON = 1; public static final int COMPLEX = 4; public static final int CURVES = 2; public static final int LINE_OF_STRAIGHT_SEGMENTS = 0; public EscherShapePathProperty(short propertyNumber, int shapePath) { super(propertyNumber, false, false, shapePath); } }
true
59d1f6f18d9dab267d5fd88b2b8295605a3e1ffa
Java
rcamacholci/Transito
/src/java/modelo/Rein.java
UTF-8
567
2.453125
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package modelo; /** * * @author acer */ import java.io.*; import java.sql.*; public class Rein implements Serializable { private String id_banco; public String getRein() { return id_banco; } public void setRein(String id_banco) { this.id_banco = id_banco; } public static Rein load(ResultSet rs)throws SQLException{ Rein banco = new Rein(); banco.setRein(rs.getString(1)); return banco; } }
true
3776bb8fce82ea5677bb3aebc69b440d69475937
Java
ramsbreddy/saml-validation
/src/main/java/com/test/saml/SamlValidateApplication.java
UTF-8
449
1.554688
2
[]
no_license
package com.test.saml; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @EnableAutoConfiguration //@EnableResourceServer public class SamlValidateApplication { public static void main(String[] args) { SpringApplication.run(SamlValidateApplication.class, args); } }
true
57baf722e39109424edf7f4dd1829fae5f980c07
Java
godaner/happyholiday
/source/src/main/java/com/happyholiday/front/officialwebsite/service/OwIndexCarouselServiceI.java
UTF-8
463
1.734375
2
[]
no_license
package com.happyholiday.front.officialwebsite.service; import java.util.List; import com.happyholiday.front.officialwebsite.exception.OfficialwebsiteException; import com.happyholiday.front.officialwebsite.pageModel.PageOwIndexCarousel; import com.happyholiday.front.officialwebsite.util.OwFrontReturnJSON; public interface OwIndexCarouselServiceI { List<PageOwIndexCarousel> getCarousels(PageOwIndexCarousel pageModel) throws OfficialwebsiteException; }
true
71d3091b44fbde1d1fb72b0bb2e39648ccb61d18
Java
randhika/foursquared
/main/src/com/joelapenna/foursquared/appwidget/StatsWidgetProviderMedium.java
UTF-8
3,615
2.296875
2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package com.joelapenna.foursquared.appwidget; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.Context; import android.content.Intent; import android.widget.RemoteViews; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquared.*; import com.joelapenna.foursquared.app.FoursquaredService; import com.joelapenna.foursquared.appwidget.stats.StatsWidgetUpdater; import com.joelapenna.foursquared.appwidget.stats.UserRank; import com.joelapenna.foursquared.appwidget.stats.UserStats; /** * @author Nick Burton (charlesnicholasburton [at] gmail.com) */ public class StatsWidgetProviderMedium extends AppWidgetProvider { @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { Intent intent = new Intent(context, FoursquaredService.class); intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); context.startService(intent); } public static StatsWidgetUpdater updater(Foursquared foursquared) { return new MediumUpdater(foursquared); } private static class MediumUpdater extends StatsWidgetUpdater { protected MediumUpdater(Foursquared foursquared) { super(foursquared); } @Override protected void setLayoutResources() { mLayoutResource = R.layout.stats_widget_layout_medium; mLayoutId = R.id.widget_medium; } @Override protected void updateUserStats(RemoteViews updateViews, UserStats userStats) { updateViews.setTextViewText(R.id.badge_count_medium, userStats.getBadgeCount()); updateViews.setTextViewText(R.id.mayor_count_medium, userStats.getMayorCount()); updateViews.setTextViewText(R.id.venue_medium, userStats.getVenue()); } @Override protected void updateUserRank(RemoteViews updateViews, UserRank userRank) { updateViews.setTextViewText(R.id.user_rank_medium, userRank.getUserRank()); updateViews.setTextViewText(R.id.checkins_medium, userRank.getCheckins()); } @Override protected void addOnClickIntents(RemoteViews updateViews, Context context, User user) { // leaderboard Intent intent = new Intent(context, StatsActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); updateViews.setOnClickPendingIntent(R.id.user_rank_medium, pendingIntent); // mayorships intent = new Intent(context, UserMayorshipsActivity.class); intent.putExtra(UserMayorshipsActivity.EXTRA_USER_ID, user.getId()); pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); updateViews.setOnClickPendingIntent(R.id.mayor_count_medium, pendingIntent); // badges intent = new Intent(context, BadgesActivity.class); intent.putParcelableArrayListExtra(BadgesActivity.EXTRA_BADGE_ARRAY_LIST_PARCEL, user.getBadges()); pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); updateViews.setOnClickPendingIntent(R.id.badge_count_medium, pendingIntent); // venue intent = new Intent(context, VenueActivity.class); intent.setAction(Intent.ACTION_VIEW); intent.putExtra(Foursquared.EXTRA_VENUE_ID, user.getCheckin().getVenue().getId()); pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); updateViews.setOnClickPendingIntent(R.id.checkins_medium, pendingIntent); } } }
true
b817cfd6c05366ae053a45d7a5873b9b8b9b4d3b
Java
AlenaMoroz/online_market_amaroz
/online-market/service-module/src/main/java/com/gmail/marozalena/onlinemarket/service/exception/ReviewsNotUpdatedException.java
UTF-8
242
1.929688
2
[]
no_license
package com.gmail.marozalena.onlinemarket.service.exception; public class ReviewsNotUpdatedException extends RuntimeException { public ReviewsNotUpdatedException(String message, Throwable cause) { super(message, cause); } }
true
048e35db16e4eaefbb5567a1a0b59dc95ebd22ef
Java
jascott711/Saeleen
/Saeleen-Worlds-Apart/src/main/java/ui/PlayerStats.java
UTF-8
1,579
3.078125
3
[]
no_license
package ui; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Rectangle; import graphics.Renderer; import objects.Player; /** * PlayerStats * display player level and is the container * to hold the health, mana, and exp bar */ public class PlayerStats extends UIComponent { protected Player player; protected Rectangle rect = new Rectangle((Renderer.gameWidth-120)/2,Renderer.gameHeight-86,120,84); public PlayerStats(Player player) { this.player = player; } public Player getPlayer() { return this.player; } public void setPlayer(Player player) { this.player = player; } public void update (float deltaTime) { } @Override public void render(Graphics g) { //player stats //styles int FontSize = 12; int lineHeight = 20; int borderRadius = 20; g.setColor(Color.WHITE); g.fillRoundRect(rect.x, rect.y, rect.width, rect.height, borderRadius, borderRadius); g.setColor(new Color(230,240,85)); //yellow #e6f055 g.fillRoundRect(rect.x + 1, rect.y + 1, rect.width - 2, rect.height - 2, borderRadius, borderRadius); g.setColor(new Color(25,25,25)); //black #191919; g.fillRoundRect(rect.x + 3, rect.y + 3, rect.width - 6, rect.height - 6, borderRadius, borderRadius); //text g.setColor(Color.WHITE); g.setFont( new Font("Tahoma", Font.BOLD, FontSize)); g.drawString("Level "+ player.level, rect.x + 12, rect.y + lineHeight); } }
true
fe83ac1a590a660b09eba24b97f44774da9a1136
Java
urahamat01/java-8-
/60-100/PrimeNumberEx.java
UTF-8
692
3.484375
3
[]
no_license
import java.util.Scanner; class PrimeNumberEx{ public static void main(String...args){ Scanner inport = new Scanner(System.in); int n, m, totalPrime=0; System.out.print("Enter any number :"); n = inport.nextInt(); System.out.print("Enter any number :"); m = inport.nextInt(); int count =0; for(int i=n; i<m; i++){ for(int j=2; j<i-1; j++){ if(i%j==0){ count++; break; } } //System.out.print (count); if(count==0){ System.out.println("prime number " + i ); //total prime number totalPrime++; } count=0; } System.out.println("Total prime number =" + totalPrime); } }
true
57221f4b61f49c9f7e4456ce33a4c3327de51e1d
Java
s-mahapat/evitaran
/src/java/IAS/Bean/masterdata/journalDetailsFormBean.java
UTF-8
2,124
2.40625
2
[]
no_license
package IAS.Bean.masterdata; public class journalDetailsFormBean { /* fields */ private int id = 0; private int vid = 0; private int journalsId = 0; private String journalName = ""; private int year = 0; private String pages = ""; private int issues = 0; private String page_size = ""; private int no_of_volumes = 0; private int volume_number = 0; private String start_month = ""; /* Methods - Getter and Setter */ public int getId() { return (this.id); } public void setId(int _Id) { this.id = _Id; } public int getVid() { return (this.vid); } public void setVid(int _Vid) { this.vid = _Vid; } public int getJournalsId() { return (this.journalsId); } public void setJournalsId(int _JournalsId) { this.journalsId = _JournalsId; } public String getJournalName() { return (this.journalName); } public void setJournalName(String _JournalName) { this.journalName = _JournalName; } public int getYear() { return (this.year); } public void setYear(int _Year) { this.year = _Year; } public String getPages() { return (this.pages); } public void setPages(String _Pages) { this.pages = _Pages; } public int getIssues() { return (this.issues); } public void setIssues(int _Issues) { this.issues = _Issues; } public String getPage_size() { return (this.page_size); } public void setPage_size(String _page_size) { this.page_size = _page_size; } public int getNo_of_volumes() { return (this.no_of_volumes); } public void setNo_of_volumes(int _no_of_volumes) { this.no_of_volumes = _no_of_volumes; } public int getVolume_number() { return (this.volume_number); } public void setVolume_number(int _Volume_number) { this.volume_number = _Volume_number; } public String getStart_month() { return (this.start_month); } public void setStart_month(String _Start_month) { this.start_month = _Start_month; } }
true
539ed46dd7d4c6dca544aee0aee5cf7b1a60bd73
Java
ricardoard12/web-academy-erp
/ web-academy-erp/AcademyERP/src/academy/faq_board/action/Faq_BoardAddAction.java
UTF-8
1,109
2.140625
2
[]
no_license
package academy.faq_board.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import academy.faq_board.db.Faq_boardDAO; import academy.faq_board.db.Faq_boardbean; public class Faq_BoardAddAction implements Action { @Override public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception { request.setCharacterEncoding("utf-8"); Faq_boardbean faq_boardbean = new Faq_boardbean(); Faq_boardDAO faq_boarddao = new Faq_boardDAO(); ActionForward forward = new ActionForward(); try{ faq_boardbean.setFaq_name(request.getParameter("faq_name")); faq_boardbean.setFaq_content(request.getParameter("faq_content")); faq_boardbean.setFaq_subject(request.getParameter("faq_subject")); faq_boardbean.setFaq_passwd(request.getParameter("faq_passwd")); faq_boarddao.faqboardinsert(faq_boardbean); forward.setRedirect(true); forward.setPath("./Faq_boardList.fb"); } catch(Exception e){ e.printStackTrace(); } return forward; } }
true
ae8cda572c08ff384826a56200fa3ae915a24a6e
Java
eldister/jkfteam-sistema-inventario-municipal
/simuniv2/src/java/simuni/clases/ln/ManejadorPermiso.java
UTF-8
11,962
2.78125
3
[]
no_license
package simuni.clases.ln; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import simuni.clases.ad.ManejadorDatosPermiso; import simuni.entidades.Respuesta; import simuni.entidades.mantenimientos.Permiso; import simuni.utils.UtilidadesServlet; /** * Esta clase de lógica de negocios de <strong>Permiso</strong> se encarga de * las operaciones de validación, solicitudes y respuestas, para hacer su * ingreso, modificación, eliminación de registros. Entre las operaciones * comunes que se solicitan estan agregar, modificar, eliminar, hacer un query * de busqueda y tambien hacer el listado por defecto que hay de los datos * ingresados. * * @author FchescO * @since 1.0 * @version 1.0 */ public class ManejadorPermiso { /** * Operación que se encarga de realizar el ingreso / registro del * <strong>Permiso</strong>. * * @param permiso El nuevo registro a ingresar. * @return Un objeto Respuesta que indica el resultado de la operación. * @since 1.0 */ public Respuesta registrarPermiso(Permiso permiso) { Respuesta resp = new Respuesta(); ManejadorDatosPermiso mdpermiso = new ManejadorDatosPermiso(); try { String msg = mdpermiso.registrarPermiso(permiso); if (msg != null && msg.startsWith("2")) { resp.setNivel(2); } else { resp.setNivel(1); } resp.setMensaje(msg); } catch (SQLException ex) { resp.setNivel(2); resp.setMensaje("Error: " + ex.getMessage()); } return resp; } /** * Método utilizado para la asignación de los permisos a un usuario en particular * * @param permisos que se le pueden dar o quitar a un usuario * @param idusuario identificador del usuario * @return un arraylist con la respuesta obtenida durante la operación. * @since 1.0 */ public ArrayList<Respuesta> asignarPermisos(String permisos[], String idusuario) { ArrayList<Respuesta> resp = new ArrayList<Respuesta>(); ManejadorDatosPermiso mdpermiso = new ManejadorDatosPermiso(); //validar si idusuario es nulo try { String ms = mdpermiso.eliminarAsignacionPermiso(idusuario); Respuesta aux2 = new Respuesta(); if (ms != null && ms.startsWith("2")) { aux2.setNivel(2); } else { aux2.setNivel(1); } aux2.setMensaje(ms); resp.add(aux2); if (permisos != null) { for (String permiso : permisos) { //validar si permiso es numero String msg = mdpermiso.registrarAsignarPermiso(idusuario, Integer.parseInt(permiso)); Respuesta aux = new Respuesta(); if (msg != null && msg.startsWith("2")) { aux.setNivel(2); } else { aux.setNivel(1); } aux.setMensaje(msg); resp.add(aux); } } } catch (SQLException ex) { Respuesta aux = new Respuesta(); aux.setNivel(2); aux.setMensaje("Error: " + ex.getMessage()); resp.add(aux); } return resp; } /** * Operación que se encarga de realizar la eliminación del * <strong>Permiso</strong> de la base de datos. No lanza excepciones, y si * las hay, las registra en bitácora. * * @param permiso El registro a eliminar. * @return Un objeto Respuesta que indica el resultado de la operación. * @since 1.0 */ public Respuesta eliminarPermiso(Permiso permiso) { Respuesta resp = new Respuesta(); ManejadorDatosPermiso mdpermiso = new ManejadorDatosPermiso(); try { String msg = mdpermiso.eliminarPermiso(permiso); if (msg != null && !msg.startsWith("2")) { resp.setNivel(1); } else { resp.setNivel(2); } resp.setMensaje(msg); } catch (SQLException ex) { resp.setNivel(2); resp.setMensaje("Error: " + ex.getMessage()); } return resp; } /** * Operación que se encarga de realizar la modificación del * <strong>Permiso</strong> de la base de datos. No lanza excepciones, y si * las hay, las registra en bitácora. * * @param permiso El registro a modificar. * @return Un objeto Respuesta que indica el resultado de la operación. * @since 1.0 */ public Respuesta modificarPermiso(Permiso permiso) { Respuesta resp = new Respuesta(); ManejadorDatosPermiso mdpermiso = new ManejadorDatosPermiso(); try { String msg = mdpermiso.modificarPermiso(permiso); if (msg != null && !msg.startsWith("2")) { resp.setNivel(1); } else { resp.setNivel(2); } resp.setMensaje(msg); System.out.println(msg); } catch (SQLException ex) { resp.setNivel(2); resp.setMensaje("Error: " + ex.getMessage()); } return resp; } /** * Función que se encarga de obtener un listado de los registros ya * ingreados. No lanza excepciones, y si las hay, las registra en bitácora. * * @param desplazamiento Registros que se ha de brincar o pasar por alto. * @param paginacion Cantidad de registros a traer. * @return Un ResultSet que trae consigo los datos de la selección. * @since 1.0 */ public ResultSet listadoPermiso(int desplazamiento, int paginacion) { ResultSet resp = null; ManejadorDatosPermiso mdPermiso = new ManejadorDatosPermiso(); try { resp = mdPermiso.listadoPermiso(desplazamiento, paginacion); } catch (SQLException ex) { ex.printStackTrace(); } return resp; } /** * Método que obtiene todo los resultados de los permisos a través de una * vista de la base de datos * * @return un arraylist con el listado de los permisos para un tipo de usuario * @since 1.0 */ public ArrayList<Permiso> listadoPermisos() { ArrayList<Permiso> tiposusuario = null; ManejadorDatosPermiso mdPermiso = new ManejadorDatosPermiso(); try { ResultSet resp = null; resp = mdPermiso.listadoPermiso(); if (resp.next()) { tiposusuario = new ArrayList<Permiso>(); do { Permiso permiso = new Permiso(); permiso.setCodigoPermiso(resp.getInt(1)); permiso.setNombrePermiso(resp.getString(2)); tiposusuario.add(permiso); } while (resp.next()); } } catch (SQLException ex) { ex.printStackTrace(); } return tiposusuario; } /** * Método que obtiene todo los permisos que han sido asignados a los usuarios del * sistema * * @param idusuario usuarios de quien se obtendran la lista de permisos * @return un arraylist con el listado de los permisos asignados a dicho usuario * @since 1.0 */ public ArrayList<Permiso> listadoPermiso_Asignados(String idusuario) { ArrayList<Permiso> tiposusuario = null; ManejadorDatosPermiso mdPermiso = new ManejadorDatosPermiso(); try { ResultSet resp = null; resp = mdPermiso.listadoPermiso_Asignados(idusuario); if (resp.next()) { tiposusuario = new ArrayList<Permiso>(); do { Permiso permiso = new Permiso(); permiso.setCodigoPermiso(resp.getInt(1)); permiso.setNombrePermiso(resp.getString(2)); tiposusuario.add(permiso); } while (resp.next()); } } catch (SQLException ex) { ex.printStackTrace(); } return tiposusuario; } /** * Método que obtiene todo los permisos que tiene disponibles un usuario del * sistema * * @param idusuario usuarios de quien se obtendran la lista de permisos disponibles * @return un resultset con el listado de los permisos disponibles de dicho usuario * @since 1.0 */ public ArrayList<Permiso> listadoPermiso_Disponibles(String idusuario) { ArrayList<Permiso> tiposusuario = null; ManejadorDatosPermiso mdPermiso = new ManejadorDatosPermiso(); try { ResultSet resp = null; resp = mdPermiso.listadoPermiso_Disponibles(idusuario); if (resp.next()) { tiposusuario = new ArrayList<Permiso>(); do { Permiso permiso = new Permiso(); permiso.setCodigoPermiso(resp.getInt(1)); permiso.setNombrePermiso(resp.getString(2)); tiposusuario.add(permiso); } while (resp.next()); } } catch (SQLException ex) { ex.printStackTrace(); } return tiposusuario; } /** * Realiza una busqueda en la base de datos. No lanza excepciones, y si las * hay, las registra en bitácora. * * @param query El criterio a buscar. * @param desplazamiento Cantidad de registros que se deben de pasar. * @param paginacion La cantidad de registros a devolver. * @return Un ResultSet con los resultados de la busqueda * @since 1.0 */ public ResultSet busquedaPermiso(String query, int desplazamiento, int paginacion) { ResultSet resp = null; ManejadorDatosPermiso mdPermiso = new ManejadorDatosPermiso(); try { resp = mdPermiso.busquedaPermiso(query, desplazamiento, paginacion); } catch (SQLException ex) { System.out.println("Debes registrar algo"); } return resp; } /** * Obtiene la cantidad de registros que hay en la base de datos, con el * criterio qeu se pasa por parámetro. No lanza excepciones, y si las hay, * las registra en bitácora. * * @param query La cadena con la busqueda a evaluar. * @return Un entero con la cantidad de registros. * @since 1.0 */ public int getCantidadRegistros(String query) { int resp = 0; try { ManejadorDatosPermiso mdpermiso = new ManejadorDatosPermiso(); resp = mdpermiso.getCantidadFilas(query); } catch (SQLException ex) { UtilidadesServlet.registrarErrorSistema("getCantidadRegistrosActivosArticulos", ex.getMessage()); ex.printStackTrace(); } return resp; } /** * Funcion que se encarga de traer un registro específico de la base de * datos con relacion a los permisos * * @param codigo El código / identificador del registro a buscar. * @return Un objeto Permiso con los valores correspondientes * @since 1.0 */ public Permiso getPermiso(int codigo) { Permiso resp = null; ManejadorDatosPermiso mdpermiso = new ManejadorDatosPermiso(); try { resp = mdpermiso.getPermiso(codigo); } catch (SQLException ex) { ex.printStackTrace(); } return resp; } }
true
53594ccca21035bd65d68944b99a8e6aa821a50f
Java
vijaykumar983/Psycoolg-user-app
/app/src/main/java/com/psycoolg/pojo/AllDoctorData.java
UTF-8
3,490
2.1875
2
[]
no_license
package com.psycoolg.pojo; import com.google.gson.annotations.SerializedName; import java.util.List; public class AllDoctorData { @SerializedName("data") private List<DataItem> data; @SerializedName("massage") private String massage; @SerializedName("status") private boolean status; public void setData(List<DataItem> data) { this.data = data; } public List<DataItem> getData() { return data; } public void setMassage(String massage) { this.massage = massage; } public String getMassage() { return massage; } public void setStatus(boolean status) { this.status = status; } public boolean isStatus() { return status; } public static class DataItem { @SerializedName("profession") private String profession; @SerializedName("firstname") private String firstname; @SerializedName("online_status") private String onlineStatus; @SerializedName("mobile") private String mobile; @SerializedName("profile_pic") private String profilePic; @SerializedName("rating") private float rating; @SerializedName("location") private String location; @SerializedName("id") private String id; @SerializedName("email") private String email; @SerializedName("lastname") private String lastname; @SerializedName("username") private String username; public void setProfession(String profession) { this.profession = profession; } public String getProfession() { return profession; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getFirstname() { return firstname; } public void setOnlineStatus(String onlineStatus) { this.onlineStatus = onlineStatus; } public String getOnlineStatus() { return onlineStatus; } public void setMobile(String mobile) { this.mobile = mobile; } public String getMobile() { return mobile; } public void setProfilePic(String profilePic) { this.profilePic = profilePic; } public String getProfilePic() { return profilePic; } public void setRating(float rating) { this.rating = rating; } public float getRating() { return rating; } public void setLocation(String location) { this.location = location; } public String getLocation() { return location; } public void setId(String id) { this.id = id; } public String getId() { return id; } public void setEmail(String email) { this.email = email; } public String getEmail() { return email; } public void setLastname(String lastname) { this.lastname = lastname; } public String getLastname() { return lastname; } public void setUsername(String username) { this.username = username; } public String getUsername() { return username; } } }
true
3974f51e55f7e80c70f9acdebf0de25b5e251e77
Java
mstftikir/LeetCode.Java
/src/com/problems/problem922/Problem922.java
UTF-8
1,443
4
4
[]
no_license
/*922. Sort Array By Parity II Given an array A of non-negative integers, half of the integers in A are odd, and half of the integers are even. Sort the array so that whenever A[i] is odd, i is odd; and whenever A[i] is even, i is even. You may return any answer array that satisfies this condition. Example 1: Input: [4,2,5,7] Output: [4,5,2,7] Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted. Note: 2 <= A.length <= 20000 A.length % 2 == 0 0 <= A[i] <= 1000 * */ package com.problems.problem922; import java.util.*; public class Problem922 { public static void main(String[] args) { Problem922 instance = new Problem922(); int[] input = {4, 2, 5, 7}; int[] result = instance.sortArrayByParityII(input); for (int i : result) { System.out.println(i); } } public int[] sortArrayByParityII(int[] A) { List<Integer> listEven = new ArrayList<>(A.length / 2); List<Integer> listOdd = new ArrayList<>(A.length / 2); for (int e : A) { if(e % 2 == 0){ listEven.add(e); } else{ listOdd.add(e); } } for (int i = 0; i < A.length; i++) { if (i % 2 == 0) { A[i] = listEven.remove(0); } else { A[i] = listOdd.remove(0); } } return A; } }
true
7be4498dd61c9a79f67959e62fdf005b23c19e44
Java
rnkoaa/marketplace-ddd
/marketplace/src/main/java/com/marketplace/domain/classifiedad/ClassifiedAdId.java
UTF-8
916
2.359375
2
[]
no_license
package com.marketplace.domain.classifiedad; import com.marketplace.cqrs.event.EventId; import java.util.UUID; public final class ClassifiedAdId extends EventId { public ClassifiedAdId(UUID id) { super(id); } public ClassifiedAdId() { this(UUID.randomUUID()); } public static ClassifiedAdId newClassifiedAdId() { return new ClassifiedAdId(UUID.randomUUID()); } public static ClassifiedAdId from(UUID value) { return new ClassifiedAdId(value); } public static ClassifiedAdId fromString(String uuid) { var id = UUID.fromString(uuid); return new ClassifiedAdId(id); } @Override public String getStreamId() { return String.format("%s:%s", ClassifiedAd.class.getSimpleName(), super.id()); } @Override public String getAggregateName() { return ClassifiedAd.class.getSimpleName(); } }
true
eefc04e2ba8b8489eb493320fb8af33e126e526b
Java
LabenekoGames/CatStep
/src/com/labeneko/androidgames/framework/math/Vector2d.java
UTF-8
2,468
3.3125
3
[]
no_license
package com.labeneko.androidgames.framework.math; public class Vector2d { //Field public static float TO_RADIANS = (1 / 180.0f) * (float) Math.PI; public static float TO_DEGREES = 180.0f / ((float) Math.PI); public float wX, wY; //Constructor public Vector2d() { } public Vector2d(float wX, float wY) { this.wX = wX; this.wY = wY; } public Vector2d(Vector2d other) { this.wX = other.wX; this.wY = other.wY; } //Method public Vector2d cpy() { return new Vector2d(wX, wY); } public Vector2d set(float wX, float wY) { this.wX = wX; this.wY = wY; return this; } public Vector2d set(Vector2d other) { this.wX = other.wX; this.wY = other.wY; return this; } public Vector2d add(float wX, float wY) { this.wX += wX; this.wY += wY; return this; } public Vector2d add(Vector2d other) { this.wX += other.wX; this.wY += other.wY; return this; } public Vector2d sub(float wX, float wY) { this.wX -= wX; this.wY -= wY; return this; } public Vector2d sub(Vector2d other) { this.wX -= other.wX; this.wY -= other.wY; return this; } public Vector2d mul(float scalar) { this.wX *= scalar; this.wY *= scalar; return this; } public float len() { return (float) Math.sqrt(wX * wX + wY * wY); } public Vector2d nor() { float len = len(); if (len != 0) { this.wX /= len; this.wY /= len; } return this; } public float angle() { float angle = (float) Math.atan2(wY, wX) * TO_DEGREES; return angle; } public Vector2d rotate(float angle) { float rad = angle * TO_RADIANS; float cos = (float) Math.cos(rad); float sin = (float) Math.sin(rad); float newX = this.wX * cos - this.wY * sin; float newY = this.wX * sin + this.wY * cos; this.wX = newX; this.wY = newY; return this; } public float dist(Vector2d other) { float distX = this.wX - other.wX; float distY = this.wY - other.wY; return (float) Math.sqrt(distX * distX + distY * distY); } public float dist(float wX, float wY) { float distX = this.wX - wX; float distY = this.wY - wY; return (float) Math.sqrt(distX * distX + distY * distY); } public float distSquared(Vector2d other) { float distX = this.wX - other.wX; float distY = this.wY - other.wY; return distX * distX + distY * distY; } public float distSquared(float wX, float wY) { float distX = this.wX - wX; float distY = this.wY - wY; return distX * distX + distY * distY; } }
true
b69495e4a79d7e8309e7639c6c347b0b2ae79787
Java
jayeshkapadnis/jashorn-model-validator
/src/test/java/com/neuralfly/specification/function/RequiredFunctionSpecTest.java
UTF-8
1,630
2.5625
3
[]
no_license
package com.neuralfly.specification.function; import com.neuralfly.scripts.ScriptEngineFactory; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; import javax.script.ScriptEngine; import javax.script.ScriptException; import java.io.IOException; public class RequiredFunctionSpecTest { private static ScriptEngine engine; @BeforeClass public static void init() throws IOException, ScriptException { engine = ScriptEngineFactory.newScriptEngine(); } @Test public void shouldReturnTrueIfCheckPassed() throws ScriptException, NoSuchMethodException { RequiredFunctionSpec functionSpec = new RequiredFunctionSpec(); String data = "{\"data\": { \"someData\": { \"num\": 3} }}"; boolean result = functionSpec.validate(data, "data.someData.num", engine); assertTrue(result); } @Test public void shouldReturnFalseIfCheckFailed() throws ScriptException, NoSuchMethodException { RequiredFunctionSpec functionSpec = new RequiredFunctionSpec(); String data = "{\"data\": { \"someData\": { \"num\": null} }}"; boolean result = functionSpec.validate(data, "data.someData.num", engine); assertFalse(result); } @Test public void shouldReturnFalseIfFieldNotPresent() throws ScriptException, NoSuchMethodException { RequiredFunctionSpec functionSpec = new RequiredFunctionSpec(); String data = "{\"data\": { \"someData\": { \"count\": 3} }}"; boolean result = functionSpec.validate(data, "data.someData.num", engine); assertFalse(result); } }
true
945d09964e42121c63ab980da75991fceccb428f
Java
voymasa/Chess_Java
/src/final_project/ChessBoard.java
UTF-8
1,293
3.40625
3
[]
no_license
package final_project; import java.awt.Color; import java.awt.Graphics2D; public class ChessBoard { private Position position; // by row and column private Color color; private ChessPiece piece; private int width; private int height; public ChessBoard(Position pos, int w, int h, Color color) { this.position = new Position(pos.getPosX(), pos.getPosY()); this.color = color; this.width = w; this.height = h; } /** * @return the position */ public Position getPosition() { return position; } /** * @return the piece */ public ChessPiece getPiece() { return piece; } /** * @return the width */ public int getWidth() { return width; } /** * @return the height */ public int getHeight() { return height; } /** * @param piece the piece to set */ public void setPiece(ChessPiece piece) { this.piece = piece; } /** * @param width the width to set */ public void setWidth(int width) { this.width = width; } /** * @param height the height to set */ public void setHeight(int height) { this.height = height; } public void draw(int x, int y, Graphics2D g2) { g2.setColor(color); g2.fillRect(x, y, width, height); if(this.getPiece() != null) { this.getPiece().draw(x, y, g2); } } }
true
d301066096e2276b42690c52c92c6b3e9f9fb8f9
Java
rhelk/Tarkvaratehnika
/src/test/java/rentdeck/controller/UserControllerTest.java
UTF-8
3,792
2.140625
2
[]
no_license
package rentdeck.controller; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import rentdeck.dao.UserDao; import rentdeck.model.Users; import java.security.Principal; import java.util.Optional; import static org.mockito.ArgumentMatchers.any; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) @WebMvcTest(value = UserController.class, secure = false) public class UserControllerTest { @Autowired private MockMvc mockMvc; @MockBean private UserDao userDao; @Test public void getUserByIdTest() throws Exception { Users mockedUser = new Users(); mockedUser.setUser_id(1L); Mockito.when(userDao.findById(1L)).thenReturn(Optional.of(mockedUser)); mockMvc.perform(MockMvcRequestBuilders.get("/api/user/get/{id}", 1L) .accept(MediaType.APPLICATION_JSON)) .andDo(System.out::println) .andExpect(MockMvcResultMatchers.jsonPath("user_id").value(1)); } @Test public void addUserTest() throws Exception { Users user = new Users(); user.setUser_id(-1L); // user.setFirst_name("Tim"); // user.setLast_name("Drake"); // user.setPassword("notrealone"); // user.setUsername("Robin"); // System.out.println(user.toString()); // System.out.println(objectMapper.writeValueAsString(user)); String userJson = "{\"user_id\":null,\"first_name\":\"Tim\",\"last_name\":\"Drake\",\"username\":\"Robin\",\"password\":\"notrealone\"}"; // Users mockUsers = Mockito.mock(Users.class); Mockito.when(userDao.save(any(Users.class))).thenReturn(user); MvcResult result = mockMvc.perform(post("/api/register") .contentType(MediaType.APPLICATION_JSON) .content(userJson)) .andExpect(status().isOk()) .andReturn(); // assertEquals(result.getResponse().getContentAsString().substring(11, 14), "-1,"); assertThat(result.getResponse().getContentAsString().substring(11, 14)).isEqualTo("-1,"); } @Test public void authCheckTest() throws Exception{ Users user = new Users(); user.setUser_id(-1L); Principal mockedPrincipal = Mockito.mock(Principal.class); Mockito.when(mockedPrincipal.getName()).thenReturn("asha"); Mockito.when(userDao.findByUsername("asha")).thenReturn(user); MvcResult mvcResult = mockMvc.perform(get("/api/user/authCheck") .contentType(MediaType.APPLICATION_JSON) .principal(mockedPrincipal)) .andExpect(status().isOk()) .andReturn(); Users resultUser = new ObjectMapper().readValue(mvcResult.getResponse().getContentAsString(), Users.class); assertThat(resultUser.getUser_id()).isEqualTo(user.getUser_id()); } }
true
437aca60b5f0e4d8a514c6c0373ec1460374a2f7
Java
wangxiaozhong/eagle
/eagle-core/src/main/java/eagle/jfaster/org/config/BaseReferConfig.java
UTF-8
1,390
2
2
[]
no_license
package eagle.jfaster.org.config; import lombok.Getter; import lombok.Setter; /** * Created by fangyanpeng1 on 2017/8/8. */ public class BaseReferConfig extends AbstractInterfaceConfig{ // 请求超时 @Setter @Getter protected Integer requestTimeout; // 连接超时 @Setter @Getter protected Long connectTimeout; // client最小连接数 @Setter @Getter protected Integer minClientConnection; // client最大连接数 @Setter @Getter protected Integer maxClientConnection; @Setter @Getter protected Long idleTime; @Setter @Getter protected Long maxLifetime; @Setter @Getter protected Integer maxInvokeError; @Getter @Setter // 是否开启gzip压缩 protected Boolean compress; @Getter @Setter // 进行gzip压缩的最小阈值,且大于此值时才进行gzip压缩。单位Byte protected Integer minCompressSize; // loadbalance 方式 @Setter @Getter protected String loadbalance; // 高可用策略 @Setter @Getter protected String haStrategy; //回调执行的线程数 @Setter @Getter protected Integer callbackThread; //回调任务对列大小 @Setter @Getter protected Integer callbackQueueSize; @Setter @Getter protected Integer callbackWaitTime; }
true
bf8bbed2a31d3057a58b431750c7e3b9af3a8cdd
Java
javaBin/AndroiditoJZ
/android/src/main/java/no/java/schedule/v2/io/model/JZDate.java
UTF-8
1,656
2.296875
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package no.java.schedule.v2.io.model; import android.util.Log; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.GregorianCalendar; public class JZDate { public int day; public int year; public int hour; public int month; public int minute; public int second; private GregorianCalendar calendar = new GregorianCalendar(); public JZDate(final String dateString) { DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); Date date; try { date = fmt.parse(dateString); day = date.getDate(); year = 1900+date.getYear(); hour = date.getHours()+2; // TODO timezone hack... month = date.getMonth(); minute = date.getMinutes(); second = date.getSeconds(); } catch (ParseException e) { Log.e(this.getClass().getName(),e.getMessage(),e); } } public long millis(){ calendar.set(year,month,day,hour,minute,second); return calendar.getTimeInMillis(); } }
true
ce439c8c760d15c6058af4275ad96021407dea0a
Java
Thirupathi6563/Java_Practice
/src/Practice_java/ChildDemo.java
UTF-8
568
3.15625
3
[]
no_license
package Practice_java; public class ChildDemo extends ParentsDemo { String name="thiru"; public ChildDemo() { System.out.println("child constructor"); //Constructor } public void getData() { super.getdata(); System.out.println(name); //It will print child class name or local name System.out.println(super.name); //when use super keyword it will print parent class name System.out.println("child mathod"); } public static void main(String[] args) { // TODO Auto-generated method stub ChildDemo c=new ChildDemo(); c.getData(); } }
true
c091cac13e411ba55ca282cb9ca893f229c151a6
Java
Angelq2/IS2-Teoria-PatronVisitor
/src/app/Bow.java
UTF-8
205
2.296875
2
[]
no_license
package app; /** * Arco * @author angel */ public class Bow implements Weapon{ public Bow(){ } @Override public void toApply(Soldier soldier) { } }
true
5b76d0207bc152130427db58752dfe80c6480b79
Java
KOSSOKO/maap-backend-esa
/bmap-external/src/main/java/com/esa/bmap/external/model/cmr/collections/Contact.java
ISO-8859-1
8,319
2.015625
2
[]
no_license
// // Ce fichier a t gnr par l'implmentation de rfrence JavaTM Architecture for XML Binding (JAXB), v2.2.8-b130911.1802 // Voir <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Toute modification apporte ce fichier sera perdue lors de la recompilation du schma source. // Gnr le : 2019.01.25 02:55:58 PM CET // package com.esa.bmap.external.model.cmr.collections; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * This entity contains the basic * characteristics for a person or an organization type of * contact. These contacts may provide information about a * Collection, Delivered Algorithm Package, PGE or Data * Originator. System and user profile contact information is * held elsewhere. * * <p>Classe Java pour Contact complex type. * * <p>Le fragment de schma suivant indique le contenu attendu figurant dans cette classe. * * <pre> * &lt;complexType name="Contact"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Role"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;minLength value="1"/> * &lt;maxLength value="80"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="HoursOfService" minOccurs="0"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;minLength value="1"/> * &lt;maxLength value="1024"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="Instructions" minOccurs="0"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;minLength value="1"/> * &lt;maxLength value="2048"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="OrganizationName" minOccurs="0"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;minLength value="1"/> * &lt;maxLength value="200"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="OrganizationAddresses" type="{}ListOfAddresses" minOccurs="0"/> * &lt;element name="OrganizationPhones" type="{}ListOfPhones" minOccurs="0"/> * &lt;element name="OrganizationEmails" type="{}ListOfEmails" minOccurs="0"/> * &lt;element name="ContactPersons" type="{}ListOfContactPersons" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "Contact", propOrder = { "role", "hoursOfService", "instructions", "organizationName", "organizationAddresses", "organizationPhones", "organizationEmails", "contactPersons" }) public class Contact { @XmlElement(name = "Role", required = true) protected String role; @XmlElement(name = "HoursOfService") protected String hoursOfService; @XmlElement(name = "Instructions") protected String instructions; @XmlElement(name = "OrganizationName") protected String organizationName; @XmlElement(name = "OrganizationAddresses") protected ListOfAddresses organizationAddresses; @XmlElement(name = "OrganizationPhones") protected ListOfPhones organizationPhones; @XmlElement(name = "OrganizationEmails") protected ListOfEmails organizationEmails; @XmlElement(name = "ContactPersons") protected ListOfContactPersons contactPersons; /** * Obtient la valeur de la proprit role. * * @return * possible object is * {@link String } * */ public String getRole() { return role; } /** * Dfinit la valeur de la proprit role. * * @param value * allowed object is * {@link String } * */ public void setRole(String value) { this.role = value; } /** * Obtient la valeur de la proprit hoursOfService. * * @return * possible object is * {@link String } * */ public String getHoursOfService() { return hoursOfService; } /** * Dfinit la valeur de la proprit hoursOfService. * * @param value * allowed object is * {@link String } * */ public void setHoursOfService(String value) { this.hoursOfService = value; } /** * Obtient la valeur de la proprit instructions. * * @return * possible object is * {@link String } * */ public String getInstructions() { return instructions; } /** * Dfinit la valeur de la proprit instructions. * * @param value * allowed object is * {@link String } * */ public void setInstructions(String value) { this.instructions = value; } /** * Obtient la valeur de la proprit organizationName. * * @return * possible object is * {@link String } * */ public String getOrganizationName() { return organizationName; } /** * Dfinit la valeur de la proprit organizationName. * * @param value * allowed object is * {@link String } * */ public void setOrganizationName(String value) { this.organizationName = value; } /** * Obtient la valeur de la proprit organizationAddresses. * * @return * possible object is * {@link ListOfAddresses } * */ public ListOfAddresses getOrganizationAddresses() { return organizationAddresses; } /** * Dfinit la valeur de la proprit organizationAddresses. * * @param value * allowed object is * {@link ListOfAddresses } * */ public void setOrganizationAddresses(ListOfAddresses value) { this.organizationAddresses = value; } /** * Obtient la valeur de la proprit organizationPhones. * * @return * possible object is * {@link ListOfPhones } * */ public ListOfPhones getOrganizationPhones() { return organizationPhones; } /** * Dfinit la valeur de la proprit organizationPhones. * * @param value * allowed object is * {@link ListOfPhones } * */ public void setOrganizationPhones(ListOfPhones value) { this.organizationPhones = value; } /** * Obtient la valeur de la proprit organizationEmails. * * @return * possible object is * {@link ListOfEmails } * */ public ListOfEmails getOrganizationEmails() { return organizationEmails; } /** * Dfinit la valeur de la proprit organizationEmails. * * @param value * allowed object is * {@link ListOfEmails } * */ public void setOrganizationEmails(ListOfEmails value) { this.organizationEmails = value; } /** * Obtient la valeur de la proprit contactPersons. * * @return * possible object is * {@link ListOfContactPersons } * */ public ListOfContactPersons getContactPersons() { return contactPersons; } /** * Dfinit la valeur de la proprit contactPersons. * * @param value * allowed object is * {@link ListOfContactPersons } * */ public void setContactPersons(ListOfContactPersons value) { this.contactPersons = value; } }
true
a18cc1984a5ed9b3414932b19d3c2c632411d9ba
Java
ponson-thankavel/spring-boot-sleuth-otel-otlp
/src/main/java/com/ponson/rest/controller/EmployeeController.java
UTF-8
669
2.265625
2
[ "Apache-2.0" ]
permissive
package com.ponson.rest.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.logging.Logger; @RestController @RequestMapping(path = "/") public class EmployeeController { Logger logger = Logger.getLogger(EmployeeController.class.getName()); @GetMapping(path="/employees", produces = "application/json") public String getEmployees() throws Exception { logger.info("Inside EmployeeController.getEmployees"); return "{ test: \"hello world\" }"; } }
true
27be6732762056e53f92f3a9d9a37162a34f549b
Java
PGMacDesign/Jetpack-Samples
/app/src/main/java/pgmacdesign/jetpacksamples/roomsamples/RoomModelAdapter.java
UTF-8
5,397
2.125
2
[ "Apache-2.0" ]
permissive
package pgmacdesign.jetpacksamples.roomsamples; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.pgmacdesign.pgmactips.adaptersandlisteners.OnTaskCompleteListener; import com.pgmacdesign.pgmactips.misc.CustomAnnotationsBase; import com.pgmacdesign.pgmactips.utilities.MiscUtilities; import java.util.List; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.content.ContextCompat; import androidx.recyclerview.widget.RecyclerView; import pgmacdesign.jetpacksamples.R; public class RoomModelAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { public static final int TAG_ROOM_MODEL_ADAPTER_CLICK = -121; public static final int TAG_ROOM_MODEL_ADAPTER_LONG_CLICK = -122; public static final int TAG_ROOM_MODEL_ADAPTER_X_IV = -123; //Dataset List private List<NotePOJO> mListObjects; //UI private LayoutInflater mInflater; //Misc private Context context; private boolean oneSelectedAnimate; private int layoutResourceId; private OnTaskCompleteListener listener; private int COLOR_BLACK; @CustomAnnotationsBase.RequiresDependency(requiresDependency = CustomAnnotationsBase.Dependencies.AndroidSupport_Design) public RoomModelAdapter(@NonNull Context context, @Nullable OnTaskCompleteListener listener) { this.context = context; this.mInflater = LayoutInflater.from(context); this.COLOR_BLACK = ContextCompat.getColor(context, com.pgmacdesign.pgmactips.R.color.black); this.layoutResourceId = R.layout.adapter_room_model_recyclerview; this.listener = listener; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = mInflater.inflate(layoutResourceId, parent, false); RoomHolder holder = new RoomHolder(view); return holder; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder0, final int position) { final NotePOJO note = this.mListObjects.get(position); RoomHolder holder = (RoomHolder) holder0; if(note == null){ //Do stuff holder.adapter_room_model_tv1.setText(""); holder.adapter_room_model_tv2.setText("No Note Found"); holder.adapter_room_model_tv3.setText(""); return; } String sNote = note.getNote(); String dateAdded = "Added on: " + note.getDateAdded(); String id = "ID: " + note.getId(); holder.adapter_room_model_tv1.setText(id); holder.adapter_room_model_tv2.setText(sNote); holder.adapter_room_model_tv3.setText(dateAdded); if(this.listener != null){ holder.adapter_room_model_root.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { RoomModelAdapter.this.listener.onTaskComplete(note, TAG_ROOM_MODEL_ADAPTER_CLICK); } }); holder.adapter_room_model_root.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { RoomModelAdapter.this.listener.onTaskComplete(note, TAG_ROOM_MODEL_ADAPTER_LONG_CLICK); return true; } }); holder.adapter_room_model_cancel_iv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { RoomModelAdapter.this.listener.onTaskComplete(note, TAG_ROOM_MODEL_ADAPTER_X_IV); } }); } int size = (MiscUtilities.isListNullOrEmpty(this.mListObjects) ? 0 : this.mListObjects.size()); if(position < size - 1){ holder.separator.setVisibility(View.VISIBLE); } else { holder.separator.setVisibility(View.INVISIBLE); } } @Override public int getItemCount() { return (MiscUtilities.isListNullOrEmpty(mListObjects) ? 0 : mListObjects.size()); } public void setListObjects(List<NotePOJO> mListObjects) { this.mListObjects = mListObjects; this.notifyDataSetChanged(); } private class RoomHolder extends RecyclerView.ViewHolder { private TextView adapter_room_model_tv1, adapter_room_model_tv2, adapter_room_model_tv3; private RelativeLayout adapter_room_model_root; private ImageView adapter_room_model_cancel_iv; private View separator; public RoomHolder(View itemView) { super(itemView); this.adapter_room_model_cancel_iv = itemView.findViewById(R.id.adapter_room_model_cancel_iv); this.adapter_room_model_root = itemView.findViewById(R.id.adapter_room_model_root); this.adapter_room_model_tv1 = itemView.findViewById(R.id.adapter_room_model_tv1); this.adapter_room_model_tv2 = itemView.findViewById(R.id.adapter_room_model_tv2); this.adapter_room_model_tv3 = itemView.findViewById(R.id.adapter_room_model_tv3); this.separator = itemView.findViewById(R.id.separator); } } }
true
7faa3f540d038fb6eea13ff77203e8a06f985f6f
Java
guvense/Mahallem
/src/main/java/com/mahallem/dto/Response/CommentResponse.java
UTF-8
384
1.6875
2
[ "MIT" ]
permissive
package com.mahallem.dto.Response; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import java.util.Date; @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class CommentResponse { private String content; private String taskId; private String ownerUserName; private Date creationDate; }
true
209f6fa8a3cdfae2e36caeb96993c5fafb3ad2e3
Java
thahimina/Task
/RegistrationServlet.java
UTF-8
3,782
2.609375
3
[]
no_license
package login.servlet; import java.io.IOException; import java.io.PrintWriter; import java.sql.DriverManager; 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 com.mysql.jdbc.Connection; import com.mysql.jdbc.PreparedStatement; @WebServlet("/RegistrationServlet") public class RegistrationServlet extends HttpServlet { private static final long serialVersionUID = 1L; public RegistrationServlet() { super(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, NumberFormatException { String firstName = request.getParameter("firstName"); String lastName = request.getParameter("lastName"); String userName = request.getParameter("userName"); String password = request.getParameter("password"); String address = request.getParameter("address"); PrintWriter out = response.getWriter(); response.setContentType("text/html"); if (firstName.isEmpty() && lastName.isEmpty() && userName.isEmpty() && password.isEmpty() && address.isEmpty()) { out.print("<font color=red>Please fill all the fields</font>"); RequestDispatcher requestDispatcher = request.getRequestDispatcher("registration.jsp"); requestDispatcher.include(request, response); } else if (firstName.isEmpty() || firstName == null) { out.print("<font color=red>Please fill the firstname </font>"); RequestDispatcher requestDispatcher = request.getRequestDispatcher("registration.jsp"); requestDispatcher.include(request, response); } else if (lastName.isEmpty() || lastName == null) { out.print("<font color=red>Please fill the lastname </font>"); RequestDispatcher requestDispatcher = request.getRequestDispatcher("registration.jsp"); requestDispatcher.include(request, response); } else if (userName.isEmpty() || userName == null) { out.print("<font color=red>Please fill the username</font>"); RequestDispatcher requestDispatcher = request.getRequestDispatcher("registration.jsp"); requestDispatcher.include(request, response); } else if (password.isEmpty() || password == null) { out.print("<font color=red>Please fill the password </font>"); RequestDispatcher requestDispatcher = request.getRequestDispatcher("registration.jsp"); requestDispatcher.include(request, response); } else if (address.isEmpty() || address == null) { out.print("<font color=red>Please fill the address </font>"); RequestDispatcher requestDispatcher = request.getRequestDispatcher("registration.jsp"); requestDispatcher.include(request, response); } else { try { Class.forName("com.mysql.jdbc.Driver"); Connection connection = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/task1", "root", "sevya"); String query = "insert into user(firstName,lastName,userName,password,address) values(?,?,?,?,?)"; PreparedStatement preparedStatement = (PreparedStatement) connection.prepareStatement(query); preparedStatement.setString(1, firstName); preparedStatement.setString(2, lastName); preparedStatement.setString(3, userName); preparedStatement.setString(4, password); preparedStatement.setString(5, address); preparedStatement.executeUpdate(); out.println("<b><font color=green >Successfully Registered</font></b>"); RequestDispatcher requestDispatcher = request.getRequestDispatcher("index.jsp"); requestDispatcher.include(request, response); preparedStatement.close(); connection.close(); } catch (Exception e) { e.printStackTrace(); } } } }
true
30bfd67c1eff53049a0825e904a9f8ace554d073
Java
ballerina-platform/ballerina-lang
/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/CheckExpressionNodeContext.java
UTF-8
6,525
1.71875
2
[ "Apache-2.0", "BSD-3-Clause", "LicenseRef-scancode-mit-old-style", "MPL-2.0", "LicenseRef-scancode-unicode", "MIT" ]
permissive
/* * Copyright (c) 2020, WSO2 Inc. (http://wso2.com) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ballerinalang.langserver.completions.providers.context; import io.ballerina.compiler.api.symbols.MethodSymbol; import io.ballerina.compiler.api.symbols.Symbol; import io.ballerina.compiler.api.symbols.SymbolKind; import io.ballerina.compiler.api.symbols.TypeSymbol; import io.ballerina.compiler.syntax.tree.CheckExpressionNode; import io.ballerina.compiler.syntax.tree.NonTerminalNode; import io.ballerina.compiler.syntax.tree.QualifiedNameReferenceNode; import io.ballerina.compiler.syntax.tree.SyntaxKind; import org.ballerinalang.annotation.JavaSPIService; import org.ballerinalang.langserver.common.utils.SymbolUtil; import org.ballerinalang.langserver.commons.BallerinaCompletionContext; import org.ballerinalang.langserver.commons.completion.LSCompletionException; import org.ballerinalang.langserver.commons.completion.LSCompletionItem; import org.ballerinalang.langserver.completions.SnippetCompletionItem; import org.ballerinalang.langserver.completions.SymbolCompletionItem; import org.ballerinalang.langserver.completions.providers.AbstractCompletionProvider; import org.ballerinalang.langserver.completions.util.CompletionUtil; import org.ballerinalang.langserver.completions.util.QNameRefCompletionUtil; import org.ballerinalang.langserver.completions.util.Snippet; import org.ballerinalang.langserver.completions.util.SortingUtil; import java.util.ArrayList; import java.util.List; import java.util.Optional; /** * Completion provider for {@link CheckExpressionNode} context. * * @since 2.0.0 */ @JavaSPIService("org.ballerinalang.langserver.commons.completion.spi.BallerinaCompletionProvider") public class CheckExpressionNodeContext extends AbstractCompletionProvider<CheckExpressionNode> { public CheckExpressionNodeContext() { super(CheckExpressionNode.class); } @Override public List<LSCompletionItem> getCompletions(BallerinaCompletionContext ctx, CheckExpressionNode node) throws LSCompletionException { List<LSCompletionItem> completionItems = new ArrayList<>(); if (node.parent().kind() == SyntaxKind.ASSIGNMENT_STATEMENT || node.parent().kind() == SyntaxKind.LOCAL_VAR_DECL || node.parent().kind() == SyntaxKind.MODULE_VAR_DECL || node.parent().kind() == SyntaxKind.OBJECT_FIELD || node.parent().kind() == SyntaxKind.FROM_CLAUSE) { completionItems.addAll(CompletionUtil.route(ctx, node.parent())); } else { NonTerminalNode nodeAtCursor = ctx.getNodeAtCursor(); if (QNameRefCompletionUtil.onQualifiedNameIdentifier(ctx, nodeAtCursor)) { List<Symbol> expressions = QNameRefCompletionUtil.getExpressionContextEntries(ctx, (QualifiedNameReferenceNode) nodeAtCursor); completionItems.addAll(getCompletionItemList(expressions, ctx)); } else { //We add the action keywords in order to support the check action context completions. completionItems.addAll(this.actionKWCompletions(ctx)); completionItems.addAll(this.expressionCompletions(ctx)); completionItems.add(new SnippetCompletionItem(ctx, Snippet.STMT_COMMIT.get())); } } this.sort(ctx, node, completionItems); return completionItems; } @Override public void sort(BallerinaCompletionContext context, CheckExpressionNode node, List<LSCompletionItem> completionItems) { Optional<TypeSymbol> contextType = context.getContextType(); for (LSCompletionItem completionItem : completionItems) { String sortText = null; LSCompletionItem.CompletionItemType type = completionItem.getType(); if (type == LSCompletionItem.CompletionItemType.SYMBOL) { Optional<Symbol> symbol = ((SymbolCompletionItem) completionItem).getSymbol(); if (symbol.isPresent() && symbol.get().kind() == SymbolKind.VARIABLE) { if (SymbolUtil.isClient(symbol.get())) { // First show the clients since they have remote methods which probably will return error unions sortText = SortingUtil.genSortText(1); } else if (SymbolUtil.isClassVariable(symbol.get())) { // Sort class variables at 3rd since they can have methods sortText = SortingUtil.genSortText(3); } } else if (symbol.isPresent() && symbol.get().kind() == SymbolKind.METHOD) { // Show init method (or the new expression) 1st as well MethodSymbol methodSymbol = (MethodSymbol) symbol.get(); if (methodSymbol.nameEquals("init")) { sortText = SortingUtil.genSortText(1); } } } else if (type == LSCompletionItem.CompletionItemType.SNIPPET) { // Show the new keyword 2nd if (((SnippetCompletionItem) completionItem).id().equals(Snippet.KW_NEW.name())) { sortText = SortingUtil.genSortText(2); } } if (sortText == null && contextType.isPresent() && SortingUtil.isCompletionItemAssignableWithCheck(completionItem, contextType.get())) { // Items which has a union containing an error member are sorted 3r sortText = SortingUtil.genSortText(3); } if (sortText == null) { // Everything else, 3rd sortText = SortingUtil.genSortText(4); } sortText += SortingUtil.genSortText(SortingUtil.toRank(context, completionItem)); completionItem.getCompletionItem().setSortText(sortText); } } }
true
429e0d22e87f19ef1f7697504ff50426f74f7b17
Java
Ahnfelt/jtransaction
/src/main/java/jtransaction/Slot.java
UTF-8
102
2.4375
2
[]
no_license
package jtransaction; public interface Slot<T> { public T get(); public void set(T value); }
true
e12a29ed5534997d8af4ec3c882857c360f3e764
Java
wangyy130/javaDemo
/src/main/java/com/wyy/javademo/suanfa/class11/PrintAllSubStrs.java
UTF-8
1,078
3.875
4
[]
no_license
package com.wyy.javademo.suanfa.class11; import java.util.ArrayList; /** * 打印字符串的所有子序列 * * 子串和子序列的区别: * 1、子串: 必须从左往右连续的 * 2、子序列:可以不连续 * * *这个类似于二叉树的递归套路,每个位置的字符 要 或 不要 * * * 如果打印所有不重复的子序列,可以用set代替list * */ public class PrintAllSubStrs { public static void printAllSubSequence(String strs){ char[] chars = strs.toCharArray(); ArrayList<String> ans = new ArrayList<>(); process(chars, 0 ,"", ans); } public static void process(char[] strs, int index,String path, ArrayList<String> ans){ if(index == strs.length){ ans.add(path); return; }else { //如果当前的字符不要 process(strs,index + 1,path,ans); //如果当前位置的字符要的话 path = path + String.valueOf(strs[index]); process(strs,index+1, path , ans); } } }
true
81fc94a6df1ae4af07eea20f23df7769b07d9342
Java
IRON-head-CWD/IDEA_coda
/Day04/src/com/itheima/DayTest05.java
UTF-8
717
3.453125
3
[]
no_license
package com.itheima; /* 输入一个数 利用遍历 找出输入的数存在数组中的位置 */ import java.util.Scanner; public class DayTest05 { public static void main(String[] args) { int[]arr=new int[]{11,12,113,16,23,15,1,31,3,12,13,1,1,878,78,46,16,4,6}; Scanner sc=new Scanner(System.in); int num=sc.nextInt(); int index=-1; for (int i = 0; i < arr.length; i++) { if(num==arr[i]){ index=i; break; } } if (index==-1){ System.out.println("吊毛没得");} else if(index!=-1){ System.out.println("仔细看"+(index+1)); } } }
true
67c85567217f879794309d846517ff4c27b4271e
Java
davidliuzd/spring-boot-v2
/Chapter9/src/main/java/net/liuzd/spring/boot/v2/repository/CustomerRepository.java
UTF-8
383
1.945313
2
[ "MIT" ]
permissive
package net.liuzd.spring.boot.v2.repository; import java.util.List; import org.springframework.data.mongodb.repository.MongoRepository; import net.liuzd.spring.boot.v2.domain.Customer; public interface CustomerRepository extends MongoRepository<Customer, String> { Customer findByFirstName(String firstName); List<Customer> findByLastName(String lastName); }
true
63e05db18f4918d51ebe0995dcba1c4b98dd1e0f
Java
mturyn/Imagerie
/imageHistMatcher/imageHistMatcher/src/com/mturyn/imageHistComparer/Utilities.java
UTF-8
1,007
2.875
3
[]
no_license
package com.mturyn.imageHistComparer; public class Utilities { public static final String COPYRIGHT_STRING ="'I won't throw down my gun until everyone else throws down theirs.'\r---some guy who got shot.\rCopyright (c) 2014 Michael Turyn; all rights reserved."; public static enum HistogramScale { COARSE,FINE } public static enum HistogramType { RAW,NORMALISED,FREQUENCIES,ENTROPIES } public static enum HistogramDistanceMethod { MATCHES,VECTOR_DISTANCE,VECTOR_EUCLIDEAN_DISTANCE,ANGLE,ONE_MINUS_COSINE } public static enum PixelRep { RGB,HSV,YUV } public final static int RAD_TO_INTEGRAL_DEGREES(double pVal){ return (int) Math.round(Math.toDegrees(pVal)) ; } final static double LN2 = Math.log(2) ; public final static double LN2(double pVal) { return Math.log(pVal)/LN2 ; }; public static String PADDED(Number n,int places){ String s = String.valueOf(n) ; while(s.length()<places){ s = " "+ s ; } return s ; } }
true
ffc14e2fe62353090adaa3dc56e7b60b099e5c2b
Java
bhadzic2/Program-na-osnovu-intervjua-java
/test/ba/unsa/etf/rpr/FakultetTest.java
UTF-8
11,655
2.859375
3
[]
no_license
package ba.unsa.etf.rpr; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import static org.junit.jupiter.api.Assertions.*; class FakultetTest { @Test void testUpisiStudentaNaFakultet() { Fakultet fakultet = new Fakultet(); Student student = new Student("Neko Neki", "17653", 1, 1); Predmet predmet = new Predmet("Predmetic", true, 1, 1, 32, 79); ArrayList<Predmet> izborni = new ArrayList<>(); izborni.add(predmet); try { fakultet.dodajPredmet(predmet); fakultet.upisiStudentaNaFakultet(student, izborni); assertTrue(fakultet.getStudenti().contains(student), "x"); } catch (Exception ex) { System.out.println(ex.getMessage()); } } @Test void testNedovoljanBrojEctsException() { Fakultet fakultet = new Fakultet(); Student student = new Student("Neko Neki", "17653", 1, 1); Predmet predmet = new Predmet("Predmetic", false, 1, 1, 2, 79); ArrayList<Predmet> izborni = new ArrayList<>(); izborni.add(predmet); try { fakultet.dodajPredmet(predmet); } catch (Exception exc) { System.out.println(exc.getMessage()); } NedovoljanBrojEctsException thrown = assertThrows( NedovoljanBrojEctsException.class, () -> fakultet.upisiStudentaNaFakultet(student, izborni), "Trebao biti bacen izuzetak, a nije" ); assertTrue(thrown.getMessage().contains("Odabran je nedovoljan broj ECTS bodova"),"x"); } @Test void testNepostojeciPredmetException() { Fakultet fakultet = new Fakultet(); Student student = new Student("Neko Neki", "17653", 1, 1); Predmet predmet = new Predmet("Predmetic", false, 1, 1, 256, 79); Predmet pogresanPredmet = new Predmet("PredmeticPogresni", false, 1, 1, 92, 79); ArrayList<Predmet> izborni = new ArrayList<>(); izborni.add(pogresanPredmet); try { fakultet.dodajPredmet(predmet); } catch (Exception ex) { System.out.println(ex.getMessage()); } NepostojeciPredmetException thrown = assertThrows( NepostojeciPredmetException.class, () -> fakultet.upisiStudentaNaFakultet(student, izborni), "Trebao biti bacen izuzetak, a nije" ); assertTrue(thrown.getMessage().contains("Odabran je nepostojeci izborni predmet"),"x"); } @Test void testStudentVecPostojiException() { Fakultet fakultet = new Fakultet(); Student student = new Student("Neko Neki", "17653", 1, 1); Predmet predmet = new Predmet("Predmetic", false, 1, 1, 256, 79); ArrayList<Predmet> izborni = new ArrayList<>(); izborni.add(predmet); try { fakultet.dodajPredmet(predmet); fakultet.upisiStudentaNaFakultet(student, izborni); } catch (Exception ex) { System.out.println(ex.getMessage()); } StudentVecPostojiException thrown = assertThrows( StudentVecPostojiException.class, () -> fakultet.upisiStudentaNaFakultet(student, izborni), "Trebao biti bacen izuzetak, a nije" ); assertTrue(thrown.getMessage().contains("Student je vec upisan na fakultet"),"x"); } @Test void testPredmetVecPostojiException() {// Fakultet fakultet = new Fakultet(); Predmet predmet = new Predmet("Predmetic", false, 1, 1, 256, 79); try { fakultet.dodajPredmet(predmet); } catch (Exception ex) { System.out.println(ex.getMessage()); } PredmetVecPostojiException thrown = assertThrows( PredmetVecPostojiException.class, () -> fakultet.dodajPredmet(predmet), "Trebao biti bacen izuzetak, a nije" ); assertTrue(thrown.getMessage().contains("Predmet vec postoji na fakultetu"),"x"); } @Test void testProfesorVecPostojiException() {// Fakultet fakultet = new Fakultet(); Profesor profesor = new Profesor("Profesor Profesic"); try { fakultet.dodajProfesora(profesor); } catch (Exception ex) { System.out.println(ex.getMessage()); } ProfesorVecPostojiException thrown = assertThrows( ProfesorVecPostojiException.class, () -> fakultet.dodajProfesora(profesor), "Trebao biti bacen izuzetak, a nije" ); assertTrue(thrown.getMessage().contains("Profesor vec postoji na fakultetu"),"x"); } @Test void testDodajPredmet() { Predmet predmet1 = new Predmet("Predmetic", true, 1, 1, 2, 79); Predmet predmet2 = new Predmet("PredmeticLijepi", true, 1, 5, 45, 9); Fakultet fakultet = new Fakultet(); try { fakultet.dodajPredmet(predmet1); fakultet.dodajPredmet(predmet2); } catch (Exception ex) { System.out.println(ex.getMessage()); } assertAll( () -> assertTrue(fakultet.getPredmeti().contains(predmet1), "x"), () -> assertTrue(fakultet.getPredmeti().contains(predmet2),"x") ); } @Test void testDodajProfesora() { Fakultet fakultet = new Fakultet(); Profesor profesor1 = new Profesor("Profesor Profesic"); Profesor profesor2 = new Profesor("Profesorica Profesoricic"); try { fakultet.dodajProfesora(profesor1); fakultet.dodajProfesora(profesor2); } catch (Exception ex) { System.out.println(ex.getMessage()); } assertAll( () -> assertTrue(fakultet.getProfesori().contains(profesor1),"x"), () -> assertTrue(fakultet.getProfesori().contains(profesor2),"x") ); } @Test void testDajStudentaPoIndeksu() { Student student = new Student("Neko Neki", "17653", 1, 1); Fakultet fakultet = new Fakultet(); Predmet predmet = new Predmet("Predmetic", false, 1, 1, 256, 79); ArrayList<Predmet> izborni = new ArrayList<>(); izborni.add(predmet); try { fakultet.dodajPredmet(predmet); } catch (Exception ex) { System.out.println(ex.getMessage()); } try { fakultet.upisiStudentaNaFakultet(student, izborni); assertEquals(student, fakultet.dajStudentaPoIndeksu("17653"),"x"); } catch (Exception exc) { System.out.println(exc.getMessage()); } } @Test void testPogresanIndeksException() { Fakultet fakultet = new Fakultet(); Student student = new Student("Neko Neki", "17653", 1, 1); Predmet predmet = new Predmet("Predmetic", false, 1, 1, 256, 79); Predmet predmet2 = new Predmet("Predmetic2", true, 1, 1, 256, 79); ArrayList<Predmet> izborni = new ArrayList<>(); izborni.add(predmet); try { fakultet.dodajPredmet(predmet); fakultet.dodajPredmet(predmet2); } catch (Exception exc) { System.out.println(exc.getMessage()); } PogresanIndeksException thrown = assertThrows( PogresanIndeksException.class, () -> { fakultet.upisiStudentaNaFakultet(student, izborni); fakultet.dajStudentaPoIndeksu("111"); }, "Trebao biti bacen izuzetak, a nije" ); assertTrue(thrown.getMessage().contains("Nema studenta sa tim indeksom"),"x"); } @Test void testGetStudenti(){ Fakultet fakultet=new Fakultet(); List<Student> st=new ArrayList<>(); assertEquals(st,fakultet.getStudenti(),"x"); } @Test void testDajProfesoraBezIliPrekoNorme() { Fakultet fakultet = new Fakultet(); Profesor profesor1 = new Profesor("Profa BezNorme"); Profesor profesor2 = new Profesor("Profa PunoNorme"); Profesor profesor3 = new Profesor("Profa Normalni"); Predmet predmet1 = new Predmet("Predmetic", true, 1, 1, 256, 700); Predmet predmet2 = new Predmet("Predmetic", true, 1, 1, 256, 130); try { fakultet.dodajProfesora(profesor1); fakultet.dodajProfesora(profesor2); fakultet.dodajProfesora(profesor3); fakultet.dodajPredmet(predmet1); fakultet.dodajPredmet(predmet2); profesor2.zaposliProfesoraNaPredmetu(predmet1); profesor3.zaposliProfesoraNaPredmetu(predmet2); } catch (Exception exc) { System.out.println(exc.getMessage()); } assertEquals("Profa BezNorme\nProfa PunoNorme\nProfa Normalni\n", fakultet.dajProfesoreBezIliPrekoNorme(),"x"); //jer nema studenata iako postoje predmeti Student student = new Student("Neko Neki", "17653", 1, 1); predmet2.upisiStudentaNaPredmet(student); predmet1.upisiStudentaNaPredmet(student); assertEquals("Profa BezNorme\nProfa PunoNorme\n", fakultet.dajProfesoreBezIliPrekoNorme(),"x"); } @Test void testDajProfesoreSortiranePoNormi() { Fakultet fakultet = new Fakultet(); Profesor profesor1 = new Profesor("Profa BezNorme"); Profesor profesor2 = new Profesor("Profa PunoNorme"); Profesor profesor3 = new Profesor("Profa Normalni"); Predmet predmet1 = new Predmet("Predmetic", true, 1, 1, 256, 700); Predmet predmet2 = new Predmet("Predmetic", true, 1, 1, 256, 130); try { fakultet.dodajProfesora(profesor1); fakultet.dodajProfesora(profesor2); fakultet.dodajProfesora(profesor3); fakultet.dodajPredmet(predmet1); fakultet.dodajPredmet(predmet2); } catch (Exception exc) { System.out.println(exc.getMessage()); } profesor2.zaposliProfesoraNaPredmetu(predmet1); profesor3.zaposliProfesoraNaPredmetu(predmet2); Student student = new Student("Neko Neki", "17653", 1, 1); predmet2.upisiStudentaNaPredmet(student); predmet1.upisiStudentaNaPredmet(student); assertEquals("Profa BezNorme\nProfa Normalni\nProfa PunoNorme\n", fakultet.dajProfesoreSortiranePoNormi(),"x"); } @Test void testDajProfesoreSortiranePoBrojuStudenata() { Fakultet fakultet = new Fakultet(); Profesor profesor1 = new Profesor("Profa BezNorme"); Profesor profesor2 = new Profesor("Profa PunoNorme"); Profesor profesor3 = new Profesor("Profa Normalni"); Predmet predmet1 = new Predmet("Predmetic", true, 1, 1, 256, 700); Predmet predmet2 = new Predmet("Predmetic", true, 1, 1, 256, 130); try { fakultet.dodajProfesora(profesor1); fakultet.dodajProfesora(profesor2); fakultet.dodajProfesora(profesor3); fakultet.dodajPredmet(predmet1); fakultet.dodajPredmet(predmet2); } catch (Exception exc) { System.out.println(exc.getMessage()); } profesor2.zaposliProfesoraNaPredmetu(predmet1); profesor3.zaposliProfesoraNaPredmetu(predmet2); Student student = new Student("Neko Neki", "17653", 1, 1); Student student2 = new Student("Neko Neki2", "176535", 1, 1); predmet2.upisiStudentaNaPredmet(student); predmet1.upisiStudentaNaPredmet(student2); predmet1.upisiStudentaNaPredmet(student); assertEquals("Profa BezNorme\nProfa Normalni\nProfa PunoNorme\n", fakultet.dajProfesoreSortiranePoBrojuStudenata(),"x"); } }
true
1aff5399887102307e75a5237e326dfe370ec10d
Java
consulo/consulo-google-guice
/plugin/src/main/java/com/sixrr/guiceyidea/reference/NamedReference.java
UTF-8
3,758
1.929688
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2000-2008 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sixrr.guiceyidea.reference; import com.intellij.java.language.psi.PsiField; import com.intellij.java.language.psi.PsiLiteralExpression; import com.intellij.java.language.psi.infos.CandidateInfo; import com.intellij.lang.properties.IProperty; import com.intellij.lang.properties.PropertiesUtil; import com.sixrr.guiceyidea.utils.MutationUtils; import consulo.document.util.TextRange; import consulo.language.psi.PsiElement; import consulo.language.psi.PsiPolyVariantReference; import consulo.language.psi.ResolveResult; import consulo.language.util.IncorrectOperationException; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; class NamedReference implements PsiPolyVariantReference { private final PsiLiteralExpression element; NamedReference(PsiLiteralExpression element){ this.element = element; } public PsiElement getElement(){ return element; } public TextRange getRangeInElement(){ return new TextRange(0, element.getTextLength()); } @Nullable public PsiElement resolve(){ return null; } @Nonnull public ResolveResult[] multiResolve(boolean incompleteCode){ final String text = element.getText(); final String strippedText = text.substring(1, text.length() - 1); // TODO[yole] figure out what was meant here. this never works and never could have worked. final List<IProperty> properties = PropertiesUtil.findAllProperties(element.getProject(), null, strippedText); final Set<IProperty> propertySet = new HashSet<IProperty>(properties); final ResolveResult[] out = new ResolveResult[propertySet.size()]; int i = 0; for(IProperty property : propertySet){ out[i] = new CandidateInfo(property.getPsiElement(), null); i++; } return out; } public String getCanonicalText(){ return element.getText(); } public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException { return MutationUtils.replaceExpression('\"' + newElementName + '\"', element); } public PsiElement bindToElement(@Nonnull PsiElement element) throws IncorrectOperationException{ return null; } public boolean isReferenceTo(PsiElement element){ if(element == null){ return false; } if(!(element instanceof PsiField)){ return false; } return element.equals(resolve()); } public Object[] getVariants(){ // TODO[yole] figure out what was meant here. this never works and never could have worked. final List<IProperty> properties = PropertiesUtil.findAllProperties(element.getProject(), null, null); final List<Object> out = new ArrayList<Object>(); for(IProperty property : properties){ out.add(property.getName()); } return out.toArray(new Object[out.size()]); } public boolean isSoft(){ return false; } }
true
65f1f18d8d8d0c4114339b7e243b3466d2be52b0
Java
NiveditaGorde/Test
/src/dev/backup/kushal/frameWork/DataProviderInParabank.java
UTF-8
3,163
2.296875
2
[ "Apache-2.0" ]
permissive
/** * */ package dev.backup.kushal.frameWork; import org.testng.annotations.Test; import org.testng.annotations.Test; import java.lang.reflect.Method; import java.util.List; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeMethod; /** * @author kushal * */ class DataProviderInParabank { WebDriver driver; @BeforeTest public void DriverDirectory() { System.setProperty("webdriver.chrome.driver", "G:\\vision_IT\\Material\\eclipse-jee-photon-R-win32-x86_64\\driver\\chromedriver.exe"); } @BeforeMethod public void InitializeDriver() { driver = new ChromeDriver(); String url ="http://parabank.parasoft.com"; driver.get(url); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS); } @Test(dataProvider="SearchProvider") public void testMethod(String author,String sendKey) throws InterruptedException{ try { WebElement clickRegistrer = driver.findElement(By.linkText("Register")); if(clickRegistrer.isDisplayed()) { clickRegistrer.click(); Thread.sleep(2000); for(int i =0; i<=10;i++) { String[] iter = {"firstName" , "lastName" , "address.street" , "address.city" , "address.state" , "address.zipCode" , "phoneNumber" , "ssn" , "username" , "password"}; WebElement sendData = driver.findElement(By.id("customer."+ iter[i] )); ((WebElement) sendData).sendKeys(sendKey); System.out.println("Welcome ->"+author+" Your search key is->"+sendKey); Thread.sleep(3000); //Enter value in register form....!...... String testValue = ((WebElement) sendData).getAttribute("value"); System.out.println(testValue +"::::"+sendKey); sendData.clear(); //Verify if the value in google search box is correct Assert.assertTrue(testValue.equalsIgnoreCase(sendKey)); } } }catch(Exception obj) { System.out.println(obj.getMessage()); } } @AfterTest public void closeAllMethod() { //driver.quit(); } /** * @return Object[][] where first column contains 'author' * and second column contains 'sendKey' */ @DataProvider(name="SearchProvider") public Object[][] getDataFromDataprovider(){ return new Object[][] { { "Name", "Kushal Thadani" }, { "Address", "Sai mastic co-society pimple chouk" }, { "City", "Pune" }, { "State", "Maharashtra" }, { "pinCode", "465254" }, { "phone", "7415451755" }, { "Account", "12456" }, { "confirmAccount", "12456" }, { "Amount", "30000" }, { "sendAccount", "13011" } }; } }
true