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
b726a6fd75ddd0074b9fcbe2af8b0426c2de0858
Java
Veganova/Entity
/app/src/main/java/com/ne/revival_games/entity/WorldObjects/Entity/SpecialEffects/GravityEffect.java
UTF-8
4,077
2.28125
2
[]
no_license
package com.ne.revival_games.entity.WorldObjects.Entity.SpecialEffects; import com.ne.revival_games.entity.WorldObjects.Entity.Entity; import com.ne.revival_games.entity.WorldObjects.Entity.Team; import com.ne.revival_games.entity.WorldObjects.Entity.Util; import com.ne.revival_games.entity.WorldObjects.MySettings; import com.ne.revival_games.entity.WorldObjects.MyWorld; import com.ne.revival_games.entity.WorldObjects.Query; import com.ne.revival_games.entity.WorldObjects.Shape.AShape; import com.ne.revival_games.entity.WorldObjects.Shape.ObjCircle; import org.dyn4j.geometry.Vector2; /** * Created by vishn on 7/12/2017. */ public class GravityEffect extends Effect { private double gravityValue; /** * joins a given shape to the applier at a given displacement from the center using a weldjoint * * @param applier * @param zone uninitialized shape, unplaced (but set angles and other properties) * @param jointDisplacement displacement from the center point of the applier to join at * @param gravityValue * @param world */ public GravityEffect(Entity applier, AShape zone, double gravityValue, Vector2 jointDisplacement, MyWorld world){ aoeJoint(applier, zone, effectType.GRAVITY, jointDisplacement, world); this.gravityValue = gravityValue; // start off this.status = false; } /** * joins a given shape to the applier at a given displacement from the center using a weldjoint * * @param applier * @param jointDisplacement displacement from the center point of the applier to join at * @param world */ public GravityEffect(Entity applier, Vector2 jointDisplacement, MyWorld world) { this.baseQueryName = new Query(applier.getName(), this.getClass().getSimpleName()); Team team = applier.team; double radius = MySettings.getEntityNum(team.toString(), new Query(this.getName(),"radius"), true); double gravityValue = MySettings.getEntityNum(team.toString(), new Query(this.getName(), "strength"), true); aoeJoint(applier, new ObjCircle(radius), effectType.GRAVITY, jointDisplacement, world); this.gravityValue = gravityValue; world.objectDatabase.put(this.zone.body, applier); } @Override public boolean apply(Entity other) { // if (!canApply(other)) { // return; // } if (super.apply(other)) { double distance = Util.getDistance(other.shape.body.getWorldCenter(), this.zone.body.getWorldCenter()); double angle = Util.absoluteAngle(other.shape.body.getWorldCenter(), this.zone.body.getWorldCenter()); double magnitude = gravityValue * this.zone.body.getMass().getMass() * other.shape.body.getMass().getMass() / (Math.pow(distance, 2)); if (Util.nearValue(other.shape.body.getLinearVelocity().x, 0, 0.001) && Util.nearValue(other.shape.body.getLinearVelocity().y, 0, 0.001)) { if (other.shape.body.getMass().getMass() * MyWorld.staticFriction > magnitude) { return false; } magnitude -= other.shape.body.getMass().getMass() * other.frictionCoefficent * MyWorld.staticFriction; } else { magnitude -= other.shape.body.getMass().getMass() * other.frictionCoefficent * MyWorld.kineticFriction; } magnitude = Math.max(magnitude, 0) * 0.01; other.shape.body.applyForce(new Vector2(magnitude * Math.cos(angle), magnitude * Math.sin(angle))); return true; } return false; } @Override public double getMaxCooldown() { return 5 * MyWorld.FPS; } @Override public double getMaxActiveTime() { return 3 * MyWorld.FPS; } @Override protected double getStartupCost() { return 0.5 * MyWorld.FPS; } }
true
fe843a51d0b23d93a63d28dbce7a0069ed366eb7
Java
sebcsaba/GeoResults
/src/main/java/scs/georesults/logic/actions/menetlevel/MentesAction.java
UTF-8
3,217
2.1875
2
[]
no_license
package scs.georesults.logic.actions.menetlevel; import scs.javax.dii.DIIException; import scs.javax.rdb.RdbException; import scs.javax.rdb.StorableEntityBase; import scs.javax.web.DynamicForm; import scs.javax.web.WebException; import scs.georesults.GeoException; import scs.georesults.common.menetlevelformula.MenetlevelFormulaLista; import scs.georesults.common.menetlevelformula.MenetlevelFormulaResz; import scs.georesults.logic.actions.AdatBevitelMentesActionBase; import scs.georesults.logic.beans.AdatbevitelBean; import scs.georesults.logic.beans.menetlevel.MenetlevelAdatokBean; import scs.georesults.om.verseny.Etap; import scs.georesults.logic.actions.*; /** * <p>A menetlevelek felvitele lapon egy adott menetlevél mentését biztosító szolgáltatás osztálya.</p> */ public class MentesAction extends AdatBevitelMentesActionBase { /** * A kijelölt etapon jelzi, hogy módosítás történt az adatain, ezért a hozzá tartozó eredményt frissíteni kell. * * @param id Az etap azonosítója */ protected void invalidate ( long id ) throws WebException, RdbException { try { Etap etap = ( Etap ) getVerseny().getEtapok().findItem( "eid", new Long( id ) ); if ( !etap.isEredmenyFrissitendo() ) { etap.read( getDb() ); etap.setEredmenyFrissitendo( true ); etap.update( getDb() ); } } catch ( DIIException ex ) { throw new GeoException( ex ); } } /** * Az adatokat tartalmazó bean osztály munkafolyamat-beli kulcsát adja vissza. */ protected String getAdatokSessionKey () { return "menetlevelAdatok"; } /** * Feltölti a HTTP kérésben érkezett paraméterekkel a betöltött menetlevelet. * * @param entity A betöltött menetlevél * @param adatokBean Az adatbevitelt segítő osztály * @param form A kérésben érkezett paramétereket tartalmazó objektum */ protected void fillEntity ( StorableEntityBase entity, AdatbevitelBean adatokBean, DynamicForm form ) throws WebException, RdbException { MenetlevelFormulaLista formula = new MenetlevelFormulaLista( form.getString( "menetlevelformula" ) ); MenetlevelAdatokBean adatok = ( MenetlevelAdatokBean ) adatokBean; for ( int i = 0; i < formula.size(); ++i ) { MenetlevelFormulaResz resz = formula.get( i ); if ( resz.getMode() == MenetlevelFormulaResz.MODE_TIME ) { adatok.fillIdo( form ); } else if ( resz.getMode() == MenetlevelFormulaResz.MODE_BUNTETES ) { if ( !resz.isPopup() ) adatok.fillBuntetesek( form ); } else if ( resz.getMode() == MenetlevelFormulaResz.MODE_DARAB ) { if ( !resz.isPopup() ) adatok.fillDarabFuggoBejegyzesek( form, resz.getEfid() ); } else if ( resz.getMode() == MenetlevelFormulaResz.MODE_SORREND ) { if ( !resz.isPopup() ) adatok.fillSorrendFuggoBejegyzesek( form, resz.getEfid() ); } else throw new IllegalArgumentException( resz.toString() ); } } /** * A futamot tartalmazó versenyrész objektum azonosító mezőjének neve. */ protected String getIdFieldName () { return "eid"; } }
true
82f3cd4f208195e252950313e17d13d67a43da4d
Java
daniloMogin/graphicEditor
/GraphicEditorRA245A - Copy/src/gui/Toolbar.java
UTF-8
3,606
2.375
2
[]
no_license
package gui; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Box; import javax.swing.JComboBox; import javax.swing.JToolBar; import javax.swing.SwingUtilities; import javax.swing.UIManager; import app.MainFrame; public class Toolbar extends JToolBar { /** * */ private static final long serialVersionUID = 1209699209668701828L; private UIManager.LookAndFeelInfo[] laf; private JComboBox jcbLaf; public Toolbar() { /** * Dodavanje akcija u toolbar * * @param toolbar */ setFloatable(false); add(MainFrame.getInstance().getActionManager().getFileOpenProjAction()); add(MainFrame.getInstance().getActionManager().getFileOpenWorkAction()); add(MainFrame.getInstance().getActionManager().getFileNewProjAction()); add(MainFrame.getInstance().getActionManager().getFileNewDiagAction()); addSeparator(); add(MainFrame.getInstance().getActionManager().getFileSaveAction()); add(MainFrame.getInstance().getActionManager().getFileSaveAsAction()); addSeparator(); add(MainFrame.getInstance().getActionManager().getUndoAction()); add(MainFrame.getInstance().getActionManager().getRedoAction()); addSeparator(); add(MainFrame.getInstance().getActionManager().getSearchAction()); addSeparator(); add(MainFrame.getInstance().getActionManager().getCutAction()); add(MainFrame.getInstance().getActionManager().getCopyAction()); add(MainFrame.getInstance().getActionManager().getPasteAction()); addSeparator(); add(MainFrame.getInstance().getActionManager().getRotateCCWAction()); add(MainFrame.getInstance().getActionManager().getRotateCWAction()); addSeparator(); add(MainFrame.getInstance().getActionManager().getDeleteElementAction()); add(MainFrame.getInstance().getActionManager() .getDeleteFromTreeAction()); addSeparator(); add(MainFrame.getInstance().getActionManager().getViewZoomInAction()); add(MainFrame.getInstance().getActionManager().getViewZoomOutAction()); addSeparator(); add(MainFrame.getInstance().getActionManager().getViewLassoZoomAction()); add(MainFrame.getInstance().getActionManager().getViewZoomBFAction()); addSeparator(); add(MainFrame.getInstance().getActionManager().getSelectAllAction()); addSeparator(); add(MainFrame.getInstance().getActionManager().getWindowsCasAction()); add(MainFrame.getInstance().getActionManager().getWindowHorAction()); add(MainFrame.getInstance().getActionManager().getWindowVertAction()); addSeparator(); add(MainFrame.getInstance().getActionManager().getWindowNextAction()); add(MainFrame.getInstance().getActionManager().getWindowPrevAction()); addSeparator(); add(Box.createHorizontalGlue()); add(MainFrame.getInstance().getActionManager().getToolsAction()); /** * Event koji nam omogucava da promenimo "look and feel" iz padajuce * liste na toolbaru * * @param toolbar */ laf = UIManager.getInstalledLookAndFeels(); String[] LAFNames = new String[laf.length]; for (int i = 0; i < laf.length; i++) { LAFNames[i] = laf[i].getName(); } jcbLaf = new JComboBox(LAFNames); jcbLaf.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub try { UIManager.setLookAndFeel(laf[jcbLaf.getSelectedIndex()] .getClassName()); SwingUtilities.updateComponentTreeUI(MainFrame .getInstance()); } catch (Exception ex) { System.out.println("Could not load " + laf[jcbLaf.getSelectedIndex()].getClassName()); } } }); add(jcbLaf); } }
true
355235ef088d8d33c9e060e47e6084418c5f7d3b
Java
cckmit/plt
/super-data/clear/src/main/java/com/wi/data/clear/controller/CDeviceAppController.java
UTF-8
1,941
2.046875
2
[]
no_license
package com.wi.data.clear.controller; import com.wi.data.clear.utils.Result; import com.wi.data.clear.utils.ResultGenerator; import com.wi.data.clear.entity.CDeviceApp; import com.wi.data.clear.service.CDeviceAppService; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import java.util.List; import java.util.Map; /** * Created by CodeGenerator on 2018/06/22. */ @RestController @RequestMapping("/c/device/app") public class CDeviceAppController { @Resource private CDeviceAppService cDeviceAppService; @PostMapping("/add") public Result add(CDeviceApp cDeviceApp) { cDeviceAppService.save(cDeviceApp); return ResultGenerator.genSuccessResult(); } @PostMapping("/delete") public Result delete(@RequestParam Integer id) { cDeviceAppService.deleteById(id); return ResultGenerator.genSuccessResult(); } @PostMapping("/update") public Result update(CDeviceApp cDeviceApp) { cDeviceAppService.update(cDeviceApp); return ResultGenerator.genSuccessResult(); } @PostMapping("/detail") public Result detail(@RequestParam Integer id) { CDeviceApp cDeviceApp = cDeviceAppService.findById(id); return ResultGenerator.genSuccessResult(cDeviceApp); } @PostMapping("/list") public Result list(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "0") Integer size) { PageHelper.startPage(page, size); List<CDeviceApp> list = cDeviceAppService.findAll(); PageInfo pageInfo = new PageInfo(list); return ResultGenerator.genSuccessResult(pageInfo); } }
true
7366338719bddb11d117ea4df70ec59ce752a49a
Java
emma-cai/AmeliaV2
/src/main/java/rte/graphmatching/RteConfiguration.java
UTF-8
5,052
2.875
3
[]
no_license
package rte.graphmatching; import rte.similarityflooding.fixpointformula.BasicFormula; import rte.similarityflooding.fixpointformula.CFormula; import rte.similarityflooding.fixpointformula.FixpointFormula; import rte.similarityflooding.BasicSimilarityFlooding; import rte.similarityflooding.SimilarityFloodingInit; import rte.similarityflooding.pcgraph.*; /** * Used to control the various parameters of RTE and Similarity Flooding. */ public class RteConfiguration { // FIXME: Try to find a way to implement these that don't require user updating the enums everytime there's a new implementation public enum GraphComparerType{ SIMILARITY_FLOODING_INIT, BASIC_SIMILARITY_FLOODING; public static GraphComparer getGraphComparer(GraphComparerType type) { if (type.equals(GraphComparerType.SIMILARITY_FLOODING_INIT)) { return new SimilarityFloodingInit(); } else if (type.equals(GraphComparerType.BASIC_SIMILARITY_FLOODING)) { return new BasicSimilarityFlooding(); } else { throw new IllegalStateException("Unknown GraphComparerType"); } } } public enum PCGraphType { COMPLETE_CROSS_PRODUCT, IDENTICAL_LABELS_ONLY, LOOSELY_MATCHED_LABELS_ONLY, STRING_NODE_MATCH_ONLY; public static PCGraph getPCGraph(PCGraphType type) { if (type.equals(PCGraphType.COMPLETE_CROSS_PRODUCT)) { return new CompleteCrossProduct(); } else if (type.equals(PCGraphType.IDENTICAL_LABELS_ONLY)) { return new IdenticalLabelsOnly(); } else if (type.equals(PCGraphType.LOOSELY_MATCHED_LABELS_ONLY)) { return new LooselyMatchedLabelsOnly(); } else if (type.equals(PCGraphType.STRING_NODE_MATCH_ONLY)) { return new StringNodeMatchOnly(); } else { throw new IllegalStateException("Unknown PCGraphType"); } } } public enum FixpointFormulaType { BASIC_FORMULA, C_FORMULA; public static FixpointFormula getFixpointFormula(FixpointFormulaType type) { if (type.equals(FixpointFormulaType.BASIC_FORMULA)) { return new BasicFormula(); } else if (type.equals(FixpointFormulaType.C_FORMULA)) { return new CFormula(); } else { throw new IllegalStateException("Unknown FixpointFormulaType"); } } } /** * Builder class for RteConfiguration. * Sample usage: * RteConfiguration config = new RteConfiguration * .RteConfigurationBuilder(RteConfiguration.GraphComparerType.BASIC_SIMILARITY_FLOODING, RteConfiguration.PCGraphType.COMPLETE_CROSS_PRODUCT) * .nbrSimFloodingIterations(10) * .build(); */ public static class RteConfigurationBuilder { private final GraphComparerType graphComparer; private final PCGraphType pcGraph; private FixpointFormulaType fixpointFormula = FIXPOINT_FORMULA_DEFAULT; private int nbrSimFloodingIterations = NBR_SIM_FLOODING_ITERATIONS_DEFAULT; public RteConfigurationBuilder(GraphComparerType gc, PCGraphType pcg) { graphComparer = gc; pcGraph = pcg; } public RteConfigurationBuilder fixpointFormula(FixpointFormulaType fft) { fixpointFormula = fft; return this; } public RteConfigurationBuilder nbrSimFloodingIterations(int its) { nbrSimFloodingIterations = its; return this; } public RteConfiguration build() { return new RteConfiguration(graphComparer, pcGraph, fixpointFormula, nbrSimFloodingIterations); } } public final GraphComparerType graphComparer; public final PCGraphType pcGraph; public final FixpointFormulaType fixpointFormula; public static final FixpointFormulaType FIXPOINT_FORMULA_DEFAULT = FixpointFormulaType.BASIC_FORMULA; public final int nbrSimFloodingIterations; public static final int NBR_SIM_FLOODING_ITERATIONS_DEFAULT = 10; /** * Create an RteConfiguration with the provided parameters using default values for the remaining fields. * @param gc * @param pcg */ public RteConfiguration(GraphComparerType gc, PCGraphType pcg) { this(gc, pcg, FIXPOINT_FORMULA_DEFAULT, NBR_SIM_FLOODING_ITERATIONS_DEFAULT); } /** * Create an RteConfiguration by specifying all the fields. Alternatively, create a RteConfigurationBuilder by calling * "new RteConfiguration.RteConfigurationBuilder()" appropriately. * @param gc * @param pcg * @param iterations */ public RteConfiguration(GraphComparerType gc, PCGraphType pcg, FixpointFormulaType fpf, int iterations) { graphComparer = gc; pcGraph = pcg; fixpointFormula = fpf; nbrSimFloodingIterations = iterations; } }
true
283cb2e0c3973d58896c8768163b341a487d3080
Java
mayank-17/codingninja
/src/coding/ninjas/assignments/recursion1/SumOfNNaturalNumber.java
UTF-8
483
3.890625
4
[]
no_license
package recursion1; //Given an integer n, find and return the sum of numbers from 1 to n using recursion. public class SumOfNNaturalNumber { public static int sum(int n) { /* * Your class should be named Solution Don't write main(). Don't read input, it * is passed as function argument. Return output and don't print it. Taking * input and printing output is handled automatically. */ if (n != 0) return n + sum(n - 1); else return n; } }
true
418ee202d8e66fb6c159f89622f68a92f37b38d4
Java
dkwjdi/Algorithm
/src/시뮬레이션/boj_17281_야구.java
UTF-8
2,360
2.8125
3
[]
no_license
package 시뮬레이션; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class boj_17281_야구 { static int N, info[][] ,players[], result; static boolean visited[]; public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader((new InputStreamReader(System.in))); N = Integer.parseInt(br.readLine()); info = new int[N+1][10]; players = new int[10]; visited = new boolean[10]; for (int i = 1; i <= N; i++) { StringTokenizer st = new StringTokenizer(br.readLine()); for(int j=1;j<=9;j++) { info[i][j]=Integer.parseInt(st.nextToken()); } } permutation(1); System.out.println(result); } private static void permutation(int cnt) { if(cnt==4) { players[cnt]=1; permutation(cnt+1); } if(cnt==10) { //System.out.println(Arrays.toString(players)); result=Math.max(result, play()); return; } for(int i=2; i<=9; i++) { if(visited[i]) continue; players[cnt]=i; visited[i]=true; permutation(cnt+1); visited[i]=false; } } private static int play() { int score=0; int playesIdx=1; for(int inning=1; inning<=N; inning++) { int out=0; boolean base[] = new boolean [5]; while(out<3) { if(info[inning][players[playesIdx]]==0) out++; else if(info[inning][players[playesIdx]]==1) score+=calScore(1, base); else if(info[inning][players[playesIdx]]==2) score+=calScore(2, base); else if(info[inning][players[playesIdx]]==3) score+=calScore(3, base); else if(info[inning][players[playesIdx]]==4) score+=calScore(4, base); if(++playesIdx==10) playesIdx=1; //다음선수로 } } return score; } private static int calScore(int roota, boolean[] base) { int score=0; if(roota>=3) { for(int i=1; i<=3; i++) { if(base[i]) { score++; base[i]=false; } } if(roota==3) { base[3]=true; return score; } else return ++score; } else { //1 , 2 루타 for(int i=3; i>0; i--) { if(base[i]) { //현재 값이 true 이면 base[i]=false; if(i+roota > 3) score++; //홈으로 들어올 상황 else base[i+roota]=true; // 홈으로 들어올 상황 x } } base[roota]=true; return score; } } }
true
f8986d94af732cd794308a06b754b4a64aeab583
Java
zihanbobo/alphadog
/service-manager/src/main/java/com/moseeker/servicemanager/web/controller/position/PositionATSController.java
UTF-8
6,910
1.765625
2
[]
no_license
package com.moseeker.servicemanager.web.controller.position; import com.moseeker.rpccenter.client.ServiceManager; import com.moseeker.servicemanager.common.ResponseLogNotification; import com.moseeker.thrift.gen.common.struct.Response; import com.moseeker.thrift.gen.position.service.PositionATSServices; import com.moseeker.thrift.gen.position.struct.BatchHandlerJobPostion; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; import com.moseeker.servicemanager.common.ParamUtils; import com.moseeker.servicemanager.web.controller.util.Params; import com.moseeker.thrift.gen.common.struct.BIZException; import com.moseeker.thrift.gen.dao.struct.thirdpartydb.ThirdpartyCompanyChannelConfDO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.List; @Controller public class PositionATSController { Logger logger = LoggerFactory.getLogger(PositionATSController.class); private PositionATSServices.Iface positonATSServices = ServiceManager.SERVICE_MANAGER.getService(PositionATSServices.Iface.class); /** * 获取可同步渠道 */ @RequestMapping(value = "/thirdparty/channel", method = RequestMethod.GET) @ResponseBody public String getSyncChannel(HttpServletRequest request, HttpServletResponse response) { try { Response res = positonATSServices.getSyncChannel(); return ResponseLogNotification.success(request, res); } catch (BIZException e) { return ResponseLogNotification.failJson(request,e); } catch (Exception e){ return ResponseLogNotification.fail(request, e); } } /** * 设置公司同步渠道 */ @RequestMapping(value = "/thirdparty/company/channel", method = RequestMethod.PUT) @ResponseBody public String updateCompanyChannelConf(HttpServletRequest request, HttpServletResponse response) { try { Params<String, Object> params = ParamUtils.parseRequestParam(request); int company_id = params.getInt("company_id"); TypeReference<List<Integer>> typeRef = new TypeReference<List<Integer>>(){}; List<Integer> channel = JSON.parseObject(params.getString("channel"),typeRef); List<ThirdpartyCompanyChannelConfDO> result = positonATSServices.updateCompanyChannelConf(company_id,channel); return ResponseLogNotification.successJson(request,result); } catch (BIZException e) { return ResponseLogNotification.failJson(request,e); } catch (Exception e){ return ResponseLogNotification.fail(request, e); } } /** * 获取可同步渠道 */ @RequestMapping(value = "/thirdparty/company/channel", method = RequestMethod.GET) @ResponseBody public String getCompanyChannelConf(HttpServletRequest request, HttpServletResponse response) { try { int company_id = Integer.valueOf(request.getParameter("company_id")); List<Integer> res = positonATSServices.getCompanyChannelConfByCompanyId(company_id); return ResponseLogNotification.successJson(request, res); } catch (BIZException e) { return ResponseLogNotification.failJson(request,e); } catch (Exception e){ return ResponseLogNotification.fail(request, e); } } /** * 谷露新增职位 */ @RequestMapping(value = "/glluePosition", method = RequestMethod.POST) @ResponseBody public String insertGlluePosition(HttpServletRequest request, HttpServletResponse response) { try { BatchHandlerJobPostion batchHandlerJobPostion = PositionParamUtils.parseGlluePostionParam(request); Response res = positonATSServices.insertGlluePosition(batchHandlerJobPostion); return ResponseLogNotification.success(request, res); } catch (Exception e) { return ResponseLogNotification.fail(request, e); } } /** * 谷露修改职位 */ @RequestMapping(value = "/glluePosition", method = RequestMethod.PUT) @ResponseBody public String updateGlluePosition(HttpServletRequest request, HttpServletResponse response) { try { BatchHandlerJobPostion batchHandlerJobPostion = PositionParamUtils.parseGlluePostionParam(request); Response res = positonATSServices.updateGlluePosition(batchHandlerJobPostion); return ResponseLogNotification.success(request, res); } catch (Exception e) { return ResponseLogNotification.fail(request, e); } } /** * 谷露下架的职位重新发布 */ @RequestMapping(value = "/glluePosition/republish", method = RequestMethod.POST) @ResponseBody public String republishGlluePosition(HttpServletRequest request, HttpServletResponse response) { try { BatchHandlerJobPostion batchHandlerJobPostion = PositionParamUtils.parseGlluePostionParam(request); Response res = positonATSServices.republishPosition(batchHandlerJobPostion); return ResponseLogNotification.success(request, res); } catch (Exception e) { return ResponseLogNotification.fail(request, e); } } /** * 谷露下架的职位重新发布 */ @RequestMapping(value = "/glluePosition/revokePosition", method = RequestMethod.POST) @ResponseBody public String revokeGlluePosition(HttpServletRequest request, HttpServletResponse response) { try { BatchHandlerJobPostion batchHandlerJobPostion = PositionParamUtils.parseGlluePostionParam(request); Response res = positonATSServices.revokeGlluePosition(batchHandlerJobPostion); return ResponseLogNotification.success(request, res); } catch (Exception e) { return ResponseLogNotification.fail(request, e); } } /** * 修改职位福利特色 */ @RequestMapping(value = "/ats/position/feature", method = RequestMethod.POST) @ResponseBody public String atsUpdatePositionFeature(HttpServletRequest request, HttpServletResponse response) { try { BatchHandlerJobPostion batchHandlerJobPostion = PositionParamUtils.parseBatchHandlerJobPostionParam(request); Response res = positonATSServices.atsUpdatePositionFeature(batchHandlerJobPostion); return ResponseLogNotification.success(request, res); } catch (Exception e) { return ResponseLogNotification.fail(request, e); } } }
true
b6e1178a95236fceb9b1eeb0b2e718f27cc1e2b4
Java
tsmarques/WikiGraph
/src/wiki/util/Graph.java
UTF-8
10,822
3.578125
4
[]
no_license
package wiki.util; import java.util.LinkedList; /************************************* * Class containing the implementation of * a Graph. * Might contain weighted edges * Might be Directed or Undirected * Might be a DAG * The id numbering of nodes goes * from 1 to graph size, but their * position on the nodes list starts in 0, so * the node with id = 1 is in position 0 * @author tmarques ************************************/ public class Graph { public static final int N_MAX = 15; // maximum capacity private LinkedList<GraphNode> nodes; private LinkedList<GraphEdge> edges; private int size; // current number of nodes private boolean isDirected; private boolean isWeighted; GraphAlgorithms algorithms = GraphAlgorithms.getAlgorithms(this); public Graph(boolean isDirected,boolean isWeighted) { nodes = new LinkedList<>(); edges = new LinkedList<>(); size = 0; setGraphOrientation(isDirected); setGraphWeighted(isWeighted); } /** * Set if graph edges have a weight associated * @param isWeighted */ public void setGraphWeighted(boolean isWeighted) { this.isWeighted = isWeighted; } /** * Set if this graph is directed * @param isDirected */ public void setGraphOrientation(boolean isDirected){ this.isDirected = isDirected; } /** * This method is used after * an algorithm is run in this graph. * The nodes are marked as unvisited * so it is possible to run them again. */ public void resetNodes() { for(GraphNode node : nodes) node.unVisit(); } /** * Returns the current size of this graph * @return */ public int size() { return size; } public boolean isEmpty() { return size == 0; } /** * Returns all the nodes of this graph * @return */ public LinkedList<GraphNode> getNodes() { return nodes; } public LinkedList<GraphEdge> getEdges() { return edges; } /** * Returns the node specified by id * @param index * @return */ public GraphNode getNode(int id) { return nodes.get(id - 1); } /** If this graph is not full add another node. * @return True if success */ public boolean addNode() { if(isFull()) return false; size++; GraphNode newNode = new GraphNode(size); nodes.addLast(newNode); return true; } /** * If the node exists it is removed, * and is removed as adjacent from * other nodes * @param node * @return True if success */ public boolean removeNode(int node) { if(node > size) // if the node does not exist.Only relevant in in unit tests return false; // Remove the given node as adjacent from others for(int i = 1; i <= size; i++) { if(i != node) { GraphNode thisNode = getNode(i); LinkedList<GraphEdge> adjacents = (LinkedList<GraphEdge>) thisNode.getAdjacentNodes().clone(); for(GraphEdge cursor : adjacents) if(cursor.getToNode().id() == node) { edges.remove(cursor); thisNode.getAdjacentNodes().remove(adjacents.indexOf(cursor)); } } } for(int i = 1; i <= size; i++) { // remove edges coming and going to the given node if(!removeFromEdgesList(node, i)) removeFromEdgesList(i, node); } // remove the node and correct the id of the nodes // from node to size. nodes.remove(node - 1); size--; for(int i = node; i <= size; i++) getNode(i).setId(i); return true; } /** * Add edge,directed or not,between the given Nodes, * if they exist. * Returns <code> True </code> if successful * and <code> False </code> if edge already exists * @param fromNode * @param toNode * @return <code>True</code> or <code>False</code> */ public boolean addEdge(int fromNode, int toNode,int weight) { if(isDirected()) { GraphEdge adjacentNode = new GraphEdge(getNode(fromNode), getNode(toNode), weight); if(getNode(fromNode).addAdjacentNode(adjacentNode)) { edges.add(adjacentNode); return true; // if successfully added an edge } return false; // if edge already exists } else { // if the graph is not directed GraphEdge node1 = new GraphEdge(getNode(fromNode),getNode(toNode), weight); GraphEdge node2 = new GraphEdge(getNode(toNode), getNode(fromNode), weight); boolean n1 = getNode(fromNode).addAdjacentNode(node1); boolean n2 = getNode(toNode).addAdjacentNode(node2); if(n1 && n2) { edges.add(node1); return true; // if successfully added an edge } return false; // if edge already exists } } /** * Remove edge between the given nodes, if * it exists. * Returns <code> True </code> if successful * and <code> False </code> if edge does not exist. * @param fromNode * @param toNode * @return True if success */ public boolean removeEdge(int fromNode, int toNode) { if(isDirected()) { edges.remove(getNode(fromNode).getEdge(getNode(toNode))); // remove the edge from the edge list return getNode(fromNode).removeAdjacentNode(getNode(toNode)); } else { boolean n1 = getNode(fromNode).removeAdjacentNode(getNode(toNode)); boolean n2 = getNode(toNode).removeAdjacentNode(getNode(fromNode)); if(n1 && n2) // remove the edge from the edges list removeFromEdgesList(fromNode, toNode); return (n1 && n2); } } /** * Change the weight of a given edge * @param fromNode * @param toNode * @param weight */ public void changeEdgeWeight(int fromNode, int toNode, int weight) { if(isDirected) getEdge(fromNode, toNode).setWeight(weight); else { getNode(fromNode).getEdge(getNode(toNode)).setWeight(weight); getNode(toNode).getEdge(getNode(fromNode)).setWeight(weight); } } /** * Removes the edge connecting * the given nodes, if it exists, * from the edges list. * @param fromNode * @param toNode * @return */ private boolean removeFromEdgesList(int fromNode, int toNode) { int index = -1; for(GraphEdge cursor : edges) { if(cursor.getFromNode().id() == fromNode && cursor.getToNode().id() == toNode) index = edges.indexOf(cursor); if(!isDirected()) // if graph is directed doesn't need to check toNode -> fromNode if(cursor.getFromNode().id() == toNode && cursor.getToNode().id() == fromNode) index = edges.indexOf(cursor); } if(index == -1) return false; edges.remove(index); return true; } /** * Returns the edge that connects * the two given nodes, if it * exists. * @param fromNode * @param toNode * @return */ public GraphEdge getEdge(int fromNode, int toNode) { for(GraphEdge cursor : edges) { if(cursor.getFromNode().id() == fromNode) if(cursor.getToNode().id() == toNode) return cursor; if(!isDirected()) { if(cursor.getFromNode().id() == toNode) if(cursor.getToNode().id() == fromNode) return cursor; } } return null; } /** * Returns <code>true</code> if * this graph is weighted and <code>false</false> if not * @return if the graph is weighted */ public boolean isWeighted() { return isWeighted; } /** * Returns <code>true</code> if * this graph is directed and <code>false</false> if not * @return if graph is directed */ public boolean isDirected() { return isDirected; } /** * Returns if this graph has * an edge with negative weight * @return */ public boolean hasNegativeEdges() { for(GraphEdge cursor : getEdges()) if(cursor.weight() < 0) return true; return false; } /** * Returns <code>True</code> if * this graph cannot have more nodes. * @return */ public boolean isFull() { return (size == N_MAX); } /** * Returns the transpose of this graph * @return */ public Graph transposeGraph() { if(isDirected()) { Graph transposeGraph = new Graph(isDirected(), isWeighted()); for(GraphNode node : getNodes()) { transposeGraph.addNode(); // used to redraw the nodes in the right position in GUI transposeGraph.getNode(node.id()).setNodeInfo(node.id(), (int)node.getCenterX(), (int)node.getCenterY()); } for(GraphEdge edge : getEdges()) { int fromNode = edge.getToNode().id(); int toNode = edge.getFromNode().id(); transposeGraph.addEdge(fromNode, toNode, edge.weight()); } return transposeGraph; } else return this; } /** * Used for debugging. * Prints all the information about * this graph: Nodes, their edges, * if it is weighted, directed * if it has negative Edges and its size. */ public void printGraphInfo() { System.out.println("## Graph Info ##"); System.out.println("Is Directed: " + isDirected()); System.out.println("Is weighted: " + isWeighted()); System.out.println("Size: " + size()); for(GraphNode node : getNodes()) { System.out.println("Node: " + node.id()); for(GraphEdge edge : node.getAdjacentNodes()) System.out.println(" -> " + edge.getToNode().id() + " weight: " + edge.weight()); } System.out.println("// Edges List //"); for(GraphEdge edge : getEdges()) System.out.println(edge.getFromNode().id() + " -> " + edge.getToNode().id() + " weight: " + edge.weight()); System.out.println("Has negative Edges: " + hasNegativeEdges()); } /************** * Algorithms * **************/ public LinkedList<GraphNode> breadthFirstSearch() { return algorithms.breadthFirstSearch(); } public LinkedList<GraphNode> depthFirstSearch() { return algorithms.depthFirstSearch(); } /** * NOTE: * Prior to running this method * it is needed to check if the graph * is weighted and undirected. If not * it shouldn't run. * @param root * @return */ public LinkedList<GraphEdge> primAlgorithm() { return algorithms.primAlgorithm(); } /** * NOTE: * Prior to running this method * it is needed to check if the graph * is weighted and undirected. If not * it shouldn't run * @param root * @return */ public int[] kruskalAlgorithm(int root) { return algorithms.kruskalAlgorithm(); } /** * Prior to running this algorithm * it's needed to check if there are * negative weight edges in the graph: * if yes don' run. * @param root */ public LinkedList<int[]> Dijkstra() { return algorithms.dijkstraAlgorithm(); } public int[] BellmanFord(int root) { return algorithms.bellmanFordAlgorithm(root); } /** * Not working * @return */ public int[][] FloydWarshall() { return algorithms.floydWarshallAlgorithm(); } /** * Applies a BFS and returns * the reachable nodes * @return */ public LinkedList<GraphNode> isConnected() { return algorithms.breadthFirstSearch(); // use BFS to get all reachable nodes } /** * Makes a Topological Sorting * of this graph, if he is * a DAG. * @return */ public LinkedList<GraphNode> topologicalSort() { return algorithms.topologicalSort(); } public LinkedList<GraphNode> limitedDepthSearch(int MAX_DEPTH) { return algorithms.limitedDepthSearch(MAX_DEPTH); } }
true
52eabcd24b6d9884b2f5b5fd80b95fd6d7809cee
Java
azeredudu1/blog-test
/src/main/java/com/azeredudu/entreprise/controller/indexController.java
UTF-8
909
2.0625
2
[]
no_license
package com.azeredudu.entreprise.controller; import java.security.Principal; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.azeredudu.entreprise.service.ItemService; import com.azeredudu.entreprise.service.UserService; @Controller public class indexController { @Autowired private ItemService itemService; @Autowired UserService userService; @RequestMapping( value = "/index" ) public String index( Model model, Principal principal ) { model.addAttribute( "items", itemService.getItems() ); if ( principal != null ) { String name = principal.getName(); model.addAttribute( "user", userService.findOne( name ) ); } return "index"; } }
true
e03671dbf206e9d98ff4d4e8cde1ef18206d0543
Java
TALBOTdev/RockPaperScissorsApp
/src/utility/LoggerUtil.java
UTF-8
1,625
3.296875
3
[]
no_license
package utility; import java.text.SimpleDateFormat; import java.util.Date; /** * * @author Ben Talbot * Proves formatted message strings based on incoming message criteria * */ public class LoggerUtil { private Message msg; public LoggerUtil () { } public LoggerUtil (Message msg) { this.msg = msg; } //https://stackoverflow.com/questions/16592493/getting-time-from-a-date-object /** * Returns a message to signify the initialization of a client * @param msg * @return Message string for display */ public static String getInitializationMessage(Message msg) { Date date = new Date(); SimpleDateFormat localDateFormat = new SimpleDateFormat("HH:mm:ss"); String time = localDateFormat.format(date); return "User " + msg.getUser() + " connected at: " + time + "\n"; } /** * Returns a message to signify a client has disconnected * @param msg Message for display * @return */ public static String getDisconnectMessage(Message msg) { Date date = msg.getTimeStamp(); SimpleDateFormat localDateFormat = new SimpleDateFormat("HH:mm:ss"); String time = localDateFormat.format(date); return "User " + msg.getUser() + " disconnected at: " + time + "\n"; } /** * Generic message used for client chat * @param msg Message for display * @return */ public static String getMessage(Message msg) { return msg.getUser() + ": " + msg.getMsg() + "\n"; } /** * Generic message to signify a players choice * @param msg * @return */ public static String getPlayerChoiceMessage(Message msg) { return msg.getUser() + " chooses " + msg.getMsg() + "\n"; } }
true
468556f757d55dfe6f87d853486ad582cdb4899a
Java
dpkg/FirstEgit
/MyFirstApp/src/com/dpkg/myfirstapp/MainActivity.java
UTF-8
1,288
2.703125
3
[]
no_license
package com.dpkg.myfirstapp; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.EditText; public class MainActivity extends Activity { public static final String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } // @Override // public boolean onCreateOptionsMenu(Menu menu) { // // Inflate the menu; this adds items to the action bar if it is present. // getMenuInflater().inflate(R.menu.activity_main, menu); // return true; // } /** Called when the user clicks the Send button */ public void sendMessage(View view) { // Do something in response to button // create a new intent to start new activity in response to button press Intent sendBtnIntent = new Intent(this, DisplayMessageActivity.class); // get data from current activity String message = ((EditText) findViewById(R.id.edit_message)).getText().toString(); // add date to intent for sending to next activity sendBtnIntent.putExtra(EXTRA_MESSAGE, message); // start the other activity passing the intent with loaded data startActivity(sendBtnIntent); } }
true
5d7c1423cc26b1f05b429b20e8fcb7dc8ead5041
Java
AzatIdrisov/job4j_tracker
/src/test/java/ru/job4j/tracker/MockitoTest.java
UTF-8
2,464
2.625
3
[]
no_license
package ru.job4j.tracker; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.hamcrest.Matchers.is; public class MockitoTest { @Test public void replaceTest() { Output out = new StubOutput(); MemTracker tracker = new MemTracker(); tracker.add(new Item("Replaced item")); String replacedName = "New item name"; EditAction rep = new EditAction(out); Input input = mock(Input.class); when(input.askInt(any(String.class))).thenReturn(1); when(input.askStr(any(String.class))).thenReturn(replacedName); rep.execute(input, tracker); String ln = System.lineSeparator(); assertThat(out.toString(), is("Successfully edit" + ln)); assertThat(tracker.findAll().get(0).getName(), is(replacedName)); } @Test public void deleteTest() { Output out = new StubOutput(); MemTracker tracker = new MemTracker(); tracker.add(new Item("Deleted item")); DeleteAction delete = new DeleteAction(out); Input input = mock(Input.class); when(input.askInt(any(String.class))).thenReturn(1); delete.execute(input, tracker); String ln = System.lineSeparator(); assertThat(out.toString(), is("Successfully deleted" + ln)); } @Test public void findByIdTest() { Output out = new StubOutput(); MemTracker tracker = new MemTracker(); tracker.add(new Item("New item")); FindByIdAction find = new FindByIdAction(out); Input input = mock(Input.class); when(input.askInt(any(String.class))).thenReturn(1); find.execute(input, tracker); String ln = System.lineSeparator(); assertThat(out.toString(), is("Id: 1 Name: New item" + ln)); } @Test public void findByNameTest() { Output out = new StubOutput(); MemTracker tracker = new MemTracker(); tracker.add(new Item("New item")); FindByNameAction find = new FindByNameAction(out); Input input = mock(Input.class); when(input.askStr(any(String.class))).thenReturn("New item"); find.execute(input, tracker); String ln = System.lineSeparator(); assertThat(out.toString(), is("Id: 1 Name: New item" + ln)); } }
true
db691205d90569fcd880b3f9b298966d17ab5a5e
Java
nusktec/Radio_with_Chat
/app/src/main/java/org/druplay/radioapp/ActivityPolicy.java
UTF-8
1,600
2.015625
2
[]
no_license
package org.druplay.radioapp; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.widget.Toast; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.TextHttpResponseHandler; import org.sufficientlysecure.htmltextview.HtmlTextView; import cz.msebera.android.httpclient.Header; public class ActivityPolicy extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_policy); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); assert actionBar!=null; actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setDisplayShowHomeEnabled(true); actionBar.setElevation(2); actionBar.setTitle(String.valueOf("Privacy Policy")); AsyncHttpClient client = new AsyncHttpClient(); client.get(new NSCLib(this).API_POLICY, new TextHttpResponseHandler() { @Override public void onFailure(int i, Header[] headers, String s, Throwable throwable) { Toast.makeText(ActivityPolicy.this, "Please try again", Toast.LENGTH_LONG).show(); } @Override public void onSuccess(int i, Header[] headers, String s) { ((HtmlTextView)findViewById(R.id.policy_txt)).setHtml(s); } }); } }
true
05991c078b7c0e172741944edf51ea2b9ec3b32c
Java
vinayanayak88/statistics-API
/src/main/java/com/n26/aggregator/controller/TransactionController.java
UTF-8
1,407
2.1875
2
[]
no_license
/** * */ package com.n26.aggregator.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.n26.aggregator.model.Transaction; import com.n26.aggregator.service.TransactionService; /** * @author vinayanayak * @date 04-Jan-2018 * TransactionController.java */ @RestController @RequestMapping(value = "/transactions", produces = "application/json") public class TransactionController { private static final Logger logger = LoggerFactory.getLogger(TransactionController.class); @Autowired TransactionService transactionService; @RequestMapping(method = RequestMethod.POST, consumes = "application/json") @ResponseBody public ResponseEntity<Void> saveTransaction(@RequestBody Transaction transaction) { logger.info(TransactionController.class + " : Received post request for transaction "); transactionService.addTransaction(transaction); return new ResponseEntity<>(HttpStatus.CREATED); } }
true
34cf3c5038d77dbc845f37fd2c0d37654adff0d1
Java
yesamer/drools
/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/JoinNodeRangeIndexingTest.java
UTF-8
20,124
1.742188
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2020 Red Hat, Inc. and/or its affiliates. * * 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.drools.compiler.integrationtests; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.drools.ancompiler.CompiledNetwork; import org.drools.core.common.BetaConstraints; import org.drools.core.reteoo.JoinNode; import org.drools.core.reteoo.ObjectSink; import org.drools.core.reteoo.ObjectSinkPropagator; import org.drools.core.reteoo.ObjectTypeNode; import org.drools.testcoverage.common.model.Cheese; import org.drools.testcoverage.common.model.Person; import org.drools.testcoverage.common.model.Pet; import org.drools.testcoverage.common.model.Pet.PetType; import org.drools.testcoverage.common.model.Primitives; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; import org.drools.testcoverage.common.util.KieUtil; import org.drools.testcoverage.common.util.TestParametersUtil; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.kie.api.KieBase; import org.kie.api.builder.KieModule; import org.kie.api.conf.BetaRangeIndexOption; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; @RunWith(Parameterized.class) public class JoinNodeRangeIndexingTest { private final KieBaseTestConfiguration kieBaseTestConfiguration; public JoinNodeRangeIndexingTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { this.kieBaseTestConfiguration = kieBaseTestConfiguration; } @Parameterized.Parameters(name = "KieBase type={0}") public static Collection<Object[]> getParameters() { return TestParametersUtil.getKieBaseCloudConfigurations(true); } private KieBase getKieBaseWithRangeIndexOption(String drl) { KieModule kieModule = KieUtil.getKieModuleFromDrls("indexing-test", kieBaseTestConfiguration, drl); return KieBaseUtil.newKieBaseFromKieModuleWithAdditionalOptions(kieModule, kieBaseTestConfiguration, BetaRangeIndexOption.ENABLED); } @Test public void testRangeIndexForJoin() { final String drl = "import " + Person.class.getCanonicalName() + ";\n" + "import " + Pet.class.getCanonicalName() + ";\n" + "rule R1\n" + "when\n" + " $pet : Pet()\n" + " Person( age > $pet.age )\n" + "then\n" + "end\n"; final KieBase kbase = getKieBaseWithRangeIndexOption(drl); assertIndexedTrue(kbase, Person.class); final KieSession ksession = kbase.newKieSession(); try { ksession.insert(new Pet(PetType.CAT, 10)); ksession.insert(new Person("Paul", 20)); assertThat(ksession.fireAllRules()).isEqualTo(1); } finally { ksession.dispose(); } } private void assertIndexedTrue(KieBase kbase, Class<?> factClass) { assertIndexed(kbase, factClass, true); } private void assertIndexedFalse(KieBase kbase, Class<?> factClass) { assertIndexed(kbase, factClass, false); } private void assertIndexed(KieBase kbase, Class<?> factClass, boolean isIndexed) { final ObjectTypeNode otn = KieUtil.getObjectTypeNode(kbase, factClass); assertThat(otn).isNotNull(); ObjectSinkPropagator objectSinkPropagator = otn.getObjectSinkPropagator(); if (this.kieBaseTestConfiguration.useAlphaNetworkCompiler()) { objectSinkPropagator = ((CompiledNetwork) objectSinkPropagator).getOriginalSinkPropagator(); } // This method expect to test only one JoinNode of factClass boolean isPassedForJoinNode = false; ObjectSink[] sinks = objectSinkPropagator.getSinks(); for (ObjectSink sink : sinks) { if (sink instanceof JoinNode) { JoinNode join = (JoinNode) sink; BetaConstraints betaConstraints = join.getRawConstraints(); assertThat(betaConstraints.isIndexed()).isEqualTo(isIndexed); isPassedForJoinNode = true; } } assertThat(isPassedForJoinNode).isTrue(); } @Test public void testCoercionBigDecimalVsInt() { final String drl = "package org.drools.compiler.integrationtests;\n" + "import " + Cheese.class.getCanonicalName() + ";\n" + "import " + Primitives.class.getCanonicalName() + ";\n" + "global java.util.List list;\n" + "rule R\n" + " when\n" + " Cheese($price : price)\n" + " p : Primitives(bigDecimal < $price)\n" + " then\n" + " list.add( p );\n" + "end"; // Integer is coerced to BigDecimal final KieBase kbase = getKieBaseWithRangeIndexOption(drl); assertIndexedTrue(kbase, Primitives.class); final KieSession ksession = kbase.newKieSession(); try { final List<Primitives> list = new ArrayList<>(); ksession.setGlobal("list", list); final Primitives bd42 = new Primitives(); bd42.setBigDecimal(new BigDecimal("42")); ksession.insert(bd42); final Primitives bd43 = new Primitives(); bd43.setBigDecimal(new BigDecimal("43")); ksession.insert(bd43); ksession.insert(new Cheese("gorgonzola", 43)); ksession.fireAllRules(); assertThat(list).containsExactly(bd42); } finally { ksession.dispose(); } } @Test public void testCoercionIntVsBigDecimal() { final String drl = "package org.drools.compiler.integrationtests;\n" + "import " + Person.class.getCanonicalName() + ";\n" + "import " + Primitives.class.getCanonicalName() + ";\n" + "global java.util.List list;\n" + "rule R\n" + "\n" + " when\n" + " Person($salary : salary)\n" + " p : Primitives(intPrimitive < $salary)\n" + " then\n" + " list.add( p );\n" + "end"; // BigDecimal is coerced to Integer final KieBase kbase = getKieBaseWithRangeIndexOption(drl); assertIndexedTrue(kbase, Primitives.class); final KieSession ksession = kbase.newKieSession(); try { final List<Primitives> list = new ArrayList<>(); ksession.setGlobal("list", list); final Primitives i42 = new Primitives(); i42.setIntPrimitive(42); ksession.insert(i42); final Primitives i43 = new Primitives(); i43.setIntPrimitive(43); ksession.insert(i43); Person john = new Person("John"); john.setSalary(new BigDecimal("43.0")); ksession.insert(john); ksession.fireAllRules(); assertThat(list).containsExactly(i42); } finally { ksession.dispose(); } } @Test public void testCoercionStringVsIntWithMap() { final String drl = "package org.drools.compiler.integrationtests;\n" + "import " + Map.class.getCanonicalName() + ";\n" + "import " + Cheese.class.getCanonicalName() + ";\n" + "global java.util.List list;\n" + "rule R\n" + " when\n" + " $map : Map()" + " p : Cheese(type < $map.get(\"key\"))\n" + " then\n" + " list.add( p );\n" + "end"; // Integer is coerced to String (thus, String comparison) final KieBase kbase = getKieBaseWithRangeIndexOption(drl); // We don't index this case assertIndexedFalse(kbase, Cheese.class); final KieSession ksession = kbase.newKieSession(); try { final List<Cheese> list = new ArrayList<>(); ksession.setGlobal("list", list); final Cheese cheese1 = new Cheese("1"); ksession.insert(cheese1); final Cheese cheese5 = new Cheese("5"); ksession.insert(cheese5); final Cheese cheese10 = new Cheese("10"); ksession.insert(cheese10); Map<String, Object> map = new HashMap<>(); map.put("key", 5); ksession.insert(map); ksession.fireAllRules(); assertThat(list).containsExactly(cheese1); // If we do String comparison, cheese10 is also contained } finally { ksession.dispose(); } } @Test public void testCoercionIntVsStringWithMap() { // we don't enable range index for this case final String drl = "package org.drools.compiler.integrationtests;\n" + "import " + Cheese.class.getCanonicalName() + ";\n" + "import " + MapHolder.class.getCanonicalName() + ";\n" + "global java.util.List list;\n" + "rule R\n" + " when\n" + " Cheese($type : type)" + " p : MapHolder(map.get(\"key\") < $type)\n" + " then\n" + " list.add( p );\n" + "end"; // String is coerced to Integer (thus, Number comparison) final KieBase kbase = getKieBaseWithRangeIndexOption(drl); // We don't index this case assertIndexedFalse(kbase, MapHolder.class); final KieSession ksession = kbase.newKieSession(); try { final List<MapHolder> list = new ArrayList<>(); ksession.setGlobal("list", list); final MapHolder holder1 = new MapHolder(); holder1.getMap().put("key", 1); ksession.insert(holder1); final MapHolder holder5 = new MapHolder(); holder5.getMap().put("key", 5); ksession.insert(holder5); final MapHolder holder10 = new MapHolder(); holder10.getMap().put("key", 10); ksession.insert(holder10); final Cheese cheese = new Cheese("5"); ksession.insert(cheese); ksession.fireAllRules(); assertThat(list).containsExactly(holder1); } finally { ksession.dispose(); } } public static class MapHolder { private Map<String, Object> map = new HashMap<>(); public Map<String, Object> getMap() { return map; } public void setMap(Map<String, Object> map) { this.map = map; } } @Test public void testJoinWithGlobal() { final String drl = "import " + Person.class.getCanonicalName() + ";\n" + "global Integer minAge;\n" + "rule R1\n" + "when\n" + " Person( age > minAge )\n" + "then\n" + "end\n"; // Actually, [age > minAge] becomes an AlphaNode and doesn't use index. final KieBase kbase = getKieBaseWithRangeIndexOption(drl); final KieSession ksession = kbase.newKieSession(); try { ksession.setGlobal("minAge", 15); ksession.insert(new Person("Paul", 20)); assertThat(ksession.fireAllRules()).isEqualTo(1); } finally { ksession.dispose(); } } @Test public void testInsertUpdateDelete() { final String drl = "import " + Person.class.getCanonicalName() + ";\n" + "import " + Pet.class.getCanonicalName() + ";\n" + "global java.util.Set result;\n" + "rule R1\n" + "when\n" + " $pet : Pet()\n" + " $person : Person( age > $pet.age )\n" + "then\n" + " result.add( $person.getName() + \" > \" + $pet.getName() );\n" + "end\n" + "rule R2\n" + " salience 100\n" + "when\n" + " String (this == \"trigger R2\")\n" + " $person : Person( name == \"Paul\" )\n" + "then\n" + " modify($person) {setAge(20)}\n" + "end\n" + "rule R3\n" + " salience 100\n" + "when\n" + " String (this == \"trigger R3\")\n" + " $pet : Pet( )\n" + "then\n" + " modify($pet) {setAge($pet.getAge() - 5)}\n" + "end\n" + "rule R4\n" + " salience 100\n" + "when\n" + " String (this == \"trigger R4\")\n" + " $pet : Pet( name == \"Oliver\" )\n" + "then\n" + " delete($pet);\n" + "end\n"; final KieBase kbase = getKieBaseWithRangeIndexOption(drl); assertIndexedTrue(kbase, Person.class); final KieSession ksession = kbase.newKieSession(); try { final Set<String> result = new HashSet<>(); ksession.setGlobal("result", result); ksession.insert(new Pet("Oliver", 5)); ksession.insert(new Pet("Leo", 10)); ksession.insert(new Pet("Milo", 20)); ksession.insert(new Person("John", 10)); ksession.insert(new Person("Paul", 10)); assertThat(ksession.fireAllRules()).isEqualTo(2); assertThat(result).containsExactlyInAnyOrder("John > Oliver", "Paul > Oliver"); ksession.insert("trigger R2"); // set Paul's age = 20 assertThat(ksession.fireAllRules()).isEqualTo(3); assertThat(result).containsExactlyInAnyOrder("John > Oliver", "Paul > Oliver", "Paul > Leo"); ksession.insert("trigger R3"); // set all Pets' age minus 5 assertThat(ksession.fireAllRules()).isEqualTo(8); assertThat(result).containsExactlyInAnyOrder("John > Oliver", "John > Leo", "Paul > Oliver", "Paul > Leo", "Paul > Milo"); ksession.insert("trigger R4"); // delete Oliver ksession.insert(new Person("George", 15)); assertThat(ksession.fireAllRules()).isEqualTo(2); assertThat(result).containsExactlyInAnyOrder("John > Oliver", "John > Leo", "Paul > Oliver", "Paul > Leo", "Paul > Milo", "George > Leo"); } finally { ksession.dispose(); } } @Test public void testBoxed() { final String drl = "import " + Person.class.getCanonicalName() + ";\n" + "import " + IntegerHolder.class.getCanonicalName() + ";\n" + "rule R1\n" + "when\n" + " $holder : IntegerHolder()\n" + " Person( age > $holder.value )\n" + "then\n" + "end\n"; final KieBase kbase = getKieBaseWithRangeIndexOption(drl); assertIndexedTrue(kbase, Person.class); final KieSession ksession = kbase.newKieSession(); try { ksession.insert(new IntegerHolder(10)); ksession.insert(new Person("Paul", 20)); assertThat(ksession.fireAllRules()).isEqualTo(1); } finally { ksession.dispose(); } } @Test public void testBoxed2() { final String drl = "import " + Person.class.getCanonicalName() + ";\n" + "import " + IntegerHolder.class.getCanonicalName() + ";\n" + "rule R1\n" + "when\n" + " $p : Person( )\n" + " IntegerHolder(value > $p.age)\n" + "then\n" + "end\n"; final KieBase kbase = getKieBaseWithRangeIndexOption(drl); assertIndexedTrue(kbase, IntegerHolder.class); final KieSession ksession = kbase.newKieSession(); try { ksession.insert(new IntegerHolder(30)); ksession.insert(new Person("Paul", 20)); assertThat(ksession.fireAllRules()).isEqualTo(1); } finally { ksession.dispose(); } } public static class IntegerHolder { private Integer value; public IntegerHolder(Integer value) { this.value = value; } public Integer getValue() { return value; } } @Test public void testMultipleFacts() { final String drl = "import " + Person.class.getCanonicalName() + ";\n" + "import " + Pet.class.getCanonicalName() + ";\n" + "global java.util.Set result;\n" + "rule R1\n" + "when\n" + " $pet : Pet()\n" + " $person : Person( age > $pet.age )\n" + "then\n" + " result.add( $person.getName() + \" > \" + $pet.getName() );\n" + "end\n"; final KieBase kbase = getKieBaseWithRangeIndexOption(drl); assertIndexedTrue(kbase, Person.class); final KieSession ksession = kbase.newKieSession(); Set<String> result = new HashSet<>(); ksession.setGlobal("result", result); try { ksession.insert(new Pet("Charlie", 5)); ksession.insert(new Pet("Max", 10)); ksession.insert(new Pet("Buddy", 15)); ksession.insert(new Pet("Oscar", 20)); ksession.insert(new Person("John", 2)); ksession.insert(new Person("Paul", 10)); ksession.insert(new Person("George", 20)); ksession.insert(new Person("Ringo", 30)); assertThat(ksession.fireAllRules()).isEqualTo(8); assertThat(result).containsExactlyInAnyOrder("Paul > Charlie", "George > Charlie", "George > Max", "George > Buddy", "Ringo > Charlie", "Ringo > Max", "Ringo > Buddy", "Ringo > Oscar"); } finally { ksession.dispose(); } } }
true
038d6044caca8ed48a1a4f26e9e12b22b772ad97
Java
VMHDev/java_studentmanagementhibernate
/Source/18424029_Ex02/src/VMHDAO/DAOUser.java
UTF-8
5,624
2.53125
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package VMHDAO; import VMHBUS.*; import VMHDTO.*; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.nio.charset.StandardCharsets; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author VMHIT */ public class DAOUser { public static boolean AddUser(String _UserName, String _Password, boolean _IsAdmin) { String sPassEncrypt = clsEncryption.encrypt(_Password, _UserName); String sClass = _UserName + "," + sPassEncrypt + ",0"; if (_IsAdmin) { sClass = _UserName + "," + sPassEncrypt + ",1"; } StringBuilder data = new StringBuilder(); try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("./data/user.csv"), "UTF-8"))) { String line = br.readLine(); while (line != null) { data.append(line).append("\n"); line = br.readLine(); } data.append(sClass); br.close(); } catch (FileNotFoundException ex) { Logger.getLogger(DAOUser.class.getName()).log(Level.SEVERE, null, ex); return false; } catch (IOException ex) { Logger.getLogger(DAOUser.class.getName()).log(Level.SEVERE, null, ex); return false; } try (BufferedWriter br = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("./data/user.csv"), StandardCharsets.UTF_8))) { br.write(data.toString()); br.close(); } catch (IOException ex) { Logger.getLogger(DAOUser.class.getName()).log(Level.SEVERE, null, ex); return false; } return true; } public static boolean ChangePasswordUser(String _UserName, String _Password) { String sPassEncrypt = clsEncryption.encrypt(_Password, _UserName); String sUser = _UserName + "," + sPassEncrypt + ",0"; if (clsParameterSys.getIsAdmin()) { sUser = _UserName + "," + sPassEncrypt + ",1"; } StringBuilder data = new StringBuilder(); try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("./data/user.csv"), "UTF-8"))) { String line = br.readLine(); while (line != null) { String[] dataLine = line.split(","); String udp = "\n"; if (_UserName == null ? dataLine[0] == null : _UserName.equals(dataLine[0])) { udp = sUser + "\n"; data.append(udp); } else { data.append(line).append(udp); } line = br.readLine(); } br.close(); } catch (FileNotFoundException ex) { Logger.getLogger(DAOUser.class.getName()).log(Level.SEVERE, null, ex); return false; } catch (IOException ex) { Logger.getLogger(DAOUser.class.getName()).log(Level.SEVERE, null, ex); return false; } try (BufferedWriter br = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("./data/user.csv"), StandardCharsets.UTF_8))) { br.write(data.toString()); br.close(); } catch (IOException ex) { Logger.getLogger(DAOUser.class.getName()).log(Level.SEVERE, null, ex); return false; } return true; } // Lấy thông tin user theo user name public DTOUser GetUserWithName(String _UserName) throws IOException { try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("./data/user.csv"), "UTF-8"))) { String line = br.readLine(); while (line != null) { String[] dataLine = line.split(","); if (_UserName.equals(dataLine[0])) { DTOUser modelUser = new DTOUser(); modelUser.setUserName(dataLine[0]); modelUser.setPassword(dataLine[1]); return modelUser; } line = br.readLine(); } } catch (FileNotFoundException ex) { Logger.getLogger(clsUtilityCombobox.class.getName()).log(Level.SEVERE, null, ex); } return null; } // Kiểm tra user đăng nhập public static boolean CheckLogin(String _UserName, String _Password) throws IOException { try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("./data/user.csv"), "UTF-8"))) { String line = br.readLine(); while (line != null) { String[] dataLine = line.split(","); String sPassDecrypt = clsEncryption.encrypt(_Password, _UserName); if (_UserName.equals(dataLine[0]) && sPassDecrypt.equals(dataLine[1])) { clsParameterSys.setIsAdmin(dataLine[2].equals("1")); return true; } line = br.readLine(); } } catch (FileNotFoundException ex) { Logger.getLogger(clsUtilityCombobox.class.getName()).log(Level.SEVERE, null, ex); return false; } return false; } }
true
af45a0ce853043f6ca9230f9a976220df2c323ee
Java
maganggang/datacloud
/get-lost/src/main/java/com/fei2e/getlost/service/UpGetService.java
UTF-8
436
1.523438
2
[]
no_license
package com.fei2e.getlost.service; import com.fei2e.getlost.base.BaseService; import com.fei2e.getlost.entity.BaseResult; import com.fei2e.getlost.entity.Page; import com.fei2e.getlost.entity.UpGet; /** * @ClassName UpGetService * @DescripTion TODO * @Author dell * @Date 2020/10/19 13:46 * @Version 1.0 **/ public interface UpGetService extends BaseService<UpGet> { BaseResult<Page<UpGet>> selectPage(Page<UpGet> page); }
true
14ea30af35b94aa6bbb33bfa909445b05b557234
Java
Turnarde/leetcode
/com/drturner/jindian/JumpFrog.java
UTF-8
1,753
3.265625
3
[]
no_license
package com.drturner.jindian; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.concurrent.ConcurrentHashMap; /** * ClassName: JumpFrog * Description: TO DO * Author: Drturner * Date: 2020/7/15 * Version: 1.0 */ public class JumpFrog { //ConcurrentHashMap public static List<List<Integer>> frogJump2(int n){ if (n==0){ return new ArrayList<>(); } if (n==1){ ArrayList<Integer> integers = new ArrayList<>(); integers.add(1); ArrayList<List<Integer>> lists = new ArrayList<>(); lists.add(integers); return lists; } List<List<Integer>> t0=new ArrayList<>(); ArrayList<Integer> l1 = new ArrayList<>(); l1.add(1); t0.add(l1); List<List<Integer>> t1=new ArrayList<>(); ArrayList<Integer> l2 = new ArrayList<>(); l2.add(1); l2.add(1); t1.add(l2); l2=new ArrayList<>(); l2.add(2); t1.add(l2); // int t0=1,t1=2; while (--n>1){ List<List<Integer>> tmp=new ArrayList<>(); List<List<Integer>> t=new ArrayList<>(); for (List<Integer> l:t1){ t.add(new ArrayList<>(l)); } // t1.clear(); for (List<Integer> l:t1){ l.add(1); tmp.add(l); } for (List<Integer> l:t0){ l.add(2); tmp.add(l); } t0=t; t1=tmp; } return t1; } public static void main(String[] args) { List<List<Integer>> lists = frogJump2(6); System.out.println(lists); } }
true
0b9fe814d3101f6200f335bd871f2c9f75cb665f
Java
chenxuan-zhou/Art-Gallery
/ArtGallery-Backend/src/test/java/ca/mcgill/ecse321/artgallery/service/TestSellerService.java
UTF-8
9,963
2.140625
2
[]
no_license
package ca.mcgill.ecse321.artgallery.service; import static org.mockito.Mockito.lenient; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.invocation.InvocationOnMock; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.stubbing.Answer; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.any; import ca.mcgill.ecse321.artgallery.dao.OrderRepository; import ca.mcgill.ecse321.artgallery.dao.ProductRepository; import ca.mcgill.ecse321.artgallery.dao.SellerRepository; import ca.mcgill.ecse321.artgallery.dto.ProductDto; import ca.mcgill.ecse321.artgallery.model.Order; import ca.mcgill.ecse321.artgallery.model.Product; import ca.mcgill.ecse321.artgallery.model.Seller; import ca.mcgill.ecse321.artgallery.model.Account.AccountStatus; /** * @author chenxuan-zhou */ @ExtendWith(MockitoExtension.class) public class TestSellerService { @Mock private SellerRepository sellerRepository; @Mock private ProductRepository productRepository; @Mock private OrderRepository orderRepository; @InjectMocks private SellerService service; private static final String SELLER_NAME = "TestSeller"; private static final String SELLER_EMAIL = "TestSeller@gmail.com"; private static final String SELLER_PASSWORD = "TestSellerP"; private static final String SELLER_PASSWORD_WRONG = "TestSellerWrongP"; private static final String SELLER_PROFILE = "TestSellerProfile"; private static final long SELLER_INCOME = 1000; private static final AccountStatus SELLER_STATUS = AccountStatus.Active; private static final long PRODUCT_ID = 11; private static final long ORDER_ID = 12; private static final String SELLER_NAME2 = "TestSeller2"; private static final String SELLER_EMAIL2 = "TestSeller2@gmail.com"; private static final String SELLER_PASSWORD2 = "TestSellerP2"; private static final String SELLER_PASSWORD_WRONG2 = "TestSellerWrongP2"; private static final String SELLER_PROFILE2 = "TestSellerProfile2"; private static final long PRODUCT_ID2 = 21; private static final long ORDER_ID2 = 22; private static final String SELLER_EMAIL_BLOCKED = "TestSellerBlocked@gmail.com"; @BeforeEach public void setMockOutput() { Seller seller = new Seller(); seller.setName(SELLER_NAME); seller.setEmail(SELLER_EMAIL); seller.setPassword(SELLER_PASSWORD); seller.setProfile(SELLER_PROFILE); seller.setIncome(SELLER_INCOME); seller.setStatus(SELLER_STATUS); Product product = new Product(); product.setId(PRODUCT_ID); seller.addProduct(product); Order order = new Order(); order.setId(ORDER_ID); order.setProduct(product); seller.addOrder(order); Seller sellerBlocked = new Seller(); sellerBlocked.setEmail(SELLER_EMAIL_BLOCKED); sellerBlocked.setPassword(SELLER_PASSWORD); sellerBlocked.setStatus(AccountStatus.Blocked); // findSellerByEmail lenient().when(sellerRepository.findSellerByEmail(anyString())).thenAnswer( (InvocationOnMock invocation) -> { if(invocation.getArgument(0).equals(SELLER_EMAIL)) { return seller; } else if (invocation.getArgument(0).equals(SELLER_EMAIL_BLOCKED)) { return sellerBlocked; } else { return null; } }); // save Answer<?> returnParameterAsAnswer = (InvocationOnMock invocation) -> invocation.getArgument(0); lenient().when(sellerRepository.save(any(Seller.class))).thenAnswer(returnParameterAsAnswer); // findAll lenient().when(sellerRepository.findAll()).thenAnswer( (InvocationOnMock invocation) -> { List<Seller> sellers = new ArrayList<Seller>(); sellers.add(seller); return sellers; }); } @Test public void testCreateSeller() { Seller createdSeller = service.createSeller(SELLER_NAME2, SELLER_EMAIL2, SELLER_PASSWORD2, SELLER_PROFILE2); // check seller created assertNotNull(createdSeller); // check match right input assertEquals(SELLER_NAME2, createdSeller.getName()); assertEquals(SELLER_EMAIL2, createdSeller.getEmail()); assertEquals(SELLER_PASSWORD2, createdSeller.getPassword()); assertEquals(SELLER_PROFILE2, createdSeller.getProfile()); // check default fields initialized assertEquals(AccountStatus.New, createdSeller.getStatus()); assertEquals(0d, createdSeller.getIncome()); } @Test public void testCreateSellerExisted() { Seller createdSeller = null; String error = null; try { createdSeller = service.createSeller(SELLER_NAME, SELLER_EMAIL, SELLER_PASSWORD, SELLER_PROFILE); } catch (IllegalArgumentException e) { error = e.getMessage(); } assertNull(createdSeller); assertEquals("Account with the email already exists.",error); } @Test public void testCreateSellerNull() { Seller createdSeller = null; String error = null; // null/empty email/password mirror each other's behavior // so it suffices to test just 2 out of 4 branches // test null try { createdSeller = service.createSeller(SELLER_NAME2, null, SELLER_PASSWORD2, SELLER_PROFILE2); } catch (IllegalArgumentException e) { error = e.getMessage(); } assertNull(createdSeller); assertEquals("Email not provided.",error); // test try { createdSeller = service.createSeller(SELLER_NAME2, SELLER_EMAIL2, "", SELLER_PROFILE2); } catch (IllegalArgumentException e) { error = e.getMessage(); } assertNull(createdSeller); assertEquals("Password not provided.",error); } @Test public void testGetSeller() { Seller seller = service.getSeller(SELLER_EMAIL); assertNotNull(seller); assertEquals(SELLER_EMAIL, seller.getEmail()); assertEquals(SELLER_PASSWORD, seller.getPassword()); assertEquals(SELLER_STATUS, seller.getStatus()); } @Test public void testChangeName() { service.changeName(SELLER_EMAIL, SELLER_NAME2); Seller seller = service.getSeller(SELLER_EMAIL); assertEquals(SELLER_NAME2, seller.getName()); } @Test public void testChangeNameNull() { // not necessary to test email not exist, see testCreateSellerNull String error = null; try { service.changeName(SELLER_EMAIL, null); } catch (IllegalArgumentException e) { error = e.getMessage(); } assertEquals("Name not provided.",error); } @Test public void testAddIncome() { service.addIncome(SELLER_EMAIL, 100); double finalIncome = 100 + SELLER_INCOME; Seller seller = service.getSeller(SELLER_EMAIL); assertEquals(finalIncome,seller.getIncome()); } @Test public void testChangeProfile() { service.changeProfile(SELLER_EMAIL, SELLER_PROFILE2); Seller seller = service.getSeller(SELLER_EMAIL); assertEquals(SELLER_PROFILE2,seller.getProfile()); } @Test public void testGetAllSellers() { List<Seller> sellers = service.getAllSellers(); assertEquals(sellers.size(),1); assertEquals(sellers.get(0).getEmail(),SELLER_EMAIL); } @Test public void testLogout() { service.logout(SELLER_EMAIL); Seller seller = service.getSeller(SELLER_EMAIL); assertEquals(AccountStatus.Inactive,seller.getStatus()); } @Test public void testLogoutWrongId() { String error = null; try { service.logout("random"); }catch (IllegalArgumentException e) { error = e.getMessage(); } assertEquals("Can not find seller with this email",error); } @Test public void testLogoutWrongStatus() { String error = null; service.logout(SELLER_EMAIL); try { service.logout(SELLER_EMAIL); }catch (IllegalArgumentException e) { error = e.getMessage(); } assertEquals("Must login first", error); } @Test public void testLogin() { service.logout(SELLER_EMAIL); //make seller logout first Seller seller = service.getSeller(SELLER_EMAIL); assertEquals(AccountStatus.Inactive,seller.getStatus()); service.login(SELLER_EMAIL,SELLER_PASSWORD ); assertEquals(AccountStatus.Active,seller.getStatus()); } @Test public void testLoginWrongPassword() { String error=null; service.logout(SELLER_EMAIL); //make seller logout first Seller seller = service.getSeller(SELLER_EMAIL); assertEquals(AccountStatus.Inactive,seller.getStatus()); try { service.login(SELLER_EMAIL,"wrong" ); }catch (IllegalArgumentException e) { error =e.getMessage(); } assertEquals("Wrong password.",error); } @Test public void testLoginWrongId() { String error = null; try { service.login("random","wrong"); }catch (IllegalArgumentException e) { error = e.getMessage(); } assertEquals("Can not find seller with this email",error); } @Test public void testLoginBlockedAccount() { String error = null; try { service.login(SELLER_EMAIL_BLOCKED,SELLER_PASSWORD); }catch (IllegalArgumentException e) { error = e.getMessage(); } assertEquals("Account blocked.",error); } @Test public void testChangePassword() { service.changePassword(SELLER_EMAIL, "newPassword"); Seller seller = service.getSeller(SELLER_EMAIL); assertEquals("newPassword", seller.getPassword()); } @Test public void testChangePasswordWrongStatus() { String error = null; service.logout(SELLER_EMAIL); try { service.changePassword(SELLER_EMAIL,"ChangePassword"); }catch (IllegalArgumentException e) { error = e.getMessage(); } assertEquals("Must login first", error); } @Test public void testChangePasswordWrongId() { String error = null; try { service.changePassword("me@mail","ChangePassword"); }catch (IllegalArgumentException e) { error = e.getMessage(); } assertEquals("Can not find seller with this email", error); } }
true
8e3cd41be981a388f71fff51af184318642cd948
Java
bhegmanns/java_core
/de.hegmanns.fundamental.chain/src/main/java/hegmanns/de/de/hegmanns/fundamental/chain/resolving/CommonCmdContext.java
UTF-8
2,557
3.09375
3
[]
no_license
package hegmanns.de.de.hegmanns.fundamental.chain.resolving; import hegmanns.de.de.hegmanns.fundamental.chain.AusfuehrungsContext; import java.util.HashMap; import java.util.Map; /** * Spezieller PruefContext, der sich der ResolverRegistry bedient und so * Werte fast automatisch ermittelt kann. * * Fuer eigene Klassen muss nur noch der Typ T bestimmt werden, so dass * es fuer jedes relevante Objekt typischerweise eine eigene Unterklasse * gibt. * * @author B. Hegmanns * * @param <T> */ public class CommonCmdContext<T> extends AusfuehrungsContext<T> { private Map<Class<?>, Object> instanceCache = new HashMap<Class<?>, Object>(); private Map<Class<?>, Boolean> cached = new HashMap<Class<?>, Boolean>(); public CommonCmdContext(T instance){ super(instance); } protected <U> InstanceResolver<U, T> getInstanceResolver(Class<U> type){ return ResolverRegistry.getResolver(type, this); } protected <U> U resolve(Class<U> type){ InstanceResolver<U, T> resolver = getInstanceResolver(type); if (resolver != null) { return resolver.resolve(this); } else { throw new IllegalArgumentException("Kein Resolver registriert fuer '" + type.getName() + "'"); } } /** * * @param type * @return */ @SuppressWarnings("unchecked") protected <U> U gatherValue(Class<U> type){ Boolean gemarkt = cached.get(type); if (gemarkt != null && Boolean.FALSE.equals(gemarkt)){ return resolve(type); } else { if (gemarkt == null) { U instanz = resolve(type); cached.put(type, Boolean.TRUE); instanceCache.put(type, instanz); return instanz; }else { return (U) instanceCache.get(type); } } } public <U> U getValue(Class<U> type){ return gatherValue(type); } /** * Setzt in diesen Context den Wert fuer einen bestimmten Typ. * Dieser Wert ist dann auch gecached und wird - so lange diese Context-Instanz * existiert - mit {@link #getInstance()} besorgt. * * @param type * @param value */ public <U> void setValue(Class<U> type, U value){ cached.put(type, Boolean.TRUE); instanceCache.put(type, value); } public <U> void setUncachable(Class<U> type, Boolean uncachable){ cached.put(type, !uncachable); } public <U> void clear(Class<U> type){ cached.remove(type); instanceCache.remove(type); } public void clearCache(){ cached = new HashMap<Class<?>, Boolean>(); instanceCache = new HashMap<Class<?>, Object>(); } }
true
947dfd5eed592ff7f0a3d85db03e1f62244b5454
Java
KahoForAndroid/MyCode
/Health_V12/app/src/main/java/zj/health/health_v1/Adapter/Friend_log_Adapter.java
UTF-8
4,020
1.898438
2
[]
no_license
package zj.health.health_v1.Adapter; import android.content.Context; import android.os.Handler; import android.os.Message; import android.support.v7.widget.RecyclerView; 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.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.bumptech.glide.request.RequestOptions; import org.json.JSONException; import org.json.JSONObject; import java.util.List; import zj.health.health_v1.Base.Constant; import zj.health.health_v1.Implements.OnItemClick; import zj.health.health_v1.Model.FriendModel; import zj.health.health_v1.R; import zj.health.health_v1.Utils.GlideCircleTransform; import zj.health.health_v1.Utils.StringUtil; import zj.health.health_v1.Utils.view.PostUtils; /** * Created by Administrator on 2018/4/18. */ public class Friend_log_Adapter extends RecyclerView.Adapter<Friend_log_Adapter.ViewHolder>{ private List<FriendModel> friendModelList; private Context context; private OnItemClick onItemClick; private RequestOptions requestOptions ; public Friend_log_Adapter(Context context,List<FriendModel> friendModelList){ this.context = context; this.friendModelList = friendModelList; requestOptions = new RequestOptions() .placeholder(R.drawable.icon_head) //加载中图片 .error(R.drawable.icon_head) //加载失败图片 .fallback(R.drawable.icon_head) //url为空图片 .centerCrop() .transform(new GlideCircleTransform(context)) // 填充方式 // .override(600,600) //尺寸 // .transform(new CircleCrop()) //圆角 // .priority(Priority.HIGH) //优先级 .diskCacheStrategy(DiskCacheStrategy.NONE); //缓存策略 } public void setFriendModelList(List<FriendModel> friendModelList){ this.friendModelList = friendModelList; notifyDataSetChanged(); } public void setOnItemClick(OnItemClick onItemClick){ this.onItemClick = onItemClick; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { ViewHolder viewHolder = new ViewHolder(LayoutInflater.from(context).inflate(R.layout.friend_log_recy_item,parent,false)); return viewHolder; } @Override public void onBindViewHolder(ViewHolder holder, final int position) { Glide.with(context). load(Constant.photo_IP+ StringUtil.trimNull(friendModelList.get(position).getIconUrl())). apply(requestOptions). into(holder.head_img); holder.user_name_text.setText(friendModelList.get(position).getNickname()); holder.to_setting_img.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onItemClick.OnItemClickListener(view,position); } }); holder.check_layout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onItemClick.OnItemClickListener(v,position); } }); } @Override public int getItemCount() { return friendModelList.size(); } class ViewHolder extends RecyclerView.ViewHolder{ ImageView head_img,to_setting_img; TextView user_name_text; RelativeLayout check_layout; public ViewHolder(View itemView) { super(itemView); head_img = (ImageView)itemView.findViewById(R.id.head_img); to_setting_img = (ImageView)itemView.findViewById(R.id.to_setting_img); user_name_text = (TextView)itemView.findViewById(R.id.user_name_text); check_layout = (RelativeLayout)itemView.findViewById(R.id.check_layout); } } }
true
369989aab545291598843a08d217232105d43f8b
Java
voduytan96vn/openshift-java-app
/src/main/java/org/jboss/as/quickstarts/kitchensink/controller/MemberService.java
UTF-8
1,444
2.375
2
[]
no_license
package org.jboss.as.quickstarts.kitchensink.controller; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.ejb.Stateful; import javax.enterprise.event.Event; import javax.enterprise.inject.Model; import javax.enterprise.inject.Produces; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.inject.Named; import javax.persistence.EntityManager; import javax.persistence.Query; import org.jboss.as.quickstarts.kitchensink.model.Member; @Stateful @Model public class MemberService { @Inject private Logger log; @Inject private FacesContext facesContext; @Inject private EntityManager em; @Inject private Event<Member> memberEventSrc; private Member newMember; @Produces @Named public Member getNewMember() { return newMember; } public void register() throws Exception { log.info("Registering " + newMember.getName()); em.persist(newMember); facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Đăng ký thành công!", "Registration successful")); memberEventSrc.fire(newMember); initNewMember(); } @PostConstruct public void initNewMember() { newMember = new Member(); } public void delete(Member member) { Query query = em.createQuery("delete FROM Member m where m.id='" + member.getId() + "'"); query.executeUpdate(); memberEventSrc.fire(member); } }
true
06702de3fba966513108cec4d501608449355158
Java
https-github-com-elisee10/FoodBuddy
/app/src/main/java/com/example/foodbuddy/fragments/trendingFragment.java
UTF-8
5,120
2.3125
2
[]
no_license
package com.example.foodbuddy.fragments; import android.graphics.Color; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import okhttp3.Headers; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import com.codepath.asynchttpclient.AsyncHttpClient; import com.codepath.asynchttpclient.callback.JsonHttpResponseHandler; import com.example.foodbuddy.R; import com.example.foodbuddy.Recipe; import com.example.foodbuddy.RecipeAdapter; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import java.util.Random; public class trendingFragment extends Fragment { //API RELATED List<Recipe> recipes; //26 total cuisine to choose from String[] chooseCuisine = { "African", "American", "British", "Cajun", "Caribbean", "Chinese", "Eastern European", "European", "French", "German", "Greek", "Indian", "Irish", "Italian", "Japanese", "Jewish", "Korean", "Latin American", "Mediterranean", "Mexican", "Middle Eastern", "Nordic", "Southern", "Spanish", "Thai", "Vietnamese" }; Random random = new Random(); int randomNumber = random.nextInt(chooseCuisine.length); public static final String TAG = "trendingFragment"; //API RELATED public trendingFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_trending, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); String NOW_PLAYING_URL = "https://api.spoonacular.com/recipes/search?cuisine=" + chooseCuisine[randomNumber] + "&number=20&apiKey=7e4bf9cab7ab42b1aa7d886374bf0b51"; //API FETCH STARTS HERE //This rvMovies is from activity_main, represents the recycler view screen RecyclerView rvTrending = view.findViewById(R.id.rvTrending); //decraling movies arraylist recipes = new ArrayList<>(); //creating async object AsyncHttpClient client = new AsyncHttpClient(); // //Create a constrcutor for movieAdapter class, and send context and movies final RecipeAdapter recipeAdapter = new RecipeAdapter(getContext(), recipes); // //set the adapter in recycler view rvTrending.setAdapter(recipeAdapter); //set a layout manager on the recycler view rvTrending.setLayoutManager(new LinearLayoutManager(getContext())); //fetching the API with client.get client.get(NOW_PLAYING_URL, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Headers headers, JSON json) { //logging onSuccess to make sure onSuccess method is invoked Log.d(TAG, "onSuccess"); //Initiating a jsonObject of type json which will let us access the movie api, key and value JSONObject jsonObject = json.jsonObject; //To make sure we don't run into error, use try catch try { //result is a json array that will fetch the results from movie api JSONArray results = jsonObject.getJSONArray("results"); //logging result to make sure it parses the api // Log.i(TAG, "Results" + results.toString()); //sending to Movie class the result object recipes.addAll(Recipe.fromJsonArray(results)); //notify when its rendered recipeAdapter.notifyDataSetChanged(); //logging the size of the movies object, which is an array list Log.i(TAG, "recipe size" + recipes.size()); } catch (JSONException e){ //if error, log JSON exception Log.e(TAG, "JSON exception"); } } @Override public void onFailure(int statusCode, Headers headers, String response, Throwable throwable) { } }); } }
true
1a597e67cf8035d10a3d7d134ad0613d351e8514
Java
gy121681/Share
/business/src/main/java/com/shareshenghuo/app/shop/network/request/AddCommentRequest.java
UTF-8
365
1.679688
2
[]
no_license
package com.shareshenghuo.app.shop.network.request; /** * @author hang * 添加/回复文章评论 */ public class AddCommentRequest extends BaseRequest { public String life_circle_id; public String user_id; public String content; public String is_reply; //是否为回复内容 public String reply_id; public String reply_name; //当is_reply=1 必填 }
true
5d897a1d17554eeed7e1a57104459a9a42cff739
Java
sleeptalking/o2o
/src/main/java/com/zx/o2o/dao/ProductImgDao.java
UTF-8
590
1.976563
2
[]
no_license
package com.zx.o2o.dao; import com.zx.o2o.entity.ProductImg; import java.util.List; public interface ProductImgDao { /** * 批量添加商品图片 * @param productImgs * @return */ int batchInsertProductImg(List<ProductImg> productImgs); /** * 根据商品id 删除所有详情图片 * @param productId * @return */ int deleteProductImgByProductId(long productId); /** * 同过商品id查询该商品详情图 * @param productId * @return */ List<ProductImg> queryProductImgList(Long productId); }
true
a382298bb417d4c4737f364a37f36f0d55c77500
Java
xiaobaiami/learnfisrt
/src/main/java/algorithm/divmerge/ReverseTupleDemo.java
UTF-8
1,305
3.65625
4
[]
no_license
package algorithm.divmerge; /** * 打印逆序对 */ public class ReverseTupleDemo { public static void main(String[] args) { int[] a ={1,3,4,2,5,0}; solve(a); } public static void solve(int[] arr) { divide(arr, 0, arr.length - 1); } public static void divide(int[] arr, int l, int r) { if (l == r) return; int mid = l + (r - l) / 2; divide(arr, l, mid); divide(arr, mid + 1, r); merge(arr, l, mid, r); } public static void merge(int[] arr, int l, int mid, int r) { int[] help = new int[r - l + 1]; int index = 0; int p1 = l; int p2 = mid + 1; while (p1 <= mid && p2 <= r) { if (arr[p1] <= arr[p2]) { help[index++] = arr[p1++]; } else { for (int i = p1; i <= mid; i++) { System.out.println(String.format("(%d, %d) is reserve tuple", arr[i], arr[p2])); } help[index++] = arr[p2++]; } } while (p1 <= mid){ help[index++] = arr[p1++]; } while (p2 <= r){ help[index++] = arr[p2++]; } for (int i = l; i <= r; i++) { arr[i] = help[i - l]; } } }
true
551ae6d886e02515769b9ea1bfa9fa57930b5ba5
Java
careermasud/UVA
/Introduction/src/adhoc/Acm11547.java
UTF-8
612
2.828125
3
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package adhoc; import java.util.Scanner; /** * * @author Masudul Haque */ public class Acm11547 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for (int i = 0; i < t; i++) { int n = sc.nextInt(); long res = (n * 567 / 9 + 7492) * 235 / 47 - 498; String resStr = "" + res; int digit = resStr.charAt(resStr.length() - 2) - '0'; System.out.println(digit); } } }
true
41a1113b22084c655522f0f657e11ae62266bf43
Java
RybakovaAnna/internship-ibs
/task-third/src/main/java/com/gmail/rybachko/anna/taskthird/servlets/JsonServiceServlet.java
UTF-8
3,851
2.75
3
[]
no_license
package com.gmail.rybachko.anna.taskthird.servlets; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException; import com.gmail.rybachko.anna.taskthird.dto.FileTemplate; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Objects; @WebServlet(name = "JsonServiceServlet", value = "/jsonService") public class JsonServiceServlet extends HttpServlet { /** * http://localhost:8081/get?fileName=<fileName> */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { try { String fileName = request.getParameter("fileName"); if (Objects.isNull(fileName)) { response.sendError(400, "fileName is empty"); return; } else { fileName += ".json"; } String json = new String(Files.readAllBytes(Paths.get("classes", fileName))); try (PrintWriter writer = response.getWriter()) { writer.println(json); } } catch (Exception e) { response.sendError(500, "Unexpected error: " + e.getMessage()); } } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { try { ObjectMapper mapper = new ObjectMapper(); FileTemplate fileTemplate = mapper.readValue(request.getReader(), FileTemplate.class); if (Objects.isNull(fileTemplate.getFileName())) { response.sendError(400, "fileName is empty"); return; } mapper.writeValue(new File(Paths.get("classes", fileTemplate.getFileName() + ".json").toUri()), fileTemplate.getContent()); } catch (UnrecognizedPropertyException e) { response.sendError(400, "Invalid json format. The correct format looks like this: \n {\nfileName:\ncontent:{}\n}"); } catch (Exception e) { response.sendError(500, "Unexpected error: " + e.getMessage()); } } @Override protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws IOException { try { String fileName = request.getParameter("fileName"); if (Objects.isNull(fileName)) { response.sendError(400, "fileName is empty"); return; } else { fileName += ".json"; } Files.delete(Paths.get("classes", fileName)); } catch (Exception e) { response.sendError(500, "Unexpected error: " + e.getMessage()); } } @Override protected void doPut(HttpServletRequest request, HttpServletResponse response) throws IOException { try { ObjectMapper mapper = new ObjectMapper(); FileTemplate fileTemplate = mapper.readValue(request.getReader(), FileTemplate.class); if (Objects.isNull(fileTemplate.getFileName())) { response.sendError(400, "fileName is empty"); return; } mapper.writeValue(new File(Paths.get("classes", fileTemplate.getFileName() + ".json").toUri()), fileTemplate.getContent()); } catch (UnrecognizedPropertyException e) { response.sendError(400, "Invalid json format. The correct format looks like this: \n {\nfileName:\ncontent:{}\n}"); } catch (Exception e) { response.sendError(500, "Unexpected error: " + e.getMessage()); } } }
true
07acbf34b330868cd56ae541cafb800f6e277dbd
Java
torito/arvensis
/core/src/main/java/org/ow2/chameleon/rose/internal/RoseMachineImpl.java
UTF-8
10,821
1.679688
2
[ "Apache-2.0" ]
permissive
package org.ow2.chameleon.rose.internal; import static java.lang.Integer.MAX_VALUE; import static org.osgi.framework.Constants.SERVICE_PID; import static org.osgi.framework.Constants.SERVICE_RANKING; import static org.osgi.framework.Constants.SERVICE_VENDOR; import static org.osgi.service.remoteserviceadmin.RemoteConstants.ENDPOINT_FRAMEWORK_UUID; import static org.ow2.chameleon.rose.RoSeConstants.ENDPOINT_CONFIG; import static org.ow2.chameleon.rose.RoSeConstants.RoSe_MACHINE_COMPONENT_NAME; import static org.ow2.chameleon.rose.util.RoseTools.getAllExporter; import static org.ow2.chameleon.rose.util.RoseTools.getAllImporter; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import org.apache.felix.ipojo.annotations.Component; import org.apache.felix.ipojo.annotations.Invalidate; import org.apache.felix.ipojo.annotations.Property; import org.apache.felix.ipojo.annotations.Requires; import org.apache.felix.ipojo.annotations.Validate; import org.osgi.framework.BundleContext; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.osgi.framework.ServiceRegistration; import org.osgi.service.log.LogService; import org.osgi.service.remoteserviceadmin.EndpointDescription; import org.osgi.service.remoteserviceadmin.EndpointListener; import org.osgi.service.remoteserviceadmin.ExportReference; import org.osgi.service.remoteserviceadmin.ExportRegistration; import org.osgi.service.remoteserviceadmin.ImportReference; import org.osgi.service.remoteserviceadmin.ImportRegistration; import org.osgi.service.remoteserviceadmin.RemoteServiceAdmin; import org.ow2.chameleon.rose.ExporterService; import org.ow2.chameleon.rose.ImporterService; import org.ow2.chameleon.rose.RoseMachine; import org.ow2.chameleon.rose.util.DefaultLogService; import org.ow2.chameleon.rose.util.RoseTools; @Component(name=RoSe_MACHINE_COMPONENT_NAME, immediate=true) public class RoseMachineImpl implements RoseMachine,RemoteServiceAdmin{ /** * Remote EndpointDescription dynamic registry. */ protected final ImportRegistryImpl importReg; /** * Local EndpointDescriptoin dynamic registry */ protected final ExportRegistryImpl exportReg; /** * Track the {@link EndpointListener} and notified them about the * {@link EndpointDescription} availabilities. */ private final EndpointListenerTracker tracklistener; /** * ServiceRegistration of the services registered by this component. * {@link RoseMachine} and {@link RemoteServiceAdmin} */ private final Set<ServiceRegistration> registrations; /** * The machine properties. */ private final Hashtable<String, Object> properties; private final BundleContext context; @Requires(optional=true,defaultimplementation=DefaultLogService.class) private LogService logger; public RoseMachineImpl(BundleContext pContext) { properties = new Hashtable<String, Object>(5); registrations = new HashSet<ServiceRegistration>(2); context = pContext; //Create the import registry importReg = new ImportRegistryImpl(); //Create the export registry exportReg = new ExportRegistryImpl(context); //Create the EndpointListener Tracker tracklistener = new EndpointListenerTracker(this); } @Validate private void start(){ //Initialize the machine properties. initProperties(context); //Register the import service and export service registries. //registrations.put(exportReg, context.registerService(new String[]{ExportRegistryListening.class.getName(),ExportRegistryProvisioning.class.getName()},exportReg,properties)); //registrations.put(importReg, context.registerService(new String[]{ImportRegistryListening.class.getName(),ImportRegistryProvisioning.class.getName()},importReg,properties)); //Register the RoseMachine Service registrations.add(context.registerService(RoseMachine.class.getName(), this, properties)); //Register the RemoteServiceAdmin Service registrations.add(context.registerService(RemoteServiceAdmin.class.getName(), this, properties)); //Open the EndpointListener tracker tracklistener.open(); log(LogService.LOG_INFO,"The RoseMachine "+properties.get(RoSe_MACHINE_ID)+" has successfully started"); } @Invalidate private void stop(){ //Unregister the services for (ServiceRegistration reg : registrations) { reg.unregister(); } //Clear the registrations set registrations.clear(); //Close the EndpointListener tracker tracklistener.close(); //Stop both rose local registry importReg.stop(); exportReg.stop(); log(LogService.LOG_INFO,"The RoseMachine "+properties.get(RoSe_MACHINE_ID)+" has been stoped"); } /*-------------------------------* * Registry methods * *-------------------------------*/ public void putRemote(Object key, EndpointDescription description) { importReg.put(key, description); } public EndpointDescription removeRemote(Object key) { return importReg.remove(key); } public boolean containsRemote(EndpointDescription desc) { return importReg.contains(desc); } public void putLocal(Object key, ExportReference xref) { exportReg.put(key, xref); } public ExportReference removeLocal(Object key) { return exportReg.remove(key); } public boolean containsLocal(ExportReference xref) { return exportReg.contains(xref); } public void addEndpointListener(EndpointListener listener, EndpointListerInterrest interrest, String filter) throws InvalidSyntaxException { switch (interrest) { case ALL: exportReg.addEndpointListener(listener, filter); importReg.addEndpointListener(listener, filter); break; case LOCAL: exportReg.addEndpointListener(listener, filter); break; case REMOTE: importReg.addEndpointListener(listener, filter); } } public void removeEndpointListener(EndpointListener listener, EndpointListerInterrest interrest) { switch (interrest) { case ALL: exportReg.removeEndpointListener(listener); importReg.removeEndpointListener(listener); break; case LOCAL: exportReg.removeEndpointListener(listener); break; case REMOTE: importReg.removeEndpointListener(listener); } } /*------------------------------* * RemoteServiceAdmin methods * *------------------------------*/ public Collection<ExportRegistration> exportService(ServiceReference reference, Map<String, Object> properties) { Collection<ExporterService> exporters = RoseTools.getAllExporter(context); Collection<ExportRegistration> registrations = new HashSet<ExportRegistration>(); for (ExporterService exporter : exporters) { ExportRegistration reg = exporter.exportService(reference, properties); if (reg!=null){ registrations.add(reg); } } return registrations; } public ImportRegistration importService(EndpointDescription endpoint) { Iterator<ImporterService> iterator; //Construct a Filter which track only the Importer which are compliant with the EndpointDescription. StringBuilder filterb = new StringBuilder("(&"); for (String conf : endpoint.getConfigurationTypes()) { filterb.append("("); filterb.append(ENDPOINT_CONFIG); filterb.append("="); filterb.append(conf); filterb.append(")"); } filterb.append(")"); try { iterator = getAllImporter(context, filterb.toString()).iterator(); } catch (InvalidSyntaxException e) { assert false; //What Would Dr. Gordon Freeman Do ? return null; } ImportRegistration registration = null; //First successful import is the winner :P while (iterator.hasNext() && registration==null) { registration = iterator.next().importService(endpoint,null); } return registration; } public Collection<ExportReference> getExportedServices() { Collection<ExporterService> exporters = getAllExporter(context); Collection<ExportReference> refs = new HashSet<ExportReference>(); for (ExporterService exporter : exporters) { refs.addAll(exporter.getAllExportReference()); } return refs; } public Collection<ImportReference> getImportedEndpoints() { Collection<ImportReference> refs = new HashSet<ImportReference>(); List<ImporterService> importers = getAllImporter(context); for (ImporterService importer : importers) { refs.addAll(importer.getAllImportReference()); } return refs; } /*------------------------------* * The RoSe Machine Properties * *------------------------------*/ /** * Default machine IP. */ //private static final String DEFAULT_IP = "127.0.0.1"; /** * Default machine Host. */ private static final String DEFAULT_HOST = "localhost"; @Property(name=RoSe_MACHINE_HOST) private String myhost; @Property(name=RoSe_MACHINE_ID) private String myid; /** * Initialize the Machine properties thanks to the framework properties. */ private final void initProperties(BundleContext context){ // Initialize machineID if (myid==null){ if (context.getProperty(RoSe_MACHINE_ID) != null) { myid = context.getProperty(RoSe_MACHINE_ID); } else if (context.getProperty(ENDPOINT_FRAMEWORK_UUID) != null) { myid = context.getProperty(ENDPOINT_FRAMEWORK_UUID); } else { myid = UUID.randomUUID().toString(); } } // Initialize machineHost if (myhost==null){ if (context.getProperty(RoSe_MACHINE_HOST) != null) { myhost = context.getProperty(RoSe_MACHINE_HOST); } else { myhost = DEFAULT_HOST; } } properties.put(RoSe_MACHINE_ID, myid); properties.put(SERVICE_PID, myhost+"-"+myid); properties.put(SERVICE_VENDOR, "org.ow2.chameleon"); properties.put(SERVICE_RANKING, MAX_VALUE); properties.put(RoSe_MACHINE_HOST, myhost); } /** * @return This rose machine id. */ public final String getId() { return (String) properties.get(RoSe_MACHINE_ID); } /** * @return This rose machine host. */ public final String getHost() { return (String) properties.get(RoSe_MACHINE_HOST); } /** * @return This RoSe machine properties. */ public final Map<String, Object> getProperties(){ return Collections.unmodifiableMap(properties); } /*---------------------------------------* * RoseMachine Logger * *---------------------------------------*/ protected void log(int level, String message){ logger.log(level, message); } protected void log(int level, String message,Throwable exception){ logger.log(level, message,exception); } /*---------------------------------------* * RoseMachine BundleContext * *---------------------------------------*/ protected BundleContext getContext(){ return context; } }
true
ee0c2652471588b10f7cded3a5074b11b8a9d3b4
Java
pylSER/HostelWorld
/src/hostel/daoImpl/CountDaoImpl.java
UTF-8
1,581
2.359375
2
[]
no_license
package hostel.daoImpl; import java.util.List; import javax.annotation.Resource; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.springframework.stereotype.Repository; import hostel.daoService.CountDao; import hostel.model.CountEntity; @Repository public class CountDaoImpl implements CountDao{ @Resource private HIbernateUtil hbutil; @Override public double getCountedMoney(int innid) { SessionFactory factory= hbutil.getSessionFactory(); Session session=factory.openSession(); Transaction transaction= session.beginTransaction(); Double sum=(Double) session.createQuery("select sum(money) from CountEntity where innid=?").setParameter(0, innid).uniqueResult(); transaction.commit(); session.close(); if(sum==null){ return 0; } return sum; } @Override public boolean saveCountEntity(CountEntity ce) { SessionFactory factory= hbutil.getSessionFactory(); Session session=factory.openSession(); Transaction transaction= session.beginTransaction(); session.save(ce); transaction.commit(); session.close(); return true; } @Override public List<CountEntity> getCountEntityById(int innid) { SessionFactory factory= hbutil.getSessionFactory(); Session session=factory.openSession(); Transaction transaction= session.beginTransaction(); List<CountEntity> list=session.createQuery("from CountEntity where innid=?").setParameter(0, innid).list(); transaction.commit(); session.close(); return list; } }
true
b9777ee09796e6ae4207c7a7ca62c9feb4db4ed7
Java
progserega/InspectionSheet
/app/src/main/java/ru/drsk/progserega/inspectionsheet/activities/InspectTower.java
UTF-8
9,344
1.90625
2
[]
no_license
package ru.drsk.progserega.inspectionsheet.activities; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ImageButton; import android.widget.Spinner; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import ru.drsk.progserega.inspectionsheet.InspectionSheetApplication; import ru.drsk.progserega.inspectionsheet.R; import ru.drsk.progserega.inspectionsheet.utility.ButtonUtils; import ru.drsk.progserega.inspectionsheet.entities.Line; import ru.drsk.progserega.inspectionsheet.entities.LineTower; import ru.drsk.progserega.inspectionsheet.entities.catalogs.InspectionType; import ru.drsk.progserega.inspectionsheet.entities.catalogs.Material; import ru.drsk.progserega.inspectionsheet.entities.catalogs.TowerType; //import ru.drsk.progserega.inspectionsheet.services.TowersService; import ru.drsk.progserega.inspectionsheet.storages.ICatalogStorage; import ru.drsk.progserega.inspectionsheet.ui.activities.TowerDeffectsActivity; @Deprecated public class InspectTower extends AppCompatActivity { public final static String LINE_ID = "line_id"; public final static String LINE_NAME = "line_name"; private InspectionSheetApplication application; // private TowersService towersService; private ICatalogStorage catalogStorage; // private long lineId; private Spinner towersSpinner; private ArrayAdapter towersAdapter; private Spinner materialsSpinner; private ArrayAdapter materialsAdapter; private Spinner towerTypesSpinner; private ArrayAdapter towerTypesAdapter; private Spinner inspectionTypesSpinner; private ArrayAdapter inspectionTypesAdapter; private List<LineTower> lineTowers; private LineTower selectedLineTower; List<Material> materials; List<TowerType> towerTypes; List<InspectionType> inspectionTypes; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_inspect_tower); ButtonUtils.initSaveBtnImg((ImageButton) findViewById(R.id.inpsect_tower_save_btn)); this.application = (InspectionSheetApplication) this.getApplication(); // towersService = application.getTowersService(); catalogStorage = application.getCatalogStorage(); // Intent intent = getIntent(); // lineId = intent.getLongExtra(LINE_ID, 0); // String lineName = intent.getStringExtra(LINE_NAME); Line line = application.getState().getCurrentLineInspection().getLine(); TextView lineNameText = (TextView) findViewById(R.id.inspection_tower_name); lineNameText.setText(line.getName()); towersAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, new ArrayList<String>()); towersAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line); towersSpinner = (Spinner) findViewById(R.id.towers_spinner); towersSpinner.setAdapter(towersAdapter); towersSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) { onSelectTower(position); } @Override public void onNothingSelected(AdapterView<?> parentView) { // your code here } }); materialsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, new ArrayList<String>()); materialsAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line); materialsSpinner = (Spinner) findViewById(R.id.materials_spinner); materialsSpinner.setAdapter(materialsAdapter); materialsSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) { onSelectMaterial(position); } @Override public void onNothingSelected(AdapterView<?> parentView) { // your code here } }); towerTypesSpinner = (Spinner) findViewById(R.id.tower_type_spinner); towerTypesAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, new ArrayList<String>()); towerTypesAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line); towerTypesSpinner.setAdapter(towerTypesAdapter); towerTypesSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) { onSelectTowerType(position); } @Override public void onNothingSelected(AdapterView<?> parentView) { // your code here } }); inspectionTypesSpinner = (Spinner) findViewById(R.id.inspection_type_spinner); inspectionTypesAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, new ArrayList<String>()); inspectionTypesAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line); inspectionTypesSpinner.setAdapter(inspectionTypesAdapter); inspectionTypesSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) { onSelectInspectionType(position); } @Override public void onNothingSelected(AdapterView<?> parentView) { // your code here } }); //lineTowers = towersService.getTowersByLine(lineId); // lineTowers = line.getTowers(); // setTowersSpinnerData(lineTowers); materials = catalogStorage.getMaterials(); setMaterialsSpinnerData(materials); towerTypes = catalogStorage.getTowerTypes(); setTowerTypesSpinnerData(towerTypes); inspectionTypes = catalogStorage.getInspectionTypes(); setInspectionTypesSpinnerData(inspectionTypes); } private void setTowersSpinnerData(List<LineTower> lineTowers){ List<String> spinnerItems = new ArrayList<>(); spinnerItems.add(""); for (LineTower lineTower : lineTowers) { spinnerItems.add(lineTower.getNumber()); } towersAdapter.clear(); towersAdapter.addAll(spinnerItems); towersAdapter.notifyDataSetChanged(); } private void setMaterialsSpinnerData(List<Material> materials){ List<String> spinerItems = new ArrayList<>(); spinerItems.add("не задан"); for(Material mat: materials){ spinerItems.add(mat.getName()); } materialsAdapter.clear(); materialsAdapter.addAll(spinerItems); materialsAdapter.notifyDataSetChanged(); } private void setTowerTypesSpinnerData(List<TowerType> types){ List<String> spinerItems = new ArrayList<>(); spinerItems.add("не задан"); for(TowerType type: types){ spinerItems.add(type.getType()); } towerTypesAdapter.clear(); towerTypesAdapter.addAll(spinerItems); towerTypesAdapter.notifyDataSetChanged(); } private void setInspectionTypesSpinnerData(List<InspectionType> types){ List<String> spinerItems = new ArrayList<>(); spinerItems.add("не задан"); for(InspectionType type: types){ spinerItems.add(type.getInspection()); } inspectionTypesAdapter.clear(); inspectionTypesAdapter.addAll(spinerItems); inspectionTypesAdapter.notifyDataSetChanged(); } private void onSelectTower(int position) { if(position == 0){ selectedLineTower = null; return; } selectedLineTower = lineTowers.get(position - 1); // application.getCurrentLineInspection().setLineTower(selectedLineTower); } private void onSelectMaterial(int position) { if(position == 0 || selectedLineTower == null){ materialsSpinner.setSelection(0); return; } selectedLineTower.getTower().setMaterial(materials.get(position - 1)); } private void onSelectTowerType(int position) { if(position == 0 || selectedLineTower == null){ return; } selectedLineTower.getTower().setTowerType(towerTypes.get(position - 1)); } private void onSelectInspectionType(int position) { if(position == 0){ return; } application.getState().getCurrentLineInspection().setInspectionType(inspectionTypes.get(position - 1)); } public void onNextBtnPress(View view){ Intent intent = new Intent(this, TowerDeffectsActivity.class); startActivity(intent); } public void onSaveBtnPress(View view){ } }
true
b224d01c804a217739caab19c6369046be53fe6b
Java
bhuvaneshwaran8996/GlobalWeatherAppForAndroid
/app/src/main/java/com/example/globalweatherapp/network/AuthApi.java
UTF-8
747
1.921875
2
[]
no_license
package com.example.globalweatherapp.network; import com.example.globalweatherapp.model.CheckDevice; import com.example.globalweatherapp.model.Device; import com.example.globalweatherapp.model.DeviceDetails; import com.google.gson.JsonObject; import io.reactivex.Flowable; import io.reactivex.Observable; import okhttp3.ResponseBody; import retrofit2.Response; import retrofit2.http.Body; import retrofit2.http.POST; public interface AuthApi { @POST("checkdevice") Flowable<String> checkDevice(@Body CheckDevice checkDevice); @POST("login") Flowable<Response<ResponseBody>> login(@Body CheckDevice deviceDetails); @POST("savedevice") Flowable<Response<ResponseBody>> saveDevice(@Body CheckDevice checkDevice); }
true
79ff9bd4c7ce86fc6eb3498dcc2230fc3ed3da6c
Java
hammondjm/ksa
/ksa-core/src/main/java/com/ksa/dao/finance/ChargeDao.java
UTF-8
772
1.960938
2
[ "Apache-2.0" ]
permissive
package com.ksa.dao.finance; import java.util.List; import com.ksa.model.finance.Charge; /** * 费用数据访问接口。 * * @author 麻文强 * * @since v0.0.1 */ public interface ChargeDao { int insertCharge( Charge charge ) throws RuntimeException; int updateCharge( Charge charge ) throws RuntimeException; int deleteCharge( Charge charge ) throws RuntimeException; Charge selectChargeById( String id ) throws RuntimeException; List<Charge> selectChargeByBookingNoteId( String bnId ) throws RuntimeException; List<Charge> selectChargeByBookingNoteId( String bnId, int direction, int nature ) throws RuntimeException; List<Charge> selectChargeByAccountId( String accountId ) throws RuntimeException; }
true
9d4def12bb82b7879122e83143733c05ac2024e4
Java
Ikhiloya/Maths
/app/src/main/java/com/rudigo/android/maths/IlcLesson3iFragment.java
UTF-8
9,681
2.375
2
[]
no_license
package com.rudigo.android.maths; import android.content.Intent; import android.os.Bundle; import android.speech.tts.TextToSpeech; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.GridView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.Locale; public class IlcLesson3iFragment extends Fragment { private TextToSpeech ttsObject; private int result; private String text; private Button testButton; private Button repeatButton; private Intent intent; private ArrayList<Integer> numbers; private ArrayList<String> numberText; private ArrayAdapter<Integer> numberAdapter; private GridView gridView; //These variables are used to display the fragments Fragment frag; FragmentTransaction fragTransaction; Bundle bundle; public IlcLesson3iFragment() { } //This method is used to inflate the fragment layout when it's called @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstance) { View rootView = inflater.inflate(R.layout.blc_test_fragment, container, false); intent = new Intent(getActivity(), IlcLesson3iFragment.class); TextView tv = rootView.findViewById(R.id.foundationFrag_textView); Button repeatButton = rootView.findViewById(R.id.repeatLesson1Btn); Button continueButton = rootView.findViewById(R.id.blcTestContinueBtn); repeatButton.setVisibility(View.GONE); ttsObject = new TextToSpeech(getContext(), new TextToSpeech.OnInitListener() { @Override public void onInit(int status) { if (status == TextToSpeech.SUCCESS) { //set Language result = ttsObject.setLanguage(Locale.UK); } else { Toast.makeText(getContext(), "Feature not supported in your device", Toast.LENGTH_SHORT).show(); } } }); tv.setText("Activity "); numbers = new ArrayList<>(); for (int i = 501; i <= 600; ++i) { numbers.add(i); } numberText = new ArrayList<>(); numberText.add("five hundred and one"); numberText.add("five hundred and two"); numberText.add("five hundred and three"); numberText.add("five hundred and four"); numberText.add("five hundred and five"); numberText.add("five hundred and six"); numberText.add("five hundred and seven"); numberText.add("five hundred and eight"); numberText.add("five hundred and nine"); numberText.add("five hundred and ten"); numberText.add("five hundred and eleven"); numberText.add("five hundred and twelve"); numberText.add("five hundred and thirteen"); numberText.add("five hundred and fourteen"); numberText.add("five hundred and fifteen"); numberText.add("five hundred and sixteen"); numberText.add("five hundred and seventeen"); numberText.add("five hundred and eighteen"); numberText.add("five hundred and nineteen"); numberText.add("five hundred and twenty"); numberText.add("five hundred and twenty-one"); numberText.add("five hundred and twenty-two"); numberText.add("five hundred and twenty-three"); numberText.add("five hundred and twenty-four"); numberText.add("five hundred and twenty-five"); numberText.add("five hundred and twenty-six"); numberText.add("five hundred and twenty-seven"); numberText.add("five hundred and twenty-eight"); numberText.add("five hundred and twenty-nine"); numberText.add("five hundred and thirty"); numberText.add("five hundred and thirty-one"); numberText.add("five hundred and thirty-two"); numberText.add("five hundred and thirty-three"); numberText.add("five hundred and thirty-four"); numberText.add("five hundred and thirty-five"); numberText.add("five hundred and thirty-six"); numberText.add("five hundred and thirty-seven"); numberText.add("five hundred and thirty-eight"); numberText.add("five hundred and thirty-nine"); numberText.add("five hundred and forty"); numberText.add("five hundred and forty-one"); numberText.add("five hundred and forty-two"); numberText.add("five hundred and forty-three"); numberText.add("five hundred and forty-four"); numberText.add("five hundred and forty-five"); numberText.add("five hundred and forty-six"); numberText.add("five hundred and forty-seven"); numberText.add("five hundred and forty-eight"); numberText.add("five hundred and forty-nine"); numberText.add("five hundred and fifty"); numberText.add("five hundred and fifty-one"); numberText.add("five hundred and fifty-two"); numberText.add("five hundred and fifty-three"); numberText.add("five hundred and fifty-four"); numberText.add("five hundred and fifty-five"); numberText.add("five hundred and fifty-six"); numberText.add("five hundred and fifty-seven"); numberText.add("five hundred and fifty-eight"); numberText.add("five hundred and fifty-nine"); numberText.add("five hundred and sixty"); numberText.add("five hundred and sixty-one"); numberText.add("five hundred and sixty-two"); numberText.add("five hundred and sixty-three"); numberText.add("five hundred and sixty-four"); numberText.add("five hundred and sixty-five"); numberText.add("five hundred and sixty-six"); numberText.add("five hundred and sixty-seven"); numberText.add("five hundred and sixty-eight"); numberText.add("five hundred and sixty-nine"); numberText.add("five hundred and seventy"); numberText.add("five hundred and seventy-one"); numberText.add("five hundred and seventy-two"); numberText.add("five hundred and seventy-three"); numberText.add("five hundred and seventy-four"); numberText.add("five hundred and seventy-five"); numberText.add("five hundred and seventy-six"); numberText.add("five hundred and seventy-seven"); numberText.add("five hundred and seventy-eight"); numberText.add("five hundred and seventy-nine"); numberText.add("five hundred and eighty"); numberText.add("five hundred and eighty-one"); numberText.add("five hundred and eighty-two"); numberText.add("five hundred and eighty-three"); numberText.add("five hundred and eighty-four"); numberText.add("five hundred and eighty-five"); numberText.add("five hundred and eighty-six"); numberText.add("five hundred and eighty-seven"); numberText.add("five hundred and eighty-eight"); numberText.add("five hundred and eighty-nine"); numberText.add("five hundred and ninety"); numberText.add("five hundred and ninety-one"); numberText.add("five hundred and ninety-two"); numberText.add("five hundred and ninety-three"); numberText.add("five hundred and ninety-four"); numberText.add("five hundred and ninety-five"); numberText.add("five hundred and ninety-six"); numberText.add("five hundred and ninety-seven"); numberText.add("five hundred and ninety-eight"); numberText.add("five hundred and ninety-nine"); numberText.add("six hundred"); numberAdapter = new ArrayAdapter<Integer>(getContext(), android.R.layout.simple_list_item_1, numbers); gridView = rootView.findViewById(R.id.test_gridView); gridView.setAdapter(numberAdapter); gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { numbers.get(position); text = numberText.get(position); playSound(text); } }); continueButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { fragTransaction = getFragmentManager().beginTransaction(); fragTransaction.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left, R.anim.slide_in_left, R.anim.slide_out_right); frag = new IlcLesson3jFragment(); fragTransaction.replace(R.id.main_container, frag); fragTransaction.addToBackStack(null); fragTransaction.commit(); } }); return rootView; } @Override public void onDestroyView() { super.onDestroyView(); if (ttsObject != null) { ttsObject.stop(); ttsObject.shutdown(); } } private void playSound(String tt) { //play text..text to speech if (result == TextToSpeech.LANG_NOT_SUPPORTED || result == TextToSpeech.LANG_MISSING_DATA) { Toast.makeText(getActivity(), "Feature not supported in your device", Toast.LENGTH_SHORT).show(); } else { ttsObject.speak(tt, TextToSpeech.QUEUE_FLUSH, null); } } }
true
7f603dc51a29a807190b95d7cfc183b68e125d40
Java
Garo-Kaikchiyan/TalentHub
/src/main/java/com/example/controller/ForumController.java
UTF-8
8,510
2.28125
2
[]
no_license
package com.example.controller; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import model.Answer; import model.Question; import model.User; import model.dao.IAnswerDAO; import model.dao.IQuestionDAO; import model.dao.IQuestionDAO.DataSource; import model.dao.IUserDAO; @Controller public class ForumController { private static ArrayList<Question> allJavaQuestions = new ArrayList<>(); private static ArrayList<Question> allPhpQuestions = new ArrayList<>(); private static ArrayList<Question> allAndroidQuestions = new ArrayList<>(); private static ArrayList<Question> allJSQuestions = new ArrayList<>(); private static ArrayList<User> allUsers = new ArrayList(); @RequestMapping(value="/forum", method = RequestMethod.GET) public String goToForums() { return "forum_types"; } @RequestMapping(value="/javaForum", method = RequestMethod.GET) public String goToJavaForums(HttpServletRequest req, Model model) { if(allJavaQuestions.isEmpty()) try { allJavaQuestions.addAll(IQuestionDAO.getDAO(DataSource.DB).getAllQuestions("javaForum")); } catch (SQLException e) { e.printStackTrace(); System.out.println("Problem retrieving java forum questions"); return "errorPage"; } model.addAttribute("endIndex", allJavaQuestions.size()); req.getSession().setAttribute("questions", allJavaQuestions); req.getSession().setAttribute("forum", "javaForum"); return "forum"; } @RequestMapping(value="/jsForum", method = RequestMethod.GET) public String goToJSForums(HttpServletRequest req, Model model) { if(allJSQuestions.isEmpty()) try { allJSQuestions = IQuestionDAO.getDAO(DataSource.DB).getAllQuestions("jsForum"); } catch (SQLException e) { e.printStackTrace(); System.out.println("Problem retrieving js forum questions"); return "errorPage"; } model.addAttribute("endIndex", allJSQuestions.size()); req.getSession().setAttribute("questions", allJSQuestions); req.getSession().setAttribute("forum", "jsForum"); return "forum"; } @RequestMapping(value="/androidForum", method = RequestMethod.GET) public String goToAndroidForums(HttpServletRequest req, Model model) { if(allAndroidQuestions.isEmpty()) try { allAndroidQuestions = IQuestionDAO.getDAO(DataSource.DB).getAllQuestions("androidForum"); Collections.sort(allAndroidQuestions, new Comparator<Question>() { @Override public int compare(Question o1, Question o2) { if(o1.getDate_created().compareTo(o2.getDate_created()) > 0) { return 1; } else { return -1; } }});; } catch (SQLException e) { e.printStackTrace(); System.out.println("Problem retrieving android forum questions"); return "errorPage"; } model.addAttribute("endIndex", allAndroidQuestions.size()); req.getSession().setAttribute("questions", allAndroidQuestions); req.getSession().setAttribute("forum", "androidForum"); return "forum"; } @RequestMapping(value="/phpForum", method = RequestMethod.GET) public String goToPhpForums(HttpServletRequest req, Model model) { if(allPhpQuestions.isEmpty()) try { allPhpQuestions = IQuestionDAO.getDAO(DataSource.DB).getAllQuestions("phpForum"); } catch (SQLException e) { e.printStackTrace(); System.out.println("Problem retrieving php forum questions"); return "errorPage"; } model.addAttribute("endIndex", allPhpQuestions.size()); req.getSession().setAttribute("questions", allPhpQuestions); req.getSession().setAttribute("forum", "phpForum"); return "forum"; } @RequestMapping(value="/createQuestion", method = RequestMethod.POST) public String createQuestion(HttpServletRequest req, Model mod){ if(req.getSession().getAttribute("loggedUser") == null) return "index"; User autor = (User) req.getSession().getAttribute("loggedUser"); Question question = new Question(req.getParameter("subject"), autor.getEmail(), req.getParameter("text"), autor.getFirstName(), autor.getLastName()); String forum = req.getSession().getAttribute("forum").toString(); try { IQuestionDAO.getDAO(DataSource.DB).addQuestion(autor, question, forum); autor.setAllForumEntrys(autor.getAllForumEntrys()+1); question.setOwner(getUserByEmail(question.getUser_email())); addQuestionToList(forum, question); } catch (SQLException e) { e.printStackTrace(); System.out.println("Error adding question in " + forum); return "errorPage"; } mod.addAttribute("answers", question.getAnswers()); mod.addAttribute("question", question); return "forum_look"; } @RequestMapping(value="/thread", method = RequestMethod.GET) public String viewQuestion(HttpServletRequest req, Model mod){ if(req.getSession().getAttribute("loggedUser") == null) return "index"; Question question = null; switch(req.getSession().getAttribute("forum").toString()){ case "javaForum": question = allJavaQuestions.get(Integer.parseInt(req.getParameter("questionIndex"))); mod.addAttribute("forumName", "Java Forum"); break; case "androidForum": question = allAndroidQuestions.get(Integer.parseInt(req.getParameter("questionIndex"))); mod.addAttribute("forumName", "Android Forum"); break; case "phpForum": question = allPhpQuestions.get(Integer.parseInt(req.getParameter("questionIndex"))); mod.addAttribute("forumName", "PHP Forum"); break; case "jsForum": question = allJSQuestions.get(Integer.parseInt(req.getParameter("questionIndex"))); mod.addAttribute("forumName", "JavaScript Forum"); break; } try { question.setAnswers(IAnswerDAO.getDAO(model.dao.IAnswerDAO.DataSource.DB).getAllAnswers(question)); } catch (SQLException e) { System.out.println("Problem getting answers"); e.printStackTrace(); return "errorPage"; } question.setOwner(getUserByEmail(question.getUser_email())); mod.addAttribute("answers", question.getAnswers()); mod.addAttribute("question", question); return "forum_look"; } @RequestMapping(value="/createTopic", method = RequestMethod.GET) public String createTopic(Model model, HttpServletRequest req) { if(req.getSession().getAttribute("loggedUser") == null) return "index"; return "create_topic"; } @RequestMapping(value="/addAnswer", method = RequestMethod.POST) public String addAnswer(HttpServletRequest req, Model mod){ if(req.getSession().getAttribute("loggedUser") == null) return "index"; User user = (User) req.getSession().getAttribute("loggedUser"); Question question = (Question) req.getSession().getAttribute("question"); Answer answer = new Answer(question.getQuestion_title(), user.getEmail(), req.getParameter("text")); try { IAnswerDAO.getDAO(model.dao.IAnswerDAO.DataSource.DB).addAnswer(answer, question, user); user.setAllForumEntrys(user.getAllForumEntrys()+1); answer.setOwner(getUserByEmail(answer.getUser_email())); question.addAnswer(answer); } catch (SQLException e) { e.printStackTrace(); System.out.println("Error adding answer"); return "errorPage"; } mod.addAttribute("question", question); mod.addAttribute("answers", question.getAnswers()); return "forum_look"; } private void addQuestionToList(String type, Question q){ switch(type){ case "javaForum": allJavaQuestions.add(q); break; case "androidForum": allAndroidQuestions.add(q); break; case "phpForum": allPhpQuestions.add(q); break; case "jsForum": allJSQuestions.add(q); break; } } public static User getUserByEmail(String email){ if(allUsers.isEmpty()){ try { allUsers.addAll(IUserDAO.getDAO(model.dao.IUserDAO.DataSource.DB).getAllUsers()); } catch (SQLException e) { e.printStackTrace(); System.out.println("Error with getAllUsers()"); return null; } } for(int i = 0; i < allUsers.size(); i++) if(allUsers.get(i).getEmail().equals(email)) return allUsers.get(i); return null; } public static void reloadUsers(){ try { allUsers.clear(); allUsers.addAll(IUserDAO.getDAO(model.dao.IUserDAO.DataSource.DB).getAllUsers()); } catch (SQLException e) { e.printStackTrace(); System.out.println("Error with setUsers()"); } } }
true
dc758051ce8a2a2673729f00f4015c9cfcdf3565
Java
ashleylmy/Music
/src/reaction/Shape.java
UTF-8
7,901
2.4375
2
[]
no_license
package reaction; import graphicsLib.G; import music.I; import music.UC; import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.io.*; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import static sandbox.PaintInk.pList; public class Shape implements Serializable { public Prototype.List prototypes = new Prototype.List(); public String name; public static String fileName="ShapeDB.DAT"; public static HashMap<String, Shape> DB = loadShapeDB(); public static Shape DOT= DB.get("DOT"); public static Collection<Shape> LIST= DB.values(); public Shape(String name) { this.name = name; } public static void saveShapeDB(){ try{ ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(fileName)); oos.writeObject(DB); System.out.println("Saved"+fileName); oos.close(); }catch (Exception e){ System.out.println("Save DB Fail"); System.out.println(e); } } private static HashMap<String, Shape> loadShapeDB() { HashMap<String, Shape> res = new HashMap<>(); res.put("DOT", new Shape("DOT")); try{ System.out.println("Attempt DB Load..."); ObjectInputStream ois=new ObjectInputStream(new FileInputStream(fileName)); res=(HashMap<String, Shape>)ois.readObject(); System.out.println("Successful Load "+ res.keySet()); ois.close(); }catch (Exception e){ System.out.println("Load DB failed"); System.out.println(e); } return res; } public static Shape recognize(Ink ink){ if(ink.vs.size.x<UC.DOT_THRESHOLD && ink.vs.size.y<UC.DOT_THRESHOLD) return DOT; Shape bestMatch=null; int bestSoFar=UC.NO_MATCH_DIST; for(Shape s:LIST){ int d=s.prototypes.bestDist(ink.norm); if(d<bestSoFar){ bestSoFar=d; bestMatch=s;} } return bestMatch; } public static Shape getOrCreate(String name){ if(!DB.containsKey(name)){DB.put(name, new Shape(name));} return DB.get(name); } //----------------------Nested Prototype Class----------------------------// public static class Prototype extends Ink.Norm implements Serializable { int nBlend = 1; public Prototype(Ink.Norm norm) { super(norm); } public void blend(Ink.Norm norm) { blend(norm, nBlend); nBlend++; } //----------------------Nested List Class----------------------------// public static class List extends ArrayList<Prototype> implements Serializable { public static Prototype bestMatch; private static final int m =UC.PROTOTYPE_LIST_MARGIN, w = UC.PROTOTYPE_LIST_SIZE; private static G.VS showBox = new G.VS(m, m, w, w); public int bestDist(Ink.Norm norm) { bestMatch = null; int bestSoFar = UC.NO_MATCH_DIST; for (Prototype p : this) { int d = p.dist(norm); if (d < bestSoFar) { bestSoFar = d; bestMatch = p; } } return bestSoFar; } public int nHit(int x, int y){ return x/(m+w);} public void show(Graphics g) { g.setColor(Color.ORANGE); for (int i = 0; i < size(); i++) { Prototype p = get(i); int x = m + i * (m + w); showBox.loc.set(x, m); p.drawAt(g, showBox); g.drawString("" + p.nBlend, x, 20); } } public Prototype blendOrAdd(Ink.Norm norm) { int d = bestDist(norm); if (d < UC.NO_MATCH_DIST) { bestMatch.blend(norm); return bestMatch; } Prototype res = new Prototype(norm); add(res); return res; } } } //----------------------------------------Trainer--------------------------------------------// public static class Trainer implements I.Area { public NameState ns = new NameState(); public static boolean isTraining = false; public void keyTyped(char c) { ns.keyTyped(c);} @Override public boolean hit(int x, int y) { return isTraining; } @Override public void dn(int x, int y) { Ink.BUFFER.dn(x, y); } @Override public void drag(int x, int y) { Ink.BUFFER.drag(x, y); } @Override public void up(int x, int y) { if (ns.illegal()) { ns.shapeBeingTrained = null; return; } Ink ink = new Ink(); Shape.Prototype proto; ns.shapeBeingTrained = Shape.getOrCreate(ns.name); Prototype.List pList=ns.shapeBeingTrained.prototypes; //click stored shape to remove from database if(pList.size()>0 && y<UC.PROTOTYPE_LIST_Y_LIM){ int iProto=pList.nHit(x, y); if(iProto<pList.size()) pList.remove(iProto); }else { pList.blendOrAdd(ink.norm); } ns.setState(); } public void show(Graphics g) { g.setColor(UC.SHAPE_TRAINER_BACKGROUND_COLOR); g.fillRect(0, 0, 5000, 5000); g.setColor(Color.BLACK); Ink.BUFFER.show(g); ns.show(g); } //-------------------------------------Name State----------------------------------------// public static class NameState { public static String UNKNOWN = "<-unknown", ILLEGAL = "<-illegal", KNOWN = "<-known", INSTRUCTIONS = "type name and draw examples - space clears name - enter saves DB - click saved shape to delete from DB"; public String name = ""; public String state = ILLEGAL; public Shape shapeBeingTrained; public void show(Graphics g) { g.setColor(Color.BLACK); g.drawString(INSTRUCTIONS, 20, 100); if (state == ILLEGAL) g.setColor(Color.RED); g.drawString(name, 600, 30); g.drawString(state, 700, 30); if (shapeBeingTrained != null) { shapeBeingTrained.prototypes.show(g); } } public void setState() { shapeBeingTrained = null; state = (name.equals("") || name.equals("DOT")) ? ILLEGAL : UNKNOWN; if (state.equals(UNKNOWN)) { if (Shape.DB.containsKey(name)) { state = KNOWN; shapeBeingTrained = Shape.DB.get(name); } } } public void keyTyped(char c) { System.out.println("typed: " + c); name = (c == ' ' || c == 0x0D || c == 0x0A) ? "" : name + c; setState(); if (c == 0x0D || c == 0x0A) { Shape.saveShapeDB(); } } public boolean illegal() { return state.equals(ILLEGAL); } } } }
true
c057ed5834ec27332250fddca1dff690af3a21fe
Java
jaebeomkwon/bitwarefinal
/src/main/java/com/bitgroupware/chat/Beans/ChatMessageDto.java
UTF-8
368
1.789063
2
[]
no_license
package com.bitgroupware.chat.Beans; import lombok.Getter; import lombok.Setter; import lombok.ToString; @Getter @Setter @ToString public class ChatMessageDto { public enum MessageType { CHAT, JOIN, LEAVE } private MessageType messageType; private String content; private String sender; private String receiver; private String roomId; }
true
0ee3e3e3dc9d51260dd3a100a5e229e613a95727
Java
Ashish1414/Doodle
/app/src/main/java/com/proxima/elearning/ChangePassword.java
UTF-8
4,291
2.203125
2
[]
no_license
package com.proxima.elearning; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; public class ChangePassword extends AppCompatActivity { EditText oldPassword,newPassword,confirmPassword; Button btnChange; SharedPreferences sharedPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_change_password); final RequestQueue requestQueue = Volley.newRequestQueue(ChangePassword.this); sharedPreferences = getSharedPreferences("Login",0); final Config config = new Config(); newPassword = findViewById(R.id.newPassword); oldPassword = findViewById(R.id.oldPassword); confirmPassword = findViewById(R.id.confirmPassword); btnChange = findViewById(R.id.btnConfirm); btnChange.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (newPassword.getText().toString().equals(confirmPassword.getText().toString())) { StringRequest stringRequest = new StringRequest(Request.Method.POST, config.baseUrl + "changepassword.php", new Response.Listener<String>() { @Override public void onResponse(String response) { try { Log.e("Json Student",response); JSONObject jsonObject = new JSONObject(response); String status = jsonObject.getString("Status"); if (status.equals("Success")) { Toast.makeText(ChangePassword.this, "Password Changed Successfully", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(ChangePassword.this,Student_dashboard.class); startActivityForResult(intent,0); overridePendingTransition(0,0); } else { Toast.makeText(ChangePassword.this, "Incorrect Password", Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("Error Student",error.toString()); } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); Log.e("id",sharedPreferences.getString("StudentID","")+"abc"); params.put("id",sharedPreferences.getString("StudentID","")); params.put("oldpassword", oldPassword.getText().toString()); params.put("newpassword",newPassword.getText().toString()); return params; } }; requestQueue.add(stringRequest); } else { Toast.makeText(ChangePassword.this, "New password and confirm password did not match", Toast.LENGTH_SHORT).show(); } } }); } }
true
a6061842a1a1b300c2f44a5d29e97884afe9bdeb
Java
DanGrew/Portfolio
/NeuralNetworkSerialization/src/representation/xml/wrapper/XmlLearningParametersWrapper.java
UTF-8
2,820
2.21875
2
[]
no_license
/* * ---------------------------------------- * Neural Networks * ---------------------------------------- * Produced by Dan Grew * ---------------------------------------- */ package representation.xml.wrapper; import java.util.Iterator; import java.util.List; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSeeAlso; import architecture.representation.StructuralRepresentation; import architecture.request.RequestSystem; import model.data.SerializableLearningParameter; import model.singleton.LearningParameter; import model.structure.LearningParameters; import representation.xml.model.XmlLearningParameter; /** * The {@link XmlLearningParametersWrapper} wraps a {@link Collection} of {@link LearningParameter}s * representing {@link LearningParameters}. */ @XmlRootElement @XmlSeeAlso( { XmlLearningParameter.class } ) public class XmlLearningParametersWrapper extends SingletonCollectionWrapper< LearningParameter, SerializableLearningParameter > implements StructuralRepresentation< LearningParameters > { /** * Constructs a new {@link XmlLearningParametersWrapper}. */ public XmlLearningParametersWrapper() { super(); }// End Constructor /** * Constructs a new {@link XmlLearningParametersWrapper} with the given elements. * @param iterator the {@link Iterator} of {@link LearningParameter} to populate with. */ public XmlLearningParametersWrapper( Iterator< LearningParameter > iterator ){ super( iterator ); }// End Constructor /** * {@inheritDoc} */ @Override public void addUnwrapped( LearningParameter object ) { addObject( object.write( XmlLearningParameter.class ) ); }// End Method /** * {@inheritDoc} */ @Override public void resolveSingletons() { objects.iterator().forEachRemaining( object -> RequestSystem.process( LearningParameter.class, object.getIdentification(), parameter -> parameter.read( object ) ) ); }// End Method /** * {@inheritDoc} */ @Override public LearningParameters makeStructure() { LearningParameters parameters = new LearningParameters(); objects.iterator().forEachRemaining( object -> { LearningParameter parameter = RequestSystem.retrieve( LearningParameter.class, object.getIdentification() ); parameters.addLearningParameter( parameter ); } ); return parameters; }// End Method /** * {@inheritDoc} */ @Override public List< LearningParameter > retrieveSingletons() { return super.retrieveSingletons( LearningParameter.class ); }// End Method }// End Method
true
2cca8cafaf2b9739dd196df5db648fcef89daae5
Java
adpushup/prebid-server-java
/src/main/java/org/prebid/server/bidder/pangle/model/PangleBidExt.java
UTF-8
250
1.789063
2
[ "Apache-2.0" ]
permissive
package org.prebid.server.bidder.pangle.model; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Value; @AllArgsConstructor(staticName = "of") @Builder(toBuilder = true) @Value public class PangleBidExt { BidExt pangle; }
true
bdfc68e75e4f2d72360255ef2fddee8ea61f2781
Java
Steamtradenet/skincoin-payment-service
/src/main/java/net/steamtrade/payment/backend/client/request/JsonRpcResponse.java
UTF-8
439
1.796875
2
[]
no_license
package net.steamtrade.payment.backend.client.request; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; @Data @JsonIgnoreProperties(ignoreUnknown = true) public class JsonRpcResponse<T> { @JsonProperty("jsonrpc") private String jsonrpc; @JsonProperty("id") private Integer id; @JsonProperty("result") private T result; }
true
cee23d7f03104dfb177e5c7d2029c2226080716d
Java
oheong/java
/day09_06io_IOQuiz01.java
UTF-8
1,022
3.890625
4
[]
no_license
package com.ssafy.java.day02_06io; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; /* * 화면에서 ㅁ누자를 입력받아 입력받은 문자를 출ㅕ * 단, 문자는 한 문자만 입력ㅂ다는다. * 입력받은 문자가 'Q' 또는 'q'일경우 * 화면에 "종료합니다" 메세지 출력 * * 실행결과 > * 한 문자를 입력하세요 : m * 입력된 문자는 m입니다. * */ public class IOQuiz01 { public static void main(String[] args) { InputStreamReader input = new InputStreamReader(System.in); while (true) { char ch; try { ch = (char) input.read(); input.read(); // \r input.read(); // \n //☆★ 줄넘김 문자 주의 if (ch == 'Q' || ch == 'q') { System.out.println("종료합니다."); break; } System.out.println(String.format("입력된 문자는 %c입니다.", ch)); } catch (IOException e) { e.printStackTrace(); } } } }
true
031cc786f6a043a5ed2fb82d7c309618de90fda1
Java
aabidkar/LogicalProgramming
/src/main/java/programms/FahrenheitToCelsiusLBP026.java
UTF-8
671
3.4375
3
[]
no_license
package programms; import java.util.Scanner; import org.apache.log4j.Logger; /* Program to convert fahrenheit to celsius. input -------> fahrenheit constraint --> no output ------> celsius formula: (F-32)*5/9 */ public class FahrenheitToCelsiusLBP026 { static Logger logger = Logger.getLogger(FahrenheitToCelsiusLBP026.class); static int celsius = 0; static int fahrenheitToCelsius(int fahrenheit) { celsius = (fahrenheit - 32) * 5 / 9; return celsius; } public static void main(String[] args) { Scanner myObj = new Scanner(System.in); int fahrenheit = myObj.nextInt(); logger.info(FahrenheitToCelsiusLBP026.fahrenheitToCelsius(fahrenheit)); } }
true
91294e3007b1ee0ec712b24c382906d74efaed87
Java
maximusmith529/JoJokes
/Enchantment.java
UTF-8
2,533
3.109375
3
[]
no_license
public class Enchantment { //Not limited to only enchantments, also potion effects, etc. public Enchantment(String name, boolean buff, boolean Static, int EType, int EAmount) { this.name = name; this.buff = buff; this.Static = Static; this.EType = EType; this.EAmount = EAmount; } public Enchantment(String name, boolean buff, boolean Static, int EType, int EAmount, int EStat) { this.name = name; this.buff = buff; this.Static = Static; this.EType = EType; this.EAmount = EAmount; this.EStat = EStat; } public Enchantment enchGenerator() { int r = (int)Math.random()*2; boolean b; boolean s; int EType = (int)Math.random()*7; int EAmount = (int) Math.random()*6; int EStat = (int) Math.random()*5; if(r == 0) { b = true; }else { b = false; } r = (int)Math.random()*2; if(r == 0) { s = true; }else { s = false; } String name = ""; //Descriptor Enchantment x = new Enchantment(name,b,s,EType,EAmount, EStat); return x; } String name; boolean buff; //Type of enchantment/buff/debuff boolean Static; //If true enchantment is not an an over time effect ie. not healing over time/ poison over time int EType; //What statistics it affects. 0 == Armor? / Health : 1 == Mana : 2 == Stamina // 3 == Stats (Strength, Agility, etc.) : 4 == Damage : 5 == Extra Life : 6 == Looting? int EAmount; int EStat; /* int strength = 8; 0 int agility = 8; 1 int dexterity = 8; 2 int intelligence = 8; 3 int constitution = 8; 4 */ boolean PDmg; public void equipEnchantment(Character ch1) { if(Static == true) { if(EType == 0) { ch1.health =+ EAmount; } if(EType == 1) { ch1.mana =+ EAmount; } if(EType == 2) { ch1.stamina =+ EAmount; } if(EType == 3) { if(EStat == 0) { ch1.strength =+ EAmount; } if(EStat == 1) { ch1.agility =+ EAmount; } if(EStat == 2) { ch1.dexterity =+ EAmount; } if(EStat == 3) { ch1.intelligence =+ EAmount; } if(EStat == 4) { ch1.constitution =+ EAmount; } } if(EType == 4) { if(PDmg == true) { ch1.pDamage =+ EAmount; } if(PDmg == false) { ch1.mDamage =+ EAmount; } } if(EType == 5) { ch1.extraLife =+ EAmount; } if(EType == 6) { ch1.luck =+ EAmount; } //Recalculate Statistics } } }
true
e7ba8fd47bc5f92f526b65b21d5cabb2407f58b3
Java
environmentalinformatics-marburg/magic
/timeseriesdatabase/src/tsdb/testing/TestingBulkLoad.java
UTF-8
1,321
2.515625
3
[]
no_license
package tsdb.testing; import java.io.File; import java.util.ArrayList; import org.mapdb.BTreeMap; import org.mapdb.DB; import org.mapdb.DBMaker; import org.mapdb.Fun.Tuple2; public class TestingBulkLoad { public static void main(String[] args) { DB db = DBMaker.newFileDB(new File("c:/TestingBulkLoad/"+"cachedb")) .closeOnJvmShutdown() .make(); System.out.println("init..."); final int count = 1000000; ArrayList<Tuple2<Long,Double>> list = new ArrayList<Tuple2<Long,Double>>(count); for(long i=0;i<count;i++) { list.add(new Tuple2<Long, Double>(i, i*10000d+(i%11d))); } System.out.println("insert..."); db.createTreeMap("newName").pumpPresort(50000000).pumpSource(list.iterator()).makeLongMap(); /*BTreeMap<Long, Double> map = db.createTreeMap("newName").make(); for(Tuple2<Long, Double> t:list) { map.put(t.a, t.b); }*/ System.out.println("commit..."); db.commit(); System.out.println("compact..."); db.compact(); System.out.println("...end"); db.close(); db = DBMaker.newFileDB(new File("c:/TestingBulkLoad/"+"cachedb")) .closeOnJvmShutdown() .make(); BTreeMap<Object, Object> map2 = db.getTreeMap("newName"); System.out.println(map2.size()); db.close(); } }
true
4f00de7266a422d2ca2bd7ad780fb44907c67843
Java
kldo1011/shop-rep
/shop/src/main/java/kundenverwaltung/domain/AbstractKunde.java
UTF-8
8,105
2.015625
2
[]
no_license
package kundenverwaltung.domain; import java.io.Serializable; import java.net.URI; import java.util.List; import javax.persistence.Basic; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.validation.Valid; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlTransient; import org.codehaus.jackson.annotate.JsonSubTypes; import org.codehaus.jackson.annotate.JsonSubTypes.Type; import org.codehaus.jackson.annotate.JsonTypeInfo; import org.hibernate.validator.constraints.Email; import bestellverwaltung.domain.Bestellung; @Entity @XmlRootElement @XmlSeeAlso({ Firmenkunde.class, Privatkunde.class }) @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonSubTypes({ @Type(value = Privatkunde.class, name = AbstractKunde.PRIVATKUNDE), @Type(value = Firmenkunde.class, name = AbstractKunde.FIRMENKUNDE) }) public abstract class AbstractKunde implements Serializable { private static final long serialVersionUID = 7401524595142572933L; public static final String PRIVATKUNDE = "P"; public static final String FIRMENKUNDE = "F"; //Pattern mit UTF-8 (statt Latin-1 bzw. ISO-8859-1) Schreibweise fuer Umlaute: private static final String NAME_PATTERN = "[A-Z\u00C4\u00D6\u00DC][a-z\u00E4\u00F6\u00FC\u00DF]+"; private static final String NACHNAME_PREFIX = "(o'|von|von der|von und zu|van)?"; public static final String NACHNAME_PATTERN = NACHNAME_PREFIX + NAME_PATTERN + "(-" + NAME_PATTERN + ")?"; private static final int NACHNAME_LENGTH_MIN = 2; private static final int NACHNAME_LENGTH_MAX = 32; private static final int EMAIL_LENGTH_MAX = 128; @Id @GeneratedValue @Basic(optional = false) private Long id; @NotNull(message = "{kundenverwaltung.kunde.nachname.notNull}") @Size(min = NACHNAME_LENGTH_MIN, max = NACHNAME_LENGTH_MAX, message = "{kundenverwaltung.kunde.nachname.length }") @Pattern(regexp = NACHNAME_PATTERN, message = "{kundenverwaltung.kunde.nachname.pattern}") private String nachname; //TODO validation private String vorname; @Email(message = "{kundenverwaltung.kunde.email.pattern}") @NotNull(message = "{kundenverwaltung.kunde.email.notNull }") @Size(max = EMAIL_LENGTH_MAX, message = "{kunde.email.length}") private String email; @Valid @NotNull(message = "{kundenverwaltung.kunde.adresse.notNull}") private Adresse adresse; @XmlTransient private List<Bestellung> bestellungen; private URI bestellungenUri; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getVorname() { return vorname; } public void setVorname(String vorname) { this.vorname = vorname; } public String getNachname() { return nachname; } public void setNachname(String nachname) { this.nachname = nachname; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Adresse getAdresse() { return adresse; } public void setAdresse(Adresse adresse) { this.adresse = adresse; } public List<Bestellung> getBestellungen() { return bestellungen; } public void setBestellungen(List<Bestellung> bestellungen) { this.bestellungen = bestellungen; } public URI getBestellungenUri() { return bestellungenUri; } public void setBestellungenUri(URI bestellungenUri) { this.bestellungenUri = bestellungenUri; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((adresse == null) ? 0 : adresse.hashCode()); result = prime * result + ((bestellungen == null) ? 0 : bestellungen.hashCode()); result = prime * result + ((bestellungenUri == null) ? 0 : bestellungenUri.hashCode()); result = prime * result + ((email == null) ? 0 : email.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((nachname == null) ? 0 : nachname.hashCode()); result = prime * result + ((vorname == null) ? 0 : vorname.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final AbstractKunde other = (AbstractKunde) obj; if (adresse == null) { if (other.adresse != null) return false; } else if (!adresse.equals(other.adresse)) return false; if (bestellungen == null) { if (other.bestellungen != null) return false; } else if (!bestellungen.equals(other.bestellungen)) return false; if (bestellungenUri == null) { if (other.bestellungenUri != null) return false; } else if (!bestellungenUri.equals(other.bestellungenUri)) return false; if (email == null) { if (other.email != null) return false; } else if (!email.equals(other.email)) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (nachname == null) { if (other.nachname != null) return false; } else if (!nachname.equals(other.nachname)) return false; if (vorname == null) { if (other.vorname != null) return false; } else if (!vorname.equals(other.vorname)) return false; return true; } @Override public String toString() { return "AbstractKunde [id=" + id + ", vorname=" + vorname + ", nachname=" + nachname + ", email=" + email + ", adresse=" + adresse + ", bestellungen=" + bestellungen + ", bestellungenUri=" + bestellungenUri + "]"; } }
true
e9f6119ad28826fdfa971737eead8a24f0daaa5a
Java
githubmet/picassosketch
/app/src/main/java/com/example/incir/picassosketch/P001PicassoListView.java
UTF-8
1,409
2.078125
2
[]
no_license
package com.example.incir.picassosketch; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.ArrayAdapter; import com.example.incir.picassosketch.adapter.P001ArrayAdapter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class P001PicassoListView extends Activity implements AdapterView.OnItemClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.p001picassolistview); ListView listViewP001=(ListView)findViewById(R.id.listViewP001); String[] calismalar=getResources().getStringArray(R.array.calismalar);//dikkat bunu gondererek daha basit yapabilirsin List<String> stringList=new ArrayList(Arrays.asList(calismalar)); ArrayAdapter arrayAdapter=new P001ArrayAdapter(this,R.layout.p001customrow,stringList); listViewP001.setAdapter(arrayAdapter); listViewP001.setOnItemClickListener(this); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent=new Intent(this,P002CreateBitmap.class); intent.putExtra("position",String.valueOf(position)); startActivity(intent); } }
true
ef649bbf5e93673bd64b67947de54a70f12f78d8
Java
electionguru4u/SmartChemist
/app/src/main/java/oasis/com/smartchemist/databases/DatabaseStock.java
UTF-8
7,405
2.171875
2
[]
no_license
package oasis.com.smartchemist.databases; import android.content.ContentValues; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import oasis.com.smartchemist.utils.Rack; import oasis.com.smartchemist.utils.Shelf; import oasis.com.smartchemist.utils.Tax; public class DatabaseStock extends SQLiteOpenHelper { private static final String DATABASE_NAME = "stocks_db"; private static final int DATABASE_VERSION = 1; private static final String DATABASE_MASTER_RACK = "master_rack"; private static final String RACK_CODE = "mrk_code"; private static final String RACK_NAME = "mrk_rack_name"; private static final String RACK_DESCRIPTION = "mrk_description"; private static final String DATABASE_MASTER_SHELF = "master_shelf"; private static final String SHELF_CODE = "msf_code"; private static final String SHELF_NAME = "msf_shelf_name"; private static final String SHELF_DESCRIPTION = "msf_description"; private static final String DATABASE_MASTER_BATCH = "master_batch"; private static final String BATCH_CODE = "BATCH_code"; private static final String PRODUCT_CODE = "mpd_code"; private static final String BATCH_BATCH_NO = "BATCH_batch_no"; private static final String BATCH_MFG_DATE = "BATCH_mfg_date"; private static final String BATCH_EXPIRY_DATE = "BATCH_expiry_date"; private static final String BATCH_MRP = "BATCH_mrp"; private static final String DATABASE_MASTER_STOCK = "master_stock"; private static final String STOCK_CODE = "mst_code"; private static final String TAX_CODE = "mst_code"; private static final String STOCK_QUANTITY = "mst_quantity"; //stock_code,batch_code,tax_code,quantity,shelf_code; private static final String DATABASE_TABLE_TAX = "master_tax"; public static final String TAX_NAME= "tax_name"; public static final String TAX_PERCENTAGE= "tax_percentage"; public static final String TAX_DESCRIPTION= "tax_description"; public static final String ACTIVE= "active"; public DatabaseStock(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { String create_table_master_rack = "CREATE TABLE " + DATABASE_MASTER_RACK + "(" + RACK_CODE + " TEXT PRIMARY KEY," + RACK_NAME + " TEXT," + RACK_DESCRIPTION + " TEXT)"; String create_table_master_shelf = "CREATE TABLE " + DATABASE_MASTER_SHELF + "(" + SHELF_CODE + " TEXT PRIMARY KEY," + RACK_CODE + " TEXT," + SHELF_NAME + " TEXT," + SHELF_DESCRIPTION + " TEXT)"; String create_table_master_batch = "CREATE TABLE " + DATABASE_MASTER_BATCH + "(" + BATCH_CODE + " TEXT PRIMARY KEY," + PRODUCT_CODE + " TEXT," + BATCH_BATCH_NO + " TEXT," + BATCH_MFG_DATE + " TEXT," + BATCH_EXPIRY_DATE + " TEXT," + BATCH_MRP + " TEXT)"; String create_table_master_stock = "CREATE TABLE " + DATABASE_MASTER_STOCK + "(" + STOCK_CODE + " TEXT PRIMARY KEY," + BATCH_CODE + " TEXT," + TAX_CODE+" TEXT,"+STOCK_QUANTITY + " TEXT,"+SHELF_CODE+" TEXT)"; String create_table_tax="CREATE TABLE "+DATABASE_TABLE_TAX+"("+TAX_CODE+" TEXT PRIMARY KEY,"+TAX_NAME+" TEXT,"+TAX_PERCENTAGE+" TEXT,"+TAX_DESCRIPTION+" TEXT,"+ACTIVE+" TEXT)"; sqLiteDatabase.execSQL(create_table_master_rack); sqLiteDatabase.execSQL(create_table_master_shelf); sqLiteDatabase.execSQL(create_table_master_batch); sqLiteDatabase.execSQL(create_table_master_stock); sqLiteDatabase.execSQL(create_table_tax); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { String drop_table_master_rack = "DROP TABLE IF EXISTS " + DATABASE_MASTER_RACK; String drop_table_master_shelf = "DROP TABLE IF EXISTS " + DATABASE_MASTER_SHELF; String drop_table_master_batch = "DROP TABLE IF EXISTS " + DATABASE_MASTER_BATCH; String drop_table_master_stock = "DROP TABLE IF EXISTS " + DATABASE_MASTER_STOCK; String drop_table_tax="DROP TABLE IF EXISTS "+DATABASE_TABLE_TAX; sqLiteDatabase.execSQL(drop_table_master_rack); sqLiteDatabase.execSQL(drop_table_master_shelf); sqLiteDatabase.execSQL(drop_table_master_batch); sqLiteDatabase.execSQL(drop_table_master_stock); sqLiteDatabase.execSQL(drop_table_tax); } public void insertRackDetails(Rack rack) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(RACK_CODE, rack.getMrk_code()); values.put(RACK_NAME, rack.getMrk_rack_name()); values.put(RACK_DESCRIPTION, rack.getMrk_desc()); int i = db.update(DATABASE_MASTER_RACK, values, RACK_CODE + "=?", new String[]{rack.getMrk_code()}); if (i == 0) db.insert(DATABASE_MASTER_RACK, null, values); db.close(); } public void insertShelfDetails(Shelf shelf) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(SHELF_CODE, shelf.getMsf_code()); values.put(RACK_CODE, shelf.getMrk_code()); values.put(SHELF_NAME, shelf.getMsf_shelf_name()); values.put(SHELF_DESCRIPTION, shelf.getMsf_desc()); int i = db.update(DATABASE_MASTER_SHELF, values, SHELF_CODE + "=?", new String[]{shelf.getMsf_code()}); if (i == 0) db.insert(DATABASE_MASTER_SHELF, null, values); db.close(); } /* public void insertBatchDetails(Batch batch) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(BATCH_CODE, batch.getBATCH_code()); values.put(PRODUCT_CODE, batch.getMpd_code()); values.put(BATCH_BATCH_NO, batch.getBATCH_batch_no()); values.put(BATCH_MFG_DATE, batch.getBATCH_mfg_date()); values.put(BATCH_EXPIRY_DATE, batch.getBATCH_expiry_date()); values.put(BATCH_MRP, batch.getBATCH_mrp()); int i = db.update(DATABASE_MASTER_BATCH, values, BATCH_CODE + "=?", new String[]{batch.getBATCH_code()}); if (i == 0) db.insert(DATABASE_MASTER_BATCH, null, values); db.close(); } public void insertStockDetails(Stock stock) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(MST_CODE, stock.getMst_code()); values.put(BATCH_CODE,stock.getBATCH_code()); values.put(MST_QUANTITY, stock.getMst_quantity()); int i = db.update(DATABASE_MASTER_STOCK, values, MST_CODE+ "=?", new String[]{stock.getMst_code()}); if (i == 0) db.insert(DATABASE_MASTER_STOCK, null, values); db.close(); }*/ public void insertTaxDetails(Tax tax){ SQLiteDatabase db=this.getWritableDatabase(); ContentValues values=new ContentValues(); values.put(TAX_CODE,tax.getTax_code()); values.put(TAX_NAME,tax.getTax_name()); values.put(TAX_PERCENTAGE,tax.getTax_percentage()); values.put(TAX_DESCRIPTION,tax.getTax_desc()); values.put(ACTIVE,tax.getActive()); int i=db.update(DATABASE_TABLE_TAX,values,TAX_CODE+"=?",new String[]{TAX_CODE}); if(i==0) db.insert(DATABASE_TABLE_TAX,null,values); db.close(); } }
true
c6351fa827af82b704ee1a66b575855b79ad93dc
Java
13266764646/spring-framewrok3.2.x
/zip/spring-framework-3.2.x/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/package-info.java
UTF-8
843
2.078125
2
[ "Apache-2.0" ]
permissive
/** * * Package providing integration of * <a href="https://hibernate.org/">Hibernate 4.x</a> * with Spring concepts. * * <p>Contains an implementation of Spring's transaction SPI for local Hibernate transactions. * This package is intentionally rather minimal, with no template classes or the like, * in order to follow Hibernate recommendations as closely as possible. We recommend * using Hibernate's native <code>sessionFactory.getCurrentSession()</code> style. * * <p><b>This package supports Hibernate 4.x only.</b> * See the {@code org.springframework.orm.hibernate3} package for Hibernate 3.x support. * <b>Note:</b> Do not use HibernateTemplate or other classes from the hibernate3 package * with Hibernate 4; this will lead to class definition exceptions at runtime. * */ package org.springframework.orm.hibernate4;
true
165d5facf592b0f3fe940c58e6eb0861c093e75a
Java
Pkaran01/Fun2Sh-Chat-Voice-Video-Games
/app/src/main/java/com/ss/fun2sh/utils/broadcasts/ChatMessageReceiver.java
UTF-8
1,668
1.984375
2
[]
no_license
package com.ss.fun2sh.utils.broadcasts; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.quickblox.q_municate_core.service.QBServiceConsts; import com.quickblox.q_municate_db.models.User; import com.ss.fun2sh.CRUD.M; import com.ss.fun2sh.ui.activities.call.CallActivity; import com.ss.fun2sh.utils.SystemUtils; import com.ss.fun2sh.utils.helpers.notification.ChatNotificationHelper; public class ChatMessageReceiver extends BroadcastReceiver { private static final String TAG = ChatMessageReceiver.class.getSimpleName(); private static final String callActivityName = CallActivity.class.getName(); @Override public void onReceive(Context context, Intent intent) { //M.E("--- onReceive()" + TAG); String activityOnTop = SystemUtils.getNameActivityOnTopStack(); if (!SystemUtils.isAppRunningNow() && !callActivityName.equals(activityOnTop)) { ChatNotificationHelper chatNotificationHelper = new ChatNotificationHelper(context); try { String message = intent.getStringExtra(QBServiceConsts.EXTRA_CHAT_MESSAGE); User user = (User) intent.getSerializableExtra(QBServiceConsts.EXTRA_USER); String dialogId = intent.getStringExtra(QBServiceConsts.EXTRA_DIALOG_ID); chatNotificationHelper.saveOpeningDialogData(user.getUserId(), dialogId); chatNotificationHelper.saveOpeningDialog(true); chatNotificationHelper.sendNotification(message); } catch (Exception e) { e.printStackTrace(); } } } }
true
1cbe6b0877ac925b92a721be44202710a4c44d08
Java
00321001/salesManagementSystem
/src/main/java/cn/salesManagementSystem/service/IInventoryService.java
UTF-8
569
1.703125
2
[]
no_license
package cn.salesManagementSystem.service; import cn.salesManagementSystem.entity.Inventory; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.service.IService; import java.util.List; /** * @author 闫铁鹰 * @program salesManagementSystem * @description 商品库存Service层接口 * @date 2021-04-30 22:20 **/ public interface IInventoryService extends IService<Inventory> { IPage<Inventory> getInventoryList(Integer storeId, IPage<Inventory> page); List<Inventory> getInventoryList(Integer storeId); }
true
12ffdc1576bf2cd53a78a69c43c3eaf5f6502400
Java
fdsmora/DCCT
/src/unam/dcct/model/tutorial/TestProtocolScenarioGenerator.java
UTF-8
1,548
2.453125
2
[]
no_license
package unam.dcct.model.tutorial; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class TestProtocolScenarioGenerator { // Three processes (dimension 2) scenarios private static int[][][] mat2 = new int[][][] { // Dummy scenarios {{1,0,0},{1,1,0},{1,0,1}}, {{1,1,0},{0,1,0},{0,1,1}}, {{1,0,1},{0,1,1},{0,0,1}}, {{1,1,0},{1,1,0},{0,1,1}}, {{1,0,1},{0,1,1},{1,0,1}}, // Immediate Snapshot execution scenarios {{1,1,1},{0,1,0},{1,1,1}}, {{1,1,1},{1,1,1},{0,0,1}}, {{1,1,0},{1,1,0},{1,1,1}}, {{1,0,1},{1,1,1},{1,0,1}}, {{1,1,1},{0,1,1},{0,1,1}}, {{1,0,0},{1,1,0},{1,1,1}}, {{1,0,1},{1,1,1},{1,0,1}}, {{1,1,0},{0,1,0},{1,1,1}}, {{1,1,1},{0,1,0},{0,1,1}}, {{1,1,1},{0,1,1},{0,0,1}}, {{1,0,1},{1,1,1},{0,0,1}}, {{1,0,0},{1,1,1},{1,0,1}}, {{1,0,0},{1,1,1},{1,1,1}}, {{1,1,1},{1,1,1},{1,1,1}} }; // Two processes (dimension 1) scenarios private static int[][][] mat1 = new int[][][] { {{1,0},{1,1}}, {{1,1},{1,1}}, {{1,1},{0,1}} }; // One process (dimension 0) scenario private static int[][][] mat0 = new int[][][] { {{1}} }; private static List<List<int[][]>> allScenariosPerDimension; static{ // Initalize list allScenariosPerDimension = new ArrayList<List<int[][]>>(); allScenariosPerDimension.add(Arrays.asList(mat0)); allScenariosPerDimension.add(Arrays.asList(mat1)); allScenariosPerDimension.add(Arrays.asList(mat2)); } public static List<int[][]> generate(int dimension){ return allScenariosPerDimension.get(dimension); } }
true
97ecba5e5e1fea4a6d4790f2058b837591a900d0
Java
360workplace/simon-360workplace
/src/main/java/com/workplace/simon/repository/ExecutionRepository.java
UTF-8
2,361
2.046875
2
[]
no_license
package com.workplace.simon.repository; import com.workplace.simon.model.Execution; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface ExecutionRepository extends JpaRepository<Execution, Long> { List<Execution> findBySourceAndStatus(Long userId, String status); List<Execution> findBySourceAndStatusNotOrderByPriorityDesc(Long userId, String status); List<Execution> findBySupervisorAndStatus(Long supervisorId, String status); List<Execution> findByStatusNot(String status); @Query(value = "SELECT execution0_.id as id, execution0_.code_from as code_from, execution0_.deadline as deadline, " + "execution0_.detail as detail, execution0_.priority as priority, execution0_.resources as resource, " + "execution0_.source as source, execution0_.status as status, execution0_.supervisor as supervisor, " + "execution0_.title as title, execution0_.resources as resources " + "FROM ejecucion execution0_ " + "INNER JOIN users u ON (execution0_.source = u.id) " + "INNER JOIN area a ON (u.area_id = a.id) " + "WHERE a.id = (:areaId) " + "AND execution0_.status = (:status)", nativeQuery = true) List<Execution> findByAreaAndStatus(@Param("areaId") Long areaId, @Param("status") String status); @Query(value = "SELECT execution0_.id as id, execution0_.code_from as code_from, execution0_.deadline as deadline, " + "execution0_.detail as detail, execution0_.priority as priority, execution0_.resources as resource, " + "execution0_.source as source, execution0_.status as status, execution0_.supervisor as supervisor, " + "execution0_.title as title, execution0_.resources as resources " + "FROM ejecucion execution0_ " + "INNER JOIN users u ON (execution0_.source = u.id) " + "INNER JOIN area a ON (u.area_id = a.id) " + "WHERE a.id = (:areaId) " + "AND execution0_.status <> (:status)", nativeQuery = true) List<Execution> findByAreaAndStatusNot(@Param("areaId") Long areaId, @Param("status") String status); }
true
95d87e79f1e9fdf0b4e2e3ed64db45dbd46b3029
Java
osuisumi/tt
/tip-course/tip-course-core/src/main/java/com/haoyu/ncts/course/dao/ICourseRegisterDao.java
UTF-8
689
1.789063
2
[]
no_license
package com.haoyu.ncts.course.dao; import java.util.List; import java.util.Map; import com.github.miemiedev.mybatis.paginator.domain.PageBounds; import com.haoyu.ncts.course.entity.CourseRegister; public interface ICourseRegisterDao { List<CourseRegister> select(Map<String, Object> params, PageBounds pageBounds); int insert(CourseRegister courseRegister); int update(Map<String,Object> param); int deleteByLogic(Map<String, Object> param); int delete(Map<String,Object> param); int deleteByPhysics(String id); CourseRegister selectByPrimaryKey(String id); Map<String, Integer> mapCount(Map<String, Object> parameter); int getCount(Map<String, Object> param); }
true
715fa0ad55a8c4dbd9691f2540f4e469bc85a5c1
Java
Rusanescu11/Clinic
/bclinica/src/main/java/com/example/clinicaprivata/controller/RezervationController.java
UTF-8
1,906
2.078125
2
[]
no_license
package com.example.clinicaprivata.controller; import com.example.clinicaprivata.model.RezervationModel; import com.example.clinicaprivata.model.dto.RezervationDto; import com.example.clinicaprivata.repository.ReservationRepository; import com.example.clinicaprivata.service.RezervationService; import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @CrossOrigin @RestController public class RezervationController { @Autowired private ReservationRepository reservationRepository; @Autowired private RezervationService rezervationService; @PostMapping("/reservation/{id}") public void add(@RequestBody RezervationDto rezervationDto, @PathVariable (name = "id")Long id) { rezervationService.save(rezervationDto,id); } @DeleteMapping("/reservation/{id}") public void deleteById(@PathVariable(name = "id") Long id) { reservationRepository.deleteById(id); } @GetMapping("/reservation") public List<RezervationModel> getAll() { return reservationRepository.findAll(); } @GetMapping("/reservation/{id}") public RezervationModel getBydId(@PathVariable(name = "id") Long id) { return reservationRepository.findById(id).orElse(null); } @PutMapping("/reservation") public void update(@RequestBody RezervationModel rezervationModel) { RezervationModel update = reservationRepository.findById(rezervationModel.getId()).orElse(null); update.setDate(rezervationModel.getDate()); update.setStartConsultation(rezervationModel.getStartConsultation()); update.setEndConsultation(rezervationModel.getEndConsultation()); update.setMedic(rezervationModel.getMedic()); reservationRepository.save(rezervationModel); } }
true
d16c69d2fdf14d3acd83e0d0c173b27f169701c8
Java
lucasscarduelli/unibave-android-todolist
/app/src/main/java/net/unibave/todolist_java/model/DatabaseConstants.java
UTF-8
449
1.71875
2
[]
no_license
package net.unibave.todolist_java.model; public class DatabaseConstants { public static final String DB_NAME = "TODOLIST"; public static final int DB_VERSION = 1; public static final String TABLE_TASK = "TASK"; public static final String COLUMN_ID = "id"; public static final String COLUMN_CREATED_AT = "createdAt"; public static final String COLUMN_NAME = "name"; public static final String COLUMN_DONE = "done"; }
true
5a75da6a1505728155d9b1cb427d0739d27fab89
Java
SarfarazG/java
/JAVA-PROGRAMS/bwin/jjjjjjj/src/.metadata/bhavin/src/overloding/Run.java
UTF-8
218
1.796875
2
[]
no_license
package overloding; public class Run { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stuba Cals c=new Cals(); c.add(); c.add(88); c.add(99,77); } }
true
7c9c018faa4bb5a2e66142fd487d3dbe2c7d5026
Java
robyrai/pramitPorjectFiles
/BankUI.java
UTF-8
8,063
2.953125
3
[]
no_license
package com.cerotid.bank.ui; import java.util.*; import com.cerotid.bank.bo.BankBO; import com.cerotid.bank.bo.BankBOImpl; import com.cerotid.bank.model.Account; import com.cerotid.bank.model.AccountType; import com.cerotid.bank.model.Address; import com.cerotid.bank.model.Customer; import com.cerotid.bank.model.Transaction; public class BankUI { // TO create singleton implementation // private static final Double COUNT = null; private BankBO bankBo; private void setBankBo(BankBO bankBo) { this.bankBo = bankBo; } public BankBO getBankBo() { return bankBo; } public static void main(String[] args) { BankUI bankUI = new BankUI(); bankUI.setBankBo(new BankBOImpl()); bankUI.bankBo.deserializeBankData(); do { displayOption(); bankUI.performActionBasedOnCustomerChoice(); } while (true); } private void performActionBasedOnCustomerChoice() { while (true) { try { switch (getScannerInstance().nextInt()) { case 1: addMoreCustomer(); break; case 2: addCustomerAccount(); break; case 3: sendMoreMoney(); break; case 4: bankBo.printBankStatus(); break; case 5: System.out.println("Enter the StateCode"); String stateCode = getScannerInstance().nextLine(); printCustomerInfoForGivenState(bankBo.getCustomersByState(stateCode)); break; case 6: System.out.println("Thanks you!"); bankBo.serializeBankData(); System.exit(0); break; default: System.out.println("Not in option!"); break; } break; // breaks while loop when it execution point gets here } catch (Exception ex) { // Validation code System.out.println("Please provide valid integer input!"); } } } private void printCustomerInfoForGivenState(List<Customer> customersByState) { System.out.println(customersByState.size() + " Customers Found "); for (Customer customer : customersByState) { System.out.println(customer); } } private void addCustomerAccount() { Customer customer = retrieveCustomerInformation(); if (customer != null) { AccountType accntType = getCustomerChoiceAccountTypeToOpen(); double openingBalance = getOpeningBalance(); Account account = new Account(accntType, new Date(), openingBalance); customer.addAccount(account); } else System.out.println("Customer not available!"); } private double getOpeningBalance() { System.out.println("Provide Opening Balance in Account: "); Scanner accountBalance = getScannerInstance(); return accountBalance.nextDouble(); } private AccountType getCustomerChoiceAccountTypeToOpen() { displayAccountTypeChoice(); AccountType accountType = null; Scanner accountTypeInput = getScannerInstance(); switch (accountTypeInput.nextInt()) { case 1: accountType = AccountType.Checking; break; case 2: accountType = AccountType.Saving; break; case 3: accountType = AccountType.Business_Checking; break; } return accountType; } private void displayAccountTypeChoice() { System.out.println("Choose AccountType: [By default is Checkign account]: "); System.out.println("1. Checking 2. Saving 3. Business Checking"); } private Customer retrieveCustomerInformation() { Scanner accountInput = getScannerInstance(); System.out.println("Enter Customer's SSN to retrieve His Account Information: "); String ssn = accountInput.nextLine(); return bankBo.getCustomerInfo(ssn); } private void sendMoreMoney() { System.out.println("Send Money from the account"); Account customerChoiceAccount; Customer customer = retrieveCustomerInformation(); if (customer != null) { customerChoiceAccount = getAccountChoice(customer); Transaction newTransaction = doTransaction(); System.out.println("New transaction: " + newTransaction); customerChoiceAccount.addTransaction(newTransaction); System.out.println("New transaction one more time: " + newTransaction); deductBalance(customerChoiceAccount, newTransaction); System.out.println(bankBo.getCustomerInfo(customer.getSsn())); System.out.println(customerChoiceAccount.getTransactions()); bankBo.sendMoney(customer, customerChoiceAccount, newTransaction); } else System.err.println("Customer do not exist!!"); } private void deductBalance(Account customerChoiceAccount, Transaction accountTransaction) { double fee = accountTransaction.getFee(); double amount = accountTransaction.getAmount(); double accountBalance = customerChoiceAccount.getAccountBalance(); customerChoiceAccount.setAccountBalance(accountBalance - amount- fee); } private Transaction doTransaction() { Scanner sc = getScannerInstance(); System.out.println("Receiver Firstname"); String receiverName = sc.nextLine(); System.out.println("Receiver Lastname"); String lastName = sc.nextLine(); System.out.println("Amount to transfer"); double amount = sc.nextDouble(); double fee = amount*.1; System.out.println("Fee : " + fee); return new Transaction(receiverName, lastName, amount, fee, new Date()); } private Account getAccountChoice(Customer customer) { Account account = null; if (doesCustomerHasAccount(customer)) { displayAccountOptions(customer); Scanner scan = getScannerInstance(); int accountChoice = scan.nextInt(); account = customer.getAccounts().get(accountChoice - 1); } return account; } private boolean doesCustomerHasAccount(Customer customer) { if (customer.getAccounts().size() < 1) { System.out.println("Customer does not have accounts"); return false; } return true; } private void displayAccountOptions(Customer customer) { System.out.println("Please choose account to send money:"); int counter = 1; for (Account account : customer.getAccounts()) { System.out.println(counter + "." + account.getAccountType() + "(" + account.getAccountNumber() + ")"); counter++; } } private void CreateTransaction(Customer customer, Account accountType, Double amountToSend) { Scanner inputTransaction = new Scanner(System.in); List<Account> customerAccounts = customer.getAccounts(); for (Account cusAcc : customerAccounts) { Double balance = cusAcc.getAccountBalance(); System.out.println(balance); System.out.println("Enter the Amount to send"); Double amountToTransfer = inputTransaction.nextDouble(); System.out.println("Final balance of the account:" + (balance - amountToTransfer)); } } private void addMoreCustomer() { Customer customer = retrieveCustomerObjectFromCustomerInput(); bankBo.addCustomer(customer); bankBo.printBankStatus(); } private Customer retrieveCustomerObjectFromCustomerInput() { Scanner input = new Scanner(System.in); System.out.println("Enter Customer First Name"); String firstName = input.nextLine(); System.out.println("Enter Customer Last Name"); String lastName = input.nextLine(); System.out.println("Enter Customer Address in Format (streetname,zipcode,city,statecode)"); String streetName = input.nextLine(); String zipCode = input.nextLine(); String city = input.nextLine(); String stateCode = input.nextLine(); System.out.println("Enter your Social Security"); String ssn = input.nextLine(); return new Customer(firstName, lastName, new Address(streetName, zipCode, city, stateCode), ssn); } private Scanner getScannerInstance() { return new Scanner(System.in); } private static void displayOption() { System.out.println("choose from the Menu below"); System.out.println("1. Add Customer"); System.out.println("2. Add Account"); System.out.println("3. Send Money"); System.out.println("4. Print Bank Status"); System.out.println("5. Print all customer by state"); System.out.println("6. Exit"); } }
true
37c14dec499f1bc5275fec1125e320585cd63eaf
Java
Terasology/MasterOfOreon
/src/main/java/org/terasology/taskSystem/assignment/BestFitStrategy.java
UTF-8
1,726
2.609375
3
[]
no_license
// Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.taskSystem.assignment; import org.terasology.engine.entitySystem.entity.EntityRef; import org.terasology.spawning.OreonAttributeComponent; import org.terasology.taskSystem.OreonAttributes; import org.terasology.taskSystem.Task; import org.terasology.taskSystem.components.TaskComponent; import java.util.Queue; public class BestFitStrategy implements AssignmentStrategy { @Override public EntityRef getBestTask(OreonAttributeComponent attributes, Queue<EntityRef> tasks) { int bestScore = Integer.MAX_VALUE; EntityRef bestTask = null; if (!tasks.isEmpty()) { while (!tasks.isEmpty()) { EntityRef taskEntity = tasks.remove(); Task task = taskEntity.getComponent(TaskComponent.class).task; int score = calculateTaskSuitability(task.recommendedAttributes, attributes); if (score >= 0 && score < bestScore) { bestScore = score; bestTask = taskEntity; } } } return bestTask; } private int calculateTaskSuitability(OreonAttributes target, OreonAttributeComponent attributes) { // The suitability rating is the arithmetic mean of the difference between the current value and the target value // Smaller scores are better return ((attributes.intelligence - target.intelligence) + (attributes.strength - target.strength) + (attributes.health - target.health) + (attributes.hunger - target.hunger)) / 4; } }
true
041082f7bbd6fb4f3f916bab5aa2f0775389a4f0
Java
singhsurya1012/Competitive-Programming
/LeetCode/src/medium/MaximumAreaOfAPieceOfCakeAfterHorizontalAndVerticalCuts.java
UTF-8
1,581
3.171875
3
[]
no_license
package medium; import java.util.Arrays; public class MaximumAreaOfAPieceOfCakeAfterHorizontalAndVerticalCuts { int mod = 1000000007; public int maxArea(int h, int w, int[] hc, int[] vc) { Arrays.sort(hc); Arrays.sort(vc); //return maxAreaBruteForce(h,w, hc,vc); int maxH = Math.max(hc[0],h-hc[hc.length-1]); int maxV = Math.max(vc[0], w-vc[vc.length-1]); for(int i=1;i<hc.length;i++){ maxH = Math.max(maxH, hc[i]-hc[i-1]); } for(int i=1;i<vc.length;i++){ maxV = Math.max(maxV, vc[i]-vc[i-1]); } return calculateArea(maxH,maxV); } public int maxAreaBruteForce(int h, int w, int[] hc, int[] vc){ int maxArea = 0; int x = 0; int y = 0; for(int i: hc){ int b = i-x; int l = 0; int area = 0; for(int j: vc){ l = j-y; maxArea = Math.max(calculateArea(l,b),maxArea); y = j; } //last piece l = w-y; maxArea = Math.max(calculateArea(l,b),maxArea); //reset x and y; x = i; y = 0; } //last bottom piece for(int i:vc){ maxArea = Math.max(calculateArea(h-x,i-y),maxArea); y= i; } maxArea = Math.max(calculateArea(h-x,w-y),maxArea); return maxArea; } public int calculateArea(int l, int b){ long area = (1l*l*b)%mod; return (int)area; } }
true
f627967c72770f9f107f9d1edca56781f3da1db8
Java
msmtmsmt123/jadx-1
/f737922a0ddc9335bb0fc2f3ae5ffe93_source_from_JADX/android/support/v4/hardware/display/DisplayManagerCompat.java
UTF-8
807
1.757813
2
[]
no_license
package android.support.v4.hardware.display; import android.content.Context; import android.view.WindowManager; import java.util.WeakHashMap; public abstract class DisplayManagerCompat { private static final WeakHashMap<Context, DisplayManagerCompat> j6; private static class JellybeanMr1Impl extends DisplayManagerCompat { private final Object j6; public JellybeanMr1Impl(Context context) { this.j6 = a.j6(context); } } private static class LegacyImpl extends DisplayManagerCompat { private final WindowManager j6; public LegacyImpl(Context context) { this.j6 = (WindowManager) context.getSystemService("window"); } } static { j6 = new WeakHashMap(); } DisplayManagerCompat() { } }
true
a113760c8549c87b27af61822631f36d133a5276
Java
moutainhigh/necmc
/src/main/java/com/sv/mc/controller/ReportController.java
UTF-8
5,417
2
2
[ "Apache-2.0" ]
permissive
package com.sv.mc.controller; import com.sv.mc.pojo.*; import com.sv.mc.repository.DeviceRepository; import com.sv.mc.repository.OrderRepository; import com.sv.mc.service.DeviceService; import com.sv.mc.service.OrderService; import com.sv.mc.service.ReportService; import org.apache.catalina.servlet4preview.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletResponse; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; /** * 销售报表统计查询controller * @auther liaozhiqiang * @date 2018/7/11 */ @Controller @RequestMapping("/saleReport") public class ReportController { @Autowired private ReportService reportService; @Autowired private OrderService orderService; @Autowired private OrderRepository orderRepository; @Autowired private DeviceService deviceService; @Autowired private DeviceRepository deviceRepository; /** * 跳转到报表查询条件页面 * @return View销售报表 * @auther liaozhiqiang * @date 2018/7/11 */ @GetMapping(value="/reportCondition") public ModelAndView turnToReportCondition(){ return new ModelAndView("./report/reportCondition"); } /** * 查询所有省份 * @return 所有省份数据 * @auther liaozhiqiang * @date 2018/7/11 */ @RequestMapping(value="/queryAllProvince") @ResponseBody public List<ProvinceEntity> queryAllProvince(){ return this.reportService.queryAllProvince(); } /** * 根据省份id查询市 * @param provinceId 省id * @return 市信息 * @auther liaozhiqiang * @date 2018//7/11 */ @RequestMapping(value="/queryAllCityByProId") @ResponseBody public List<CityEntity> queryAllCityByProId(int provinceId){ return this.reportService.queryAllCityByProId(provinceId); } /** * 根据市id查询场地 * @param cityId 市Id * @return 场地信息集合 * @auther liaozhiqiang * @date 2018//7/11 */ @RequestMapping(value="/queryAllPlaceByCityId") @ResponseBody public List<PlaceEntity> queryAllPlaceByCityId(int cityId){ return this.reportService.queryAllPlaceByCityId(cityId); } /** * 点击[生成报表]按钮后,获取页面数据 * @param reportParamEntity 报表对象 * @return 订单信息集合 */ @RequestMapping(value="/getReportCondition") @ResponseBody public List<OrderEntity> getReportCondition(ReportParamEntity reportParamEntity){ List<OrderEntity> orderEntityList = new ArrayList<>(); System.out.println(reportParamEntity.getProvinceId()); // System.out.println(reportParamEntity.getEndTime()); BigDecimal totalIncome = this.orderRepository.findTotalIncomeByTime(reportParamEntity.getStartTime(),reportParamEntity.getEndTime());//查询时间段内的总收入 // System.out.println(totalIncome); int totalNormalChairCount = this.deviceRepository.findNormalDeviceTotalCount();//按摩椅正常数量 // System.out.println(totalNormalChairCount); int totalFaultChairCount = this.deviceRepository.findFaultDeviceTotalCount(); //按摩椅异常数量 // System.out.println(totalFaultChairCount); int totalLaunchChairCount = this.deviceRepository.findLaunchChairCount(reportParamEntity.getStartTime(),reportParamEntity.getEndTime());//设备投放量 // System.out.println(totalLaunchChairCount); int totalFaultInfoCount = this.deviceRepository.findFaultInfoCount();//异常信息数量 // System.out.println(totalFaultInfoCount); String[] timeData = reportParamEntity.getStartTime().split("/"); String reportMonth = timeData[1]; String reportDay = timeData[2].split(" ")[0]; System.out.println(reportDay); String dailyReportDate = reportParamEntity.getEndTime().substring(0,9); String dailyReportDate2=""; if(Integer.parseInt(reportMonth)>=1 && Integer.parseInt(reportMonth)<10){ //如果月份在1-10 if(Integer.parseInt(reportDay)>=1 && Integer.parseInt(reportDay)<10){//如果日期在1-10 dailyReportDate2 = reportParamEntity.getStartTime().substring(0,8); }else{ dailyReportDate2 = reportParamEntity.getStartTime().substring(0,10); } }else if(Integer.parseInt(reportMonth)>=10 && Integer.parseInt(reportMonth)<=12){//如果月份在11-12 if(Integer.parseInt(reportDay)>=10 && Integer.parseInt(reportDay)<=31){//10-31 dailyReportDate2 = reportParamEntity.getStartTime().substring(0,10); }else{ dailyReportDate2 = reportParamEntity.getStartTime().substring(0,9); } } System.out.println(dailyReportDate); System.out.println(dailyReportDate2); return orderEntityList; } }
true
b746d3fd90c7bb19ed6108674d6654a521d63feb
Java
mmosalam217/expleoAssignment
/Staff/src/main/java/com/ExpleoGroup/Staff/Entities/QEEmployee.java
UTF-8
1,874
2.546875
3
[]
no_license
package com.ExpleoGroup.Staff.Entities; import java.util.Date; import com.ExpleoGroup.Staff.Types.IQEEmployee; public class QEEmployee extends QAEmployee implements IQEEmployee{ private Boolean isCareerManager; private int countOfEmployeesReportingToHim; public QEEmployee() { } public QEEmployee(String firstname, String lastname, Date hiringDate, int teamNumber, int countOfEmployeesReportingToHim) { super(firstname, lastname, hiringDate, teamNumber); this.countOfEmployeesReportingToHim = countOfEmployeesReportingToHim; } public Boolean getIsCareerManager() { return isCareerManager; } public void setIsCareerManager(Boolean isCareerManager) { this.isCareerManager = isCareerManager; } public int getCountOfEmployeesReportingToHim() { return countOfEmployeesReportingToHim; } public void setCountOfEmployeesReportingToHim(int countOfEmployeesReportingToHim) { this.countOfEmployeesReportingToHim = countOfEmployeesReportingToHim; } @Override public void executeTests() { System.out.println("QE started executing testcases..."); } @Override public void reviewTestExecution() { System.out.println("QE is now reviewing test execution of his colleagues...."); } @Override public String sendExecutionReport() { return "Execution Report \n" + "Total TCs: 30, Passed: 18, Failed: 12"; } @Override public String toString() { return "QEEmployee [isCareerManager: " + isCareerManager + ", countOfEmployeesReportingToHim: " + countOfEmployeesReportingToHim + ", assigned Projects: " + getAssignedProjects() + ", Team Number: " + getTeamNumber() + ", Last Signed In: " + getLastSignedIn() + ", Last Signed Out: " + getLastSignedOut() + ", Firstname: " + getFirstname() + ", Lastname :" + getLastname() + ", Hiring-Date: " + getHiringDate() + ", isResigned: " + getIsResigned() + "]"; } }
true
4a7dde9a7bdcab601ec71b2c9ef93f97ebcb5458
Java
ZOUANI/-ecom-back-v2
/src/main/java/ma/zs/generated/ws/rest/provided/vo/ProductVo.java
UTF-8
5,127
2.28125
2
[]
no_license
package ma.zs.generated.ws.rest.provided.vo; import java.util.List; import java.math.BigDecimal; public class ProductVo { private String size; private String qteStock; private String label; private String weight; private String color; private String price; private String reference; private String id; private Long units; private BigDecimal sales; private List<OrderLineVo> orderLinesVo; private String qteStockMax; private String qteStockMin; private String weightMax; private String weightMin; private String priceMax; private String priceMin; private Long totalCommands; private Long totalAmountConfirmed; private Long totalAmountDelivered; private Long totalCommandsReturned; private BigDecimal pricee; public ProductVo(String label, BigDecimal pricee, Long units) { this.label = label; this.pricee = pricee; this.units = units; this.sales = pricee.multiply(new BigDecimal(units)); } public ProductVo(String label, Long totalCommands, Long totalAmountConfirmed, Long totalAmountDelivered, Long totalCommandsReturned) { this.label = label; this.totalCommands = totalCommands; this.totalAmountConfirmed = totalAmountConfirmed; this.totalAmountDelivered = totalAmountDelivered; this.totalCommandsReturned = totalCommandsReturned; } public BigDecimal getSales() { return sales; } public BigDecimal getPricee() { return pricee; } public void setPricee(BigDecimal pricee) { this.pricee = pricee; } public Long getTotalCommands() { return totalCommands; } public void setTotalCommands(Long totalCommands) { this.totalCommands = totalCommands; } public Long getUnits() { return units; } public void setUnits(Long units) { this.units = units; } public void setSales(BigDecimal sales) { this.sales = sales; } public Long getTotalAmountConfirmed() { return totalAmountConfirmed; } public void setTotalAmountConfirmed(Long totalAmountConfirmed) { this.totalAmountConfirmed = totalAmountConfirmed; } public Long getTotalAmountDelivered() { return totalAmountDelivered; } public void setTotalAmountDelivered(Long totalAmountDelivered) { this.totalAmountDelivered = totalAmountDelivered; } public Long getTotalCommandsReturned() { return totalCommandsReturned; } public void setTotalCommandsReturned(Long totalCommandsReturned) { this.totalCommandsReturned = totalCommandsReturned; } public ProductVo() { super(); } public String getSize() { return this.size; } public void setSize(String size) { this.size = size; } public String getQteStock() { return this.qteStock; } public void setQteStock(String qteStock) { this.qteStock = qteStock; } public String getLabel() { return this.label; } public void setLabel(String label) { this.label = label; } public String getWeight() { return this.weight; } public void setWeight(String weight) { this.weight = weight; } public String getColor() { return this.color; } public void setColor(String color) { this.color = color; } public String getPrice() { return this.price; } public void setPrice(String price) { this.price = price; } public String getReference() { return this.reference; } public void setReference(String reference) { this.reference = reference; } public String getId() { return this.id; } public void setId(String id) { this.id = id; } public String getQteStockMax() { return this.qteStockMax; } public String getQteStockMin() { return this.qteStockMin; } public void setQteStockMax(String qteStockMax) { this.qteStockMax = qteStockMax; } public void setQteStockMin(String qteStockMin) { this.qteStockMin = qteStockMin; } public String getWeightMax() { return this.weightMax; } public String getWeightMin() { return this.weightMin; } public void setWeightMax(String weightMax) { this.weightMax = weightMax; } public void setWeightMin(String weightMin) { this.weightMin = weightMin; } public String getPriceMax() { return this.priceMax; } public String getPriceMin() { return this.priceMin; } public void setPriceMax(String priceMax) { this.priceMax = priceMax; } public void setPriceMin(String priceMin) { this.priceMin = priceMin; } public List<OrderLineVo> getOrderLinesVo() { return this.orderLinesVo; } public void setOrderLinesVo(List<OrderLineVo> orderLinesVo) { this.orderLinesVo = orderLinesVo; } }
true
f27c39d3fe1cb9936330c4245df30c234e948237
Java
DevB007/Capstone-Stage-2---Build
/app/src/main/java/com/example/deveshwar/imalive/ReminderComposerActivity.java
UTF-8
11,046
2.109375
2
[]
no_license
package com.example.deveshwar.imalive; import android.content.Intent; import android.database.Cursor; import android.graphics.Typeface; import android.net.Uri; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.ImageView; import org.json.JSONException; import org.json.JSONObject; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnCheckedChanged; public class ReminderComposerActivity extends AppCompatActivity implements TimePickerFragment .OnTimeSetListener { private Intent intentExtras; @BindView(R.id.save_reminder_fab) FloatingActionButton saveReminderFAB; @BindView(R.id.reminder_time_picker_button) Button reminderTimePickerButton; @BindView(R.id.reminder_delete_button) Button reminderDeleteButton; @BindView(R.id.reminder_message) EditText reminderMessage; @BindView(R.id.message_delivery_day_sunday_button) CheckBox reminderDeliveryDaySundayButton; @BindView(R.id.message_delivery_day_monday_button) CheckBox reminderDeliveryDayMondayButton; @BindView(R.id.message_delivery_day_tuesday_button) CheckBox reminderDeliveryDayTuesdayButton; @BindView(R.id.message_delivery_day_wednesday_button) CheckBox reminderDeliveryDayWednesdayButton; @BindView(R.id.message_delivery_day_thursday_button) CheckBox reminderDeliveryDayThursdayButton; @BindView(R.id.message_delivery_day_friday_button) CheckBox reminderDeliveryDayFridayButton; @BindView(R.id.message_delivery_day_saturday_button) CheckBox reminderDeliveryDaySaturdayButton; @BindView(R.id.toolbar) Toolbar toolbar; @BindView(R.id.contact_photo) ImageView contactPhotoIv; private String contactName; private String contactNumber; private String contactPhoto; private boolean isEditing; private Reminder reminder; private String reminderDeliveryTime; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_reminder_composer); ButterKnife.bind(this); intentExtras = getIntent(); if (intentExtras.hasExtra("reminderId")) { isEditing = true; final Cursor cur = getContentResolver().query( RemindersContract.buildReminderUri( intentExtras.getIntExtra("reminderId", -1)), null, null, null, null); cur.moveToFirst(); reminder = Reminder.from(cur); cur.close(); if (reminder != null) { reminderDeleteButton.setVisibility(View.VISIBLE); reminderDeleteButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getContentResolver().delete( RemindersContract.buildReminderUri( intentExtras.getIntExtra("reminderId", -1)), null, null); finish(); } }); contactName = reminder.getContactName(); contactNumber = reminder.getContactNumber(); contactPhoto = reminder.getContactPhoto(); reminderMessage.setText(reminder.getText()); reminderDeliveryTime = reminder.getDeliveryTime(); reminderTimePickerButton.setText(Util.getHumanFormattedTime(reminderDeliveryTime)); JSONObject deliveryDays; try { deliveryDays = new JSONObject(reminder.getDeliveryDays()); if (!deliveryDays.getBoolean("Sunday")) { reminderDeliveryDaySundayButton.setChecked(false); } if (!deliveryDays.getBoolean("Monday")) { reminderDeliveryDayMondayButton.setChecked(false); } if (!deliveryDays.getBoolean("Tuesday")) { reminderDeliveryDayTuesdayButton.setChecked(false); } if (!deliveryDays.getBoolean("Wednesday")) { reminderDeliveryDayWednesdayButton.setChecked(false); } if (!deliveryDays.getBoolean("Thursday")) { reminderDeliveryDayThursdayButton.setChecked(false); } if (!deliveryDays.getBoolean("Friday")) { reminderDeliveryDayFridayButton.setChecked(false); } if (!deliveryDays.getBoolean("Saturday")) { reminderDeliveryDaySaturdayButton.setChecked(false); } } catch (JSONException e) { e.printStackTrace(); } } } else { contactName = intentExtras.getStringExtra("contactName"); contactNumber = intentExtras.getStringExtra("contactNumber"); contactPhoto = intentExtras.getStringExtra("contactPhoto"); } toolbar.setTitle(contactName); setSupportActionBar(toolbar); if (contactPhoto != null) { contactPhotoIv.setImageURI(Uri.parse(contactPhoto)); } saveReminderFAB.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (!isMessageCompositionValid()) { return; } if (!isEditing) { reminder = new Reminder(); reminder.setContactName(contactName); reminder.setContactNumber(contactNumber); reminder.setContactPhoto(contactPhoto); } reminder.setText(reminderMessage.getText().toString()); reminder.setDeliveryTime(reminderDeliveryTime); reminder.setDeliveryDays(getReminderDeliveryDays()); if (!isEditing) { // insert getContentResolver().insert(RemindersContract.ReminderEntry.CONTENT_URI, reminder.toContentValues()); } else { getContentResolver().update(RemindersContract.buildReminderUri(reminder.getId()), reminder.toContentValues(), null, null); // update } String deliveryTime[] = reminder.getDeliveryTime().split(":"); int hour = Integer.parseInt(deliveryTime[0]); int minute = Integer.parseInt(deliveryTime[1]); Util.setAlarm(ReminderComposerActivity.this, hour, minute); finish(); } }); reminderTimePickerButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TimePickerFragment timerPickerFragment = new TimePickerFragment(); timerPickerFragment.bind(ReminderComposerActivity.this); timerPickerFragment.show(getFragmentManager(), "timePicker"); } }); } @OnCheckedChanged({R.id.message_delivery_day_sunday_button, R.id.message_delivery_day_monday_button, R.id.message_delivery_day_tuesday_button, R.id.message_delivery_day_wednesday_button, R.id.message_delivery_day_thursday_button, R.id.message_delivery_day_friday_button, R.id.message_delivery_day_saturday_button}) public void onReminderDeliveryDayCheckChanged(CompoundButton buttonView, boolean isChecked ) { if (!isChecked) { buttonView.setTextColor(getResources().getColor(R.color.colorPrimaryText)); buttonView.setBackgroundResource(R.drawable.reminder_day_background_transparent); buttonView.setTypeface(Typeface.DEFAULT); } else { buttonView.setTextColor(getResources().getColor(android.R.color.white)); buttonView.setBackgroundResource(R.drawable.reminder_day_background); buttonView.setTypeface(Typeface.DEFAULT_BOLD); } } @Override public void onTimeSet(int hh, int mm) { reminderDeliveryTime = Util.getFormattedTime(hh, mm); reminderTimePickerButton.setText(Util.getHumanFormattedTime(reminderDeliveryTime)); } public boolean isMessageCompositionValid() { String messageTextStr = reminderMessage.getText().toString(); if (!(reminderDeliveryDaySundayButton.isChecked() || reminderDeliveryDayMondayButton.isChecked() || reminderDeliveryDayTuesdayButton.isChecked() || reminderDeliveryDayWednesdayButton.isChecked() || reminderDeliveryDayThursdayButton.isChecked() || reminderDeliveryDayFridayButton.isChecked() || reminderDeliveryDaySaturdayButton .isChecked())) { Snackbar.make(saveReminderFAB, getString(R.string.error_invalid_reminder_day) + " " + contactName, Snackbar.LENGTH_LONG).show(); return false; } if (reminderDeliveryTime == null) { Snackbar.make(saveReminderFAB, getString(R.string.error_invalid_reminder_time) + " " + contactName, Snackbar.LENGTH_LONG).show(); return false; } if (!(messageTextStr.length() > 0)) { Snackbar.make(saveReminderFAB, getString(R.string.error_invalid_reminder_message) + " " + contactName, Snackbar.LENGTH_LONG).show(); return false; } return true; } private String getReminderDeliveryDays() { JSONObject reminderDeliveryDays = new JSONObject(); try { reminderDeliveryDays.put("Sunday", reminderDeliveryDaySundayButton.isChecked()); reminderDeliveryDays.put("Monday", reminderDeliveryDayMondayButton.isChecked()); reminderDeliveryDays.put("Tuesday", reminderDeliveryDayTuesdayButton.isChecked()); reminderDeliveryDays.put("Wednesday", reminderDeliveryDayWednesdayButton.isChecked()); reminderDeliveryDays.put("Thursday", reminderDeliveryDayThursdayButton.isChecked()); reminderDeliveryDays.put("Friday", reminderDeliveryDayFridayButton.isChecked()); reminderDeliveryDays.put("Saturday", reminderDeliveryDaySaturdayButton.isChecked()); } catch (JSONException e) { e.printStackTrace(); } return reminderDeliveryDays.toString(); } }
true
c5873bebe18fa7c7162ef4792fed7900db81385a
Java
ZJHqs/ServicesRental
/src/View/Customer/ShowInformationView.java
UTF-8
1,710
2.59375
3
[]
no_license
package View.Customer; import Controller.Customer; import javax.swing.*; public class ShowInformationView { JFrame jFrame=new JFrame("查看个人信息"); JPanel jPanel=new JPanel(null); JLabel cid=new JLabel("用户名:"); JLabel cname=new JLabel("用户昵称:"); JLabel password=new JLabel("密码:"); JLabel phone=new JLabel("联系电话:"); JTextField idtext=new JTextField(20); JTextField nametext=new JTextField(20); JTextField passwordtext=new JPasswordField(20); JTextField phonetext=new JTextField(20); public void init() { jFrame.setSize(400,300); cid.setBounds(10,20,80,25); idtext.setBounds(100,20,165,25); cname.setBounds(10,50,80,25); nametext.setBounds(100,50,165,25); password.setBounds(10,80,80,25); passwordtext.setBounds(100,80,165,25); phone.setBounds(10,110,80,25); phonetext.setBounds(100,110,165,25); Customer customer = Customer.getCustomer(); idtext.setText(customer.getCid()); nametext.setText(customer.getCnmae()); passwordtext.setText(customer.getPassword()); phonetext.setText(customer.getPhone()); idtext.setEditable(false); nametext.setEditable(false); passwordtext.setEditable(false); phonetext.setEditable(false); jPanel.add(cid); jPanel.add(idtext); jPanel.add(cname); jPanel.add(nametext); jPanel.add(password); jPanel.add(passwordtext); jPanel.add(phone); jPanel.add(phonetext); jFrame.add(jPanel); jFrame.setVisible(true); jFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } }
true
cd2d195ca66163defcf39cac9066ffdc456900db
Java
thiagoalvescosta/neonews-studio
/src/main/java/com/in9midia/studio/data/entity/ContentAnswerReport.java
UTF-8
3,188
2.34375
2
[]
no_license
package com.in9midia.studio.data.entity; import java.io.*; import javax.persistence.*; import java.util.*; import javax.xml.bind.annotation.*; import java.util.Date; /** * Classe que representa a tabela CMS_CONTENT_ANSWER_REPORT * @generated */ @Entity @Table(name = "\"CMS_CONTENT_ANSWER_REPORT\"" ) @XmlRootElement public class ContentAnswerReport implements Serializable { /** * UID da classe, necessário na serialização * @generated */ private static final long serialVersionUID = 895919509l; /** * @generated */ @ManyToOne @JoinColumn(name="CON_ID", referencedColumnName = "CON_ID") private Content content; /** * @generated */ @ManyToOne @JoinColumn(name="CCQ_ID", referencedColumnName = "CCQ_ID") private ContentAnswerQuiz contentAnswerQuiz; /** * @generated */ @Temporal(TemporalType.TIMESTAMP) @Column(name = "ccqr_date", nullable = false, unique = false) private Date date; /** * @generated */ @Id @Column(name = "ccqr_id") private java.lang.String id = UUID.randomUUID().toString().toUpperCase(); /** * Construtor * @generated */ public ContentAnswerReport(){ } /** * Obtém content * @param content content * return content * @generated */ public Content getContent(){ return this.content; } /** * Define content * @param content content * @generated */ public ContentAnswerReport setContent(Content content){ this.content = content; return this; } /** * Obtém contentAnswerQuiz * @param contentAnswerQuiz contentAnswerQuiz * return contentAnswerQuiz * @generated */ public ContentAnswerQuiz getContentAnswerQuiz(){ return this.contentAnswerQuiz; } /** * Define contentAnswerQuiz * @param contentAnswerQuiz contentAnswerQuiz * @generated */ public ContentAnswerReport setContentAnswerQuiz(ContentAnswerQuiz contentAnswerQuiz){ this.contentAnswerQuiz = contentAnswerQuiz; return this; } /** * Obtém date * @param date date * return date * @generated */ public Date getDate(){ return this.date; } /** * Define date * @param date date * @generated */ public ContentAnswerReport setDate(Date date){ this.date = date; return this; } /** * Obtém id * @param id id * return id * @generated */ public java.lang.String getId(){ return this.id; } /** * Define id * @param id id * @generated */ public ContentAnswerReport setId(java.lang.String id){ this.id = id; return this; } /** * @generated */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } /** * @generated */ @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(!(obj instanceof ContentAnswerReport)) return false; ContentAnswerReport other = (ContentAnswerReport)obj; if(this.id == null && other.id != null) return false; else if(!this.id.equals(other.id)) return false; return true; } }
true
7619ef4d2943b04f7c5ca1f354232b658bb2bb21
Java
chiendarrendor/AlbertsAdalogicalAenigmas
/addenda-9/src/CellColorPairLogicStep.java
UTF-8
1,476
3.109375
3
[ "MIT" ]
permissive
import grid.logic.LogicStatus; import grid.logic.LogicStep; public class CellColorPairLogicStep implements LogicStep<Board> { int x1; int y1; int x2; int y2; public CellColorPairLogicStep(int x1, int y1, int x2, int y2) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; } public LogicStatus apply(Board thing) { CellColor c1 = thing.getCellColor(x1,y1); CellColor c2 = thing.getCellColor(x2,y2); // 9 cases // c1 // BLACK WHITE ? // c2 BLACK x ok c1=WHITE // WHITE ok x c1=BLACK // ? c2=WHITE c2=BLACK ? if (c1 == CellColor.UNKNOWN && c2 == CellColor.UNKNOWN) return LogicStatus.STYMIED; if (c1 == CellColor.BLACK && c2 == CellColor.WHITE) return LogicStatus.STYMIED; if (c1 == CellColor.WHITE && c2 == CellColor.BLACK) return LogicStatus.STYMIED; if (c1 == CellColor.WHITE && c2 == CellColor.WHITE) return LogicStatus.CONTRADICTION; if (c1 == CellColor.BLACK && c2 == CellColor.BLACK) return LogicStatus.CONTRADICTION; if (c1 == CellColor.UNKNOWN) { thing.setCellColor(x1,y1,c2 == CellColor.BLACK ? CellColor.WHITE : CellColor.BLACK); return LogicStatus.LOGICED; } thing.setCellColor(x2,y2,c1 == CellColor.BLACK ? CellColor.WHITE : CellColor.BLACK); return LogicStatus.LOGICED; } }
true
97cff1aacbaede41a55bca9b6b7cf56dacdda05d
Java
HaoranJ/Algorithm_and_Design
/MaximumProductArray.java
UTF-8
718
3.265625
3
[]
no_license
import java.util.*; //LeetCode 152, //time = o(n), space = constant public class MaximumProductArray{ public static int maxProduct(int[] nums) { assert nums != null; if (nums.length == 0) { return 0; } int maxSofar = Integer.MIN_VALUE; int minEndHere = 1; int maxEndHere = 1; for (int i = 0; i < nums.length; i++) { int cur = nums[i]; int temp = maxEndHere; maxEndHere = Math.max(cur * maxEndHere, Math.max(cur, cur * minEndHere)); minEndHere = Math.min(cur * minEndHere, Math.min(cur, cur * temp)); maxSofar = Math.max(maxSofar, maxEndHere); } return maxSofar; } public static void main(String[] args) { int[] arr = {2,3,-2,-4}; System.out.println(maxProduct(arr)); } }
true
a821c0555912006f1458c85a604860ea41b78916
Java
armandodelcol-coder/efficient-training
/src/main/java/br/com/armando/efficienttraining/api/model/input/TaskInput.java
UTF-8
658
1.953125
2
[]
no_license
package br.com.armando.efficienttraining.api.model.input; import lombok.Getter; import lombok.Setter; import javax.validation.Valid; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; @Getter @Setter public class TaskInput { @NotBlank private String name; @NotBlank private String description; @Max(value = 3) @Min(value = 1) @NotNull private Integer complexityLevel; private String observation; @Valid @NotNull private ProjectIdInput project; }
true
7e0a2cc052f40cd1653cf85e955f2057f7fd0e97
Java
sshpark/ETreeLearning
/src/learning/controls/initializers/SetMinDelayMatrixForProtocol.java
UTF-8
2,930
2.578125
3
[ "MIT" ]
permissive
package learning.controls.initializers; import learning.interfaces.AbstractProtocol; import learning.node.ETreeNode; import learning.protocols.FederatedLearningProtocol; import learning.topology.TopoUtil; import peersim.config.Configuration; import peersim.core.Control; import peersim.core.Network; import peersim.core.Protocol; import java.io.FileWriter; import java.io.IOException; /** * The minDelayMatrix is set up for the protocol of each node * because of the high cost of generating the mindelay matrix. * @author sshpark * @date 20/2/2020 */ public class SetMinDelayMatrixForProtocol implements Control { private static final String PAR_PROT = "protocol"; private final int pid; private final String topoFilePath; private int[][] graph; private int[][] minDelayMatrix; public SetMinDelayMatrixForProtocol(String prefix) { pid = Configuration.getPid(prefix + "." + PAR_PROT); topoFilePath = Configuration.getString("TOPO_FILEPATH"); graph = TopoUtil.getGraph(Network.size(), topoFilePath); minDelayMatrix = TopoUtil.generateMinDelayMatrix(graph); } @Override public boolean execute() { outputDelay(); for (int i = 0; i < Network.size(); i++) { Protocol abstractProtocolP = Network.get(i).getProtocol(pid); if (abstractProtocolP instanceof AbstractProtocol) { // get the learning protocol AbstractProtocol abstractProtocol = (AbstractProtocol) abstractProtocolP; abstractProtocol.setMinDelayMatrix(minDelayMatrix); } else { throw new RuntimeException("The given protocol in initializer setMinDelayMatrix.protocol is not a Abstract protocol!"); } } return false; } private void outputDelay() { try { String filepath = Configuration.getString("DELAY_OUTPUT_FILEPATH"); FileWriter fileWriter = new FileWriter(filepath); if (filepath.contains("delay_etree")) { for (int id = 0; id < Network.size(); id++) { ETreeNode node = (ETreeNode) Network.get(id); ETreeNode par_node = (ETreeNode) Network.get(node.getParentNode(0)); fileWriter.write(minDelayMatrix[id][node.getParentNode(0)] + " "); fileWriter.write(minDelayMatrix[node.getParentNode(0)][par_node.getParentNode(1)] + " "); } } else { int masterId = FederatedLearningProtocol.getMasterID(); for (int id = 0; id < Network.size(); id++) { if (id != masterId) fileWriter.write(minDelayMatrix[id][masterId] + " "); } } fileWriter.flush(); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } }
true
5046246d97ba97eb2f329fcfb23c169acf602bc8
Java
timoteoponce/paginator
/src/com/github/timoteoponce/paginator/Iterator.java
UTF-8
904
2.859375
3
[ "MIT" ]
permissive
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.github.timoteoponce.paginator; import java.util.Collection; /** * * @param <T> * @author timoteo */ public class Iterator<T> implements java.util.Iterator<Collection<T>> { private final Paginator<T> paginator; private int nextPage = 0; public Iterator(final Paginator<T> paginator) { this.paginator = paginator; } @Override public boolean hasNext() { return paginator.hasNextPage() || nextPage == 0; } @Override public Collection<T> next() { if (nextPage == 0 || paginator.isLastPage()) { paginator.goFirstPage(); }else{ paginator.goNextPage(); } nextPage++; return paginator.getList(); } @Override public void remove() { // do nothing } }
true
66885b0212326f1a266534204e3e58a506735368
Java
giu-fio/GroupMasterApp
/app/src/main/java/it/polito/groupmasterapp/test/DeviceDataSourceStub.java
UTF-8
651
1.960938
2
[]
no_license
package it.polito.groupmasterapp.test; import android.app.Activity; import android.support.annotation.NonNull; import it.polito.groupmasterapp.data.source.DevicesDataSource; import it.polito.groupmasterapp.data.source.device.DeviceDataSource; /** * Created by giuseppe on 13/10/16. */ public class DeviceDataSourceStub implements DeviceDataSource { @Override public void start() { } @Override public void stop() { } @Override public void startDiscovering(@NonNull Activity activity, @NonNull DevicesDataSource.FindDevicesCallback callback) { } @Override public void stopDiscovering() { } }
true
4d07cc952e3683da306f2b5d9cd0b7cc41e8c825
Java
ScureHu/study
/dolphin/src/com/huruilei/designpattern/strategy/QuackBehavior.java
UTF-8
177
2.296875
2
[]
no_license
package com.huruilei.designpattern.strategy; /** * @author: huruilei * @date: 2019/10/31 * @description: * @return */ public interface QuackBehavior { void quack(); }
true
969274f55ca7158fd4020e6e878f3a99a98b7137
Java
moni2305/Gebiss
/biiImageJ3DViewer/bii/isosurface/MeshEditor.java
UTF-8
4,490
2.984375
3
[]
no_license
/** Albert Cardona 2007 * Released under the terms of the latest edition of the General Public License. */ package bii.isosurface; import javax.vecmath.Point3f; import bii.customnode.CustomTriangleMesh; import java.util.ArrayList; import java.util.Hashtable; import java.util.HashSet; import java.util.Iterator; import java.util.List; public class MeshEditor { /** * If the Content instance wraps a mesh, smooth it by the * fraction K (0, 1). */ static public void smooth(final CustomTriangleMesh c, final float K) { final List triangles = c.getMesh(); if (0 != triangles.size() % 3) { System.out.println("MeshEditor.smooth: need a list of points multiple of 3."); return; } // for each unique point, find which other points are linked by one edge to it. // In the triangles List, there are only points, but each sequence of 3 points makes a triangle. final Hashtable ht = new Hashtable(); for (int i=0; i<triangles.size(); i+=3) { // process one triangle at a time Point3f p1 = (Point3f)triangles.get(i); Point3f p2 = (Point3f)triangles.get(i+1); Point3f p3 = (Point3f)triangles.get(i+2); build(p1, p2, p3, ht); build(p2, p3, p1, ht); build(p3, p1, p2, ht); } /* // shrinkage correction works, but generates undesirably unsmooth edges for (Iterator it = ht.values().iterator(); it.hasNext(); ) { PointGroup pg = (PointGroup)it.next(); pg.computeVector(K); } for (Iterator it = ht.values().iterator(); it.hasNext(); ) { PointGroup pg = (PointGroup)it.next(); pg.applyVector(ht); } */ for (Iterator it = ht.values().iterator(); it.hasNext(); ) { PointGroup pg = (PointGroup)it.next(); pg.smoothMembers(K); } // done! } /** Represents one point in 3D space that appears in multiple instances within the triangles list. */ static private class PointGroup { Point3f first; HashSet edges = new HashSet(); ArrayList members = new ArrayList(); // can't be a HashSet, because points will compare as equal float vx, vy, vz; PointGroup(Point3f first) { this.first = first; members.add(first); } void addMember(Point3f p) { members.add(p); } void addEdge(Point3f p) { edges.add(p); } void smoothMembers(float K) { // Compute a vector composed of all vectors to other points with which it shares an edge, and add some fraction of that vector to each member point. vx = 0; vy = 0; vz = 0; for (Iterator it = edges.iterator(); it.hasNext(); ) { Point3f po = (Point3f)it.next(); vx += po.x; vy += po.y; vz += po.z; } int size = edges.size(); vx = (vx/size - first.x) * K; vy = (vy/size - first.y) * K; vz = (vz/size - first.z) * K; for (Iterator it = members.iterator(); it.hasNext(); ) { Point3f m = (Point3f)it.next(); m.x += vx; m.y += vy; m.z += vz; } } void computeVector(float K) { // Compute a vector composed of all vectors to other points with which it shares an edge, and add some fraction of that vector to each member point. vx = 0; vy = 0; vz = 0; for (Iterator it = edges.iterator(); it.hasNext(); ) { Point3f po = (Point3f)it.next(); vx += po.x; vy += po.y; vz += po.z; } int size = edges.size(); vx = (vx/size - first.x) * K; vy = (vy/size - first.y) * K; vz = (vz/size - first.z) * K; } void applyVector(Hashtable ht) { // compute average displacement vector for all neighbors, i.e. edge points float ax=0, ay=0, az=0; int count = 0; for (Iterator it = edges.iterator(); it.hasNext(); ) { PointGroup pg = (PointGroup)ht.get(it.next()); if (null == pg) continue; count++; ax += pg.vx; ay += pg.vy; az += pg.vz; } ax += vx; ay += vy; az += vz; count++; // so count can never be zero ax /= count; ay /= count; az /= count; // apply to each member the smoothing vector minus average neighborhood smoothing vector to avoid shrinking for (Iterator it = members.iterator(); it.hasNext(); ) { Point3f m = (Point3f)it.next(); m.x += vx;// - ax; m.y += vy;// - ay; m.z += vz;// - az; } } } /** Build a list of points that are just one edge away from p1, and store them in the Hashtable. */ static private void build(Point3f p1, Point3f p2, Point3f p3, Hashtable ht) { PointGroup pg = (PointGroup)ht.get(p1); if (null != pg) { pg.addMember(p1); } else { pg = new PointGroup(p1); ht.put(p1, pg); } pg.addEdge(p2); pg.addEdge(p3); } }
true
d75194bf4760b39f4fd4ef7a1f995a2b347fa7b6
Java
jeremiahsuess/repo
/charlie/capstone-charlie/src/main/java/com/techelevator/studentprofile/model/Portfolio.java
UTF-8
1,443
2.09375
2
[]
no_license
package com.techelevator.studentprofile.model; public class Portfolio { private int portfolioId; private int studentId; private String projectName; private String projectDescription; private String technologyUsed; private String sourceCodeLink; private boolean isGroupProject; public int getPortfolioId() { return portfolioId; } public void setPortfolioId(int portfolioId) { this.portfolioId = portfolioId; } public int getStudentId() { return studentId; } public void setStudentId(int studentId) { this.studentId = studentId; } public String getProjectName() { return projectName; } public void setProjectName(String projectName) { this.projectName = projectName; } public String getProjectDescription() { return projectDescription; } public void setProjectDescription(String projectDescription) { this.projectDescription = projectDescription; } public String getTechnologyUsed() { return technologyUsed; } public void setTechnologyUsed(String technologyUsed) { this.technologyUsed = technologyUsed; } public String getSourceCodeLink() { return sourceCodeLink; } public void setSourceCodeLink(String sourceCodeLink) { this.sourceCodeLink = sourceCodeLink; } public boolean isGroupProject() { return isGroupProject; } public void setGroupProject(boolean isGroupProject) { this.isGroupProject = isGroupProject; } }
true
c575c66ee362b3b5ba201fd722a66c471cad8622
Java
bianjiang/clara
/clara-webapp/src/main/java/edu/uams/clara/webapp/contract/web/ajax/ContractDashboardAjaxController.java
UTF-8
28,245
1.53125
2
[]
no_license
package edu.uams.clara.webapp.contract.web.ajax; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Set; import javax.xml.transform.Source; import org.joda.time.DateTime; import org.joda.time.Minutes; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; 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 org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import edu.uams.clara.webapp.common.businesslogic.BusinessObjectStatusHelperContainer; import edu.uams.clara.webapp.common.dao.history.TrackDao; import edu.uams.clara.webapp.common.dao.usercontext.UserDao; import edu.uams.clara.webapp.common.domain.history.Track; import edu.uams.clara.webapp.common.domain.relation.RelatedObject; import edu.uams.clara.webapp.common.domain.security.MutexLock; import edu.uams.clara.webapp.common.domain.usercontext.User; import edu.uams.clara.webapp.common.domain.usercontext.UserRole; import edu.uams.clara.webapp.common.domain.usercontext.enums.Committee; import edu.uams.clara.webapp.common.domain.usercontext.enums.Permission; import edu.uams.clara.webapp.common.security.MutexLockService; import edu.uams.clara.webapp.common.security.ObjectAclService; import edu.uams.clara.webapp.common.service.audit.AuditService; import edu.uams.clara.webapp.common.service.form.FormService; import edu.uams.clara.webapp.common.service.relation.RelationService; import edu.uams.clara.webapp.common.util.XMLResponseHelper; import edu.uams.clara.webapp.common.util.response.JsonResponse; import edu.uams.clara.webapp.contract.dao.ContractDao; import edu.uams.clara.webapp.contract.dao.businesslogicobject.ContractFormCommitteeStatusDao; import edu.uams.clara.webapp.contract.dao.businesslogicobject.ContractFormStatusDao; import edu.uams.clara.webapp.contract.dao.contractform.ContractFormDao; import edu.uams.clara.webapp.contract.dao.contractform.ContractFormXmlDataDao; import edu.uams.clara.webapp.contract.domain.Contract; import edu.uams.clara.webapp.contract.domain.businesslogicobject.ContractFormCommitteeStatus; import edu.uams.clara.webapp.contract.domain.businesslogicobject.ContractFormStatus; import edu.uams.clara.webapp.contract.domain.businesslogicobject.enums.ContractFormCommitteeStatusEnum; import edu.uams.clara.webapp.contract.domain.businesslogicobject.enums.ContractFormStatusEnum; import edu.uams.clara.webapp.contract.domain.contractform.ContractForm; import edu.uams.clara.webapp.contract.domain.contractform.ContractFormXmlData; import edu.uams.clara.webapp.contract.service.history.ContractTrackService; import edu.uams.clara.webapp.xml.processor.XmlProcessor; @Controller public class ContractDashboardAjaxController { private final static Logger logger = LoggerFactory .getLogger(ContractDashboardAjaxController.class); private ContractDao contractDao; private RelationService relationService; private ContractFormDao contractFormDao; private TrackDao trackDao; private ContractFormXmlDataDao contractFormXmlDataDao; private ContractFormStatusDao contractFormStatusDao; private ContractFormCommitteeStatusDao contractFormCommitteeStatusDao; private XmlProcessor xmlProcessor; private UserDao userDao; private MutexLockService mutexLockService; private AuditService auditService; private ObjectAclService objectAclService; private ContractTrackService contractTrackService; private BusinessObjectStatusHelperContainer businessObjectStatusHelperContainer; private FormService formService; private static final int timeOutPeriod = 45; private List<ContractFormStatusEnum> canEditContractFormStatusLst = new ArrayList<ContractFormStatusEnum>();{ canEditContractFormStatusLst.add(ContractFormStatusEnum.DRAFT); canEditContractFormStatusLst.add(ContractFormStatusEnum.PENDING_PI_ENDORSEMENT); } private String getActionXml(ContractForm contractForm, ContractFormStatus contractFormStatus, ContractFormXmlData lastContractFormXmlData, User u, String formTypeMachineReadable, String xmlResult){ switch (contractFormStatus.getContractFormStatus()) { case UNDER_REVISION: if (objectAclService.hasEditObjectAccess(Contract.class, contractForm.getContract().getId(), u)){ xmlResult += "<action cls='green'><name>Continue Revision</name><url>/contracts/" + contractForm.getContract().getId() + "/contract-forms/" + contractForm.getId() + "/" + formTypeMachineReadable + "/revise?committee=PI</url></action>"; } break; case DRAFT: case PENDING_PI_ENDORSEMENT: if (objectAclService.hasEditObjectAccess(Contract.class, contractForm.getContract().getId(), u) || u.getAuthorities().contains(Permission.DELETE_CONTRACT_DOCUMENT)){ xmlResult += "<action cls='green'><name>Edit "+ contractForm.getContractFormType().getDescription() +"</name><url>/contracts/" + contractForm.getContract().getId() + "/contract-forms/" + contractForm.getId() + "/" + formTypeMachineReadable + "/contract-form-xml-datas/" + lastContractFormXmlData.getId() + "/</url></action>"; } break; case REVISION_REQUESTED: if (objectAclService.hasEditObjectAccess(Contract.class, contractForm.getContract().getId(), u)){ xmlResult += "<action cls='green'><name>Revise</name><url>/contracts/" + contractForm.getContract().getId() + "/contract-forms/" + contractForm.getId() + "/" + formTypeMachineReadable + "/revise?committee=PI</url></action>"; } break; default: break; } return xmlResult; } /** * return a list of forms associated with this contract. the controller will * decide "Action" cell, which defines what the user can do based on the * user's role and rights. * * @param contractId * @return */ @RequestMapping(value = "/ajax/contracts/{contractId}/contract-forms/list.xml", method = RequestMethod.GET) public @ResponseBody String listContractForms(@PathVariable("contractId") long contractId, @RequestParam("userId") long userId) { /* * User u = * (User)SecurityContextHolder.getContext().getAuthentication(). * getPrincipal(); * * for(GrantedAuthority ga:u.getAuthorities()){ * logger.debug(ga.getAuthority()); } */ User user = userDao.findById(userId); List<ContractForm> contractForms = contractDao .listLatestContractFormsByContractId(contractId); logger.debug("size: " + contractForms.size()); String xmlResult = "<list>"; for (ContractForm contractForm : contractForms) { String formTypeMachineReadable = contractForm.getContractFormType() .getUrlEncoded(); ContractFormStatus pformStatus = contractFormStatusDao .getLatestContractFormStatusByFormId(contractForm.getId()); ContractFormXmlData lastContractFormXmlData = contractFormXmlDataDao .getLastContractFormXmlDataByContractFormIdAndType( contractForm.getId(), contractForm .getContractFormType() .getDefaultContractFormXmlDataType()); String index = ""; try { index = xmlProcessor.getAttributeValueByPathAndAttributeName("/contract", contractForm.getMetaDataXml(), "index"); } catch (Exception e) { e.printStackTrace(); } // ContractFormXmlData latestContractFormXmlData = // contractForm.getTypedContractFormXmlDatas().get(contractForm.getContractFormType().getDefaultContractFormXmlDataType()); xmlResult += "<contract-form contractFormId=\"" + contractForm.getId() + "\" lastVersionId=\"" + lastContractFormXmlData.getId() + "\" index=\""+ index +"\">"; xmlResult += "<contract-form-type id=\"" + formTypeMachineReadable + "\">" + contractForm.getContractFormType().getDescription() + "</contract-form-type>"; xmlResult += "<url>/contracts/" + contractForm.getContract().getId() + "/contract-forms/" + contractForm.getId() + "/dashboard</url>"; // xmlResult += "<editurl>/contracts/" + // contractForm.getContract().getId() + "/contract-forms/" + // contractForm.getId() + // "/"+formTypeMachineReadable+"/contract-form-xml-datas/" + // lastContractFormXmlData.getId() + "/</editurl>"; logger.debug("checking who is editing..."); //User editing = mutexLockService.whoIsEditing(ContractForm.class, contractForm.getId()); MutexLock mutexLock = mutexLockService.getLockedByObjectClassAndId(ContractForm.class, contractForm.getId()); Date currentDate = new Date(); Date lastModifiedDate = mutexLock != null?mutexLock.getModified():null; DateTime currentDateTime = new DateTime(currentDate); DateTime lastModifiedDateTime = mutexLock != null?new DateTime(lastModifiedDate):null; String lockedOrNot = "false"; String ifEditingMessage = ""; long editingUserId = (mutexLock!=null)?mutexLock.getUser().getId():0; // if(mutexLock != null){ // // ifEditingMessage= mutexLock.getUser().getPerson().getFullname() + " is editing..."; // // } xmlResult += "<actions>"; if (!mutexLockService.isLockedByObjectClassAndIdForCurrentUser(ContractForm.class, contractForm.getId(), user) ) { xmlResult = getActionXml(contractForm, pformStatus, lastContractFormXmlData, user, formTypeMachineReadable, xmlResult); } else { if (mutexLock != null){ logger.debug("time period after last access: " + Minutes.minutesBetween(lastModifiedDateTime, currentDateTime).getMinutes()); if (Minutes.minutesBetween(lastModifiedDateTime, currentDateTime).getMinutes() > timeOutPeriod){ xmlResult = getActionXml(contractForm, pformStatus, lastContractFormXmlData, user, formTypeMachineReadable, xmlResult); } else { lockedOrNot = "true"; ifEditingMessage= mutexLock.getUser().getPerson().getFullname() + " is editing..."; } } } xmlResult += "<action cls='white'><name>View Summary</name><url>/contracts/" + contractForm.getContract().getId() + "/contract-forms/" + contractForm.getId() + "/" + formTypeMachineReadable + "/summary?noheader=true&amp;review=false</url></action>"; if (user.getAuthorities().contains(Permission.FORWARD_CONTRACT)){ xmlResult += "<action cls='blue'><name>Forward</name><url type='javascript'>Clara.Application.FormController.ForwardSelectedContract();</url></action>"; } if (user.getAuthorities().contains(Permission.CAN_EXECUTE_CONTRACT_AT_ANYTIME)) { xmlResult += "<action cls='blue'><name>Execute Contract</name><url type='javascript'>Clara.Application.FormController.ExecuteForm();</url></action>"; } if (user.getAuthorities().contains(Permission.CAN_UPLOAD_DOCUMENT)){ xmlResult += "<action cls='blue'><name>Upload Document</name><url type='javascript'>Clara.Application.FormController.ChooseUploadDocumentRole({formId:" + contractForm.getId() + "});</url></action>"; } try { List<ContractFormCommitteeStatus> contractFormCommitteeStatusLst = contractFormCommitteeStatusDao .listLatestByContractFormId(contractForm.getId()); ContractFormCommitteeStatus lastestCommitteeStatus = contractFormCommitteeStatusDao.getLatestByCommitteeAndContractFormId(Committee.CONTRACT_MANAGER, contractForm.getId()); if (lastestCommitteeStatus != null && lastestCommitteeStatus.getContractFormCommitteeStatus().equals(ContractFormCommitteeStatusEnum.PENDING_REVIEWER_ASSIGNMENT)){ if (user.getAuthorities().contains(Permission.ROLE_CONTRACT_MANAGER)){ xmlResult += "<action cls='blue'><name>Contract: Assign Reviewer</name><url type='javascript'>Clara.Application.FormController.Assign({roleId:'ROLE_CONTRACT_MANAGER',formTypeId:\'"+ formTypeMachineReadable +"\',formId:" + contractForm.getId() + ",committee:'CONTRACT_MANAGER'},{objectType:'Contract'});</url></action>"; } } if (user.getAuthorities().contains(Permission.ROLE_REVIEWER) && contractFormCommitteeStatusLst != null && !contractFormCommitteeStatusLst.isEmpty()) { xmlResult += "<action cls='blue'><name>Review</name><url type='javascript'>Clara.Application.FormController.ChooseReviewRole({formId:" + contractForm.getId() + "});</url></action>"; for (ContractFormCommitteeStatus cfcs : contractFormCommitteeStatusLst) { if ((cfcs.getCommittee().equals(Committee.CONTRACT_MANAGER) || cfcs.getCommittee().equals(Committee.CONTRACT_LEGAL_REVIEW)) && cfcs.getContractFormCommitteeStatus().equals(ContractFormCommitteeStatusEnum.REVIEWER_ASSIGNED)) { if (user.getAuthorities().contains( Permission.ROLE_CONTRACT_LEGAL_REVIEW)) { xmlResult += "<action cls='blue'><name>Contract: Re-assign Reviewer</name><url type='javascript'>Clara.Application.QueueController.Reassign({roleId:'ROLE_CONTRACT_LEGAL_REVIEW',formTypeId:\'"+ formTypeMachineReadable +"\',formId:" + contractForm.getId() + ",committee:'CONTRACT_LEGAL_REVIEW'},{objectType:'Contract'});</url></action>"; } } } } } catch (Exception e) { e.printStackTrace(); } if (user.getAuthorities().contains(Permission.ROLE_CONTRACT_LEGAL_REVIEW) && !pformStatus.equals(ContractFormStatusEnum.CANCELLED) && lockedOrNot.equals("false")){ xmlResult += "<action cls='red'><name>Cancel</name><url type='javascript'>Clara.Application.FormController.CancelForm();</url></action>"; } if (user.getAuthorities().contains(Permission.DELETE_CONTRACT_FORM_ANY_TIME)) { xmlResult += "<action cls='red'><name>Delete "+ contractForm.getContractFormType().getDescription() +"</name><url type='javascript'>Clara.Application.FormController.RemoveForm();</url></action>"; } xmlResult += "</actions>"; xmlResult += "<status><description>" + org.apache.commons.lang.StringEscapeUtils .escapeXml(pformStatus.getContractFormStatus() .getDescription()) + "</description><modified>" + pformStatus.getModified() + "</modified><lock value=\""+ lockedOrNot +"\" modified=\""+lastModifiedDate+"\" userid=\""+ editingUserId +"\" message=\""+ ifEditingMessage +"\" /></status>"; xmlResult += formService.getAssignedReviewers(contractForm); xmlResult += "</contract-form>"; } xmlResult += "</list>"; return xmlResult; } @RequestMapping(value = "/ajax/contracts/{contractId}/contract-forms/{contractFormId}/get-user-role-list", method = RequestMethod.GET, produces="application/xml") public @ResponseBody Source getUserCommitteeList(@PathVariable("contractFormId") long contractFormId, @RequestParam("userId") long userId){ User currentUser = userDao.findById(userId); String finalCommitteeXml = "<committees>"; try{ List<ContractFormCommitteeStatus> contractFormCommitteeStatusLst = contractFormCommitteeStatusDao.listLatestByContractFormId(contractFormId); List<Committee> reviewCommitteeList = new ArrayList<Committee>(); if (contractFormCommitteeStatusLst != null && !contractFormCommitteeStatusLst.isEmpty()){ for (ContractFormCommitteeStatus cfcs : contractFormCommitteeStatusLst){ if (!cfcs.getCommittee().equals(Committee.PI)){ reviewCommitteeList.add(cfcs.getCommittee()); } } } else { return XMLResponseHelper.newErrorResponseStub("No committee has reviewed this form yet!"); } String committeeXml = ""; if (reviewCommitteeList != null && !reviewCommitteeList.isEmpty()){ for (Committee c : reviewCommitteeList){ if (currentUser.getAuthorities().contains(c.getRolePermissionIdentifier())){ committeeXml += "<committee name=\""+ c.toString() +"\" desc=\""+ c.getDescription() +"\" />"; } } } else { return XMLResponseHelper.newErrorResponseStub(""); } finalCommitteeXml += committeeXml + "</committees>"; return XMLResponseHelper.newDataResponseStub(finalCommitteeXml); } catch (Exception e){ e.printStackTrace(); return XMLResponseHelper.newErrorResponseStub("Failed to load committee list!"); } } @RequestMapping(value = "/ajax/contracts/{contractId}/contract-forms/{contractFormId}/contract-executed", method = RequestMethod.POST, produces="application/xml") public @ResponseBody Source executeContract(@PathVariable("contractFormId") long contractFormId, @RequestParam("userId") long userId, @RequestParam("note") String note){ User currentUser = userDao.findById(userId); ContractForm contractForm = contractFormDao.findById(contractFormId); try{ businessObjectStatusHelperContainer .getBusinessObjectStatusHelper(contractForm.getContractFormType().toString()) .triggerAction( contractForm, Committee.CONTRACT_ADMIN, currentUser, "CONTRACT_EXECUTED_WITHOUT_WORKFLOW", note, ""); return XMLResponseHelper.newSuccessResponseStube("Successfully execute contract!"); } catch (Exception e){ e.printStackTrace(); return XMLResponseHelper.newErrorResponseStub("Failed execute contract!"); } } @RequestMapping(value = "/ajax/contracts/{contractId}/contract-forms/{contractFormId}/get-upload-documentuser-role-list", method = RequestMethod.GET, produces="application/xml") public @ResponseBody Source getUserCommitteeListForUploadDocument(@PathVariable("contractFormId") long contractFormId, @RequestParam("userId") long userId){ User currentUser = userDao.findById(userId); String finalCommitteeXml = "<committees>"; try{ Set<UserRole> userRoles = currentUser.getUserRoles(); String committeeXml = ""; for (UserRole ur : userRoles){ if (ur.getRole().getCommitee() != null){ committeeXml += "<committee name=\""+ ur.getRole().getCommitee().toString() +"\" desc=\""+ ur.getRole().getCommitee().getDescription() +"\" />"; } } finalCommitteeXml += committeeXml + "</committees>"; return XMLResponseHelper.newDataResponseStub(finalCommitteeXml); } catch (Exception e){ e.printStackTrace(); return XMLResponseHelper.newErrorResponseStub("Failed to load committee list!"); } } @RequestMapping(value = "/ajax/contracts/{contractId}/add-related-contract", method = RequestMethod.POST) public @ResponseBody JsonResponse addRelatedContract(@PathVariable("contractId") long contractId, @RequestParam("relatedContractId") long relatedContractId, @RequestParam("userId") long userId) { //might need to restrict roles // try{ // Contract relatedContract = contractDao.findById(relatedContractId); // Contract contract = contractDao.findById(contractId); // // RelatedContract newRelatedContract = new RelatedContract(); // newRelatedContract.setContract(contract); // newRelatedContract.setRelated_contract(relatedContract); // // //relatedContract.setContract(contract); // relatedContractDao.saveOrUpdate(newRelatedContract); // // return new JsonResponse(false, "", ""); // } catch (Exception e){ // e.printStackTrace(); // return new JsonResponse(true, "Failed to add related contract!", ""); // } try{ RelatedObject relatedObject = relationService.addRelationByIdAndType(contractId, relatedContractId, "contract", "contract"); return new JsonResponse(false, "", "", false, relatedObject); } catch (Exception e){ e.printStackTrace(); return new JsonResponse(true, "Failed to add related contract!", "", false, null); } } @RequestMapping(value = "/ajax/contracts/{contractId}/delete-related-contract", method = RequestMethod.POST) public @ResponseBody JsonResponse deleteRelatedContract(@PathVariable("contractId") long contractId, @RequestParam("relatedContractId") long relatedContractId, @RequestParam("userId") long userId) { //might need to restrict roles // try{ // RelatedContract exRelatedContract = relatedContractDao.getRelatedContractByContractIdAndRelatedContractId(contractId, relatedContractId); // exRelatedContract.setRetired(true); // // relatedContractDao.saveOrUpdate(exRelatedContract); // // return new JsonResponse(false, "", ""); // } catch (Exception e){ // e.printStackTrace(); // return new JsonResponse(true, "Failed to remove related contract!", ""); // } try{ RelatedObject relatedObject = relationService.removeRelationByIdAndType(contractId, relatedContractId, "contract", "contract"); return new JsonResponse(false, "", "", false, null); } catch (Exception e){ e.printStackTrace(); return new JsonResponse(true, "Failed to remove related contract!", "", false, null); } } @RequestMapping(value = "/ajax/contracts/{contractId}/new-form-types.xml", method = RequestMethod.GET) public @ResponseBody String getNewFormList(@PathVariable("contractId") long contractId){ //Contract contract = contractDao.findById(contractId); User u = (User) SecurityContextHolder.getContext().getAuthentication() .getPrincipal(); String newFormList = "<forms>"; //if (objectAclService.hasEditObjectAccess(Contract.class, contractId, u) || u.getAuthorities().contains(Permission.ROLE_CONTRACT_ADMIN) || u.getAuthorities().contains(Permission.ROLE_CONTRACT_LEGAL_REVIEW) || u.getAuthorities().contains(Permission.ROLE_CONTRACT_MANAGER)){ if (u.getAuthorities().contains(Permission.CAN_CREATE_CONTRACT)){ newFormList += "<form type=\"contract\" id=\"amendment\" title=\"Contract Amendment\"><description></description></form>"; } newFormList += "</forms>"; return newFormList; } @RequestMapping(value = "/ajax/contracts/{contractId}/update-summary", method = RequestMethod.POST) public @ResponseBody JsonResponse updateContractSummary(@PathVariable("contractId") long contractId, @RequestParam("path") String path, @RequestParam("value") String value, @RequestParam("userId") long userId){ Contract contract = contractDao.findById(contractId); String contractMetaXml = contract.getMetaDataXml(); User currentUser = userDao.findById(userId); try{ contractMetaXml = xmlProcessor.replaceOrAddNodeValueByPath(path, contractMetaXml, value); contract.setMetaDataXml(contractMetaXml); contractDao.saveOrUpdate(contract); auditService.auditEvent("CONTRACT_SUMMARY_UPDATED", currentUser.getPerson().getFullname() + " has updated answer of " + path + " to " + value); return new JsonResponse(false, "", "", false, null); } catch (Exception e){ e.printStackTrace(); return new JsonResponse(true, "Failed to update contract summary!", "", false, null); } } @RequestMapping(value = "/ajax/contracts/{contractId}/update-committee-note", method = RequestMethod.POST, produces="application/xml") public @ResponseBody Source updateCommitteeNot(@PathVariable("contractId") long contractId, @RequestParam("logId") String logId, @RequestParam(value="formCommitteeStatusId", required=false) long formCommitteeStatusId, @RequestParam("log") String newLog, @RequestParam(value="note", required=false) String note, @RequestParam("action") String action){ Track track = trackDao.getTrackByTypeAndRefObjectID("CONTRACT", contractId); try { track = contractTrackService.updateSingleLogContent(track, logId, newLog); } catch (Exception e) { e.printStackTrace(); } String commiteeNote = (note != null)?note:""; if (formCommitteeStatusId != 0) { try { ContractFormCommitteeStatus cfcs = contractFormCommitteeStatusDao.findById(formCommitteeStatusId); cfcs.setNote(commiteeNote); cfcs = contractFormCommitteeStatusDao.saveOrUpdate(cfcs); return XMLResponseHelper.newSuccessResponseStube("Successfully!"); } catch (Exception e) { e.printStackTrace(); return XMLResponseHelper.newErrorResponseStub("Failed to edit note!"); } } else { return XMLResponseHelper.newSuccessResponseStube("Successfully!"); } } @Autowired(required = true) public void setContractDao(ContractDao contractDao) { this.contractDao = contractDao; } public ContractDao getContractDao() { return contractDao; } @Autowired(required = true) public void setXmlProcessor(XmlProcessor xmlProcessor) { this.xmlProcessor = xmlProcessor; } public XmlProcessor getXmlProcessor() { return xmlProcessor; } @Autowired(required = true) public void setContractFormStatusDao( ContractFormStatusDao contractFormStatusDao) { this.contractFormStatusDao = contractFormStatusDao; } public ContractFormStatusDao getContractFormStatusDao() { return contractFormStatusDao; } @Autowired(required = true) public void setContractFormXmlDataDao( ContractFormXmlDataDao contractFormXmlDataDao) { this.contractFormXmlDataDao = contractFormXmlDataDao; } public ContractFormXmlDataDao getContractFormXmlDataDao() { return contractFormXmlDataDao; } public ContractFormDao getContractFormDao() { return contractFormDao; } @Autowired(required = true) public void setContractFormDao(ContractFormDao contractFormDao) { this.contractFormDao = contractFormDao; } public UserDao getUserDao() { return userDao; } @Autowired(required = true) public void setUserDao(UserDao userDao) { this.userDao = userDao; } public MutexLockService getMutexLockService() { return mutexLockService; } @Autowired(required = true) public void setMutexLockService(MutexLockService mutexLockService) { this.mutexLockService = mutexLockService; } public RelationService getRelationService() { return relationService; } @Autowired(required = true) public void setRelationService(RelationService relationService) { this.relationService = relationService; } public AuditService getAuditService() { return auditService; } @Autowired(required = true) public void setAuditService(AuditService auditService) { this.auditService = auditService; } public ObjectAclService getObjectAclService() { return objectAclService; } @Autowired(required = true) public void setObjectAclService(ObjectAclService objectAclService) { this.objectAclService = objectAclService; } public FormService getFormService() { return formService; } @Autowired(required = true) public void setFormService(FormService formService) { this.formService = formService; } public ContractFormCommitteeStatusDao getContractFormCommitteeStatusDao() { return contractFormCommitteeStatusDao; } @Autowired(required = true) public void setContractFormCommitteeStatusDao( ContractFormCommitteeStatusDao contractFormCommitteeStatusDao) { this.contractFormCommitteeStatusDao = contractFormCommitteeStatusDao; } public BusinessObjectStatusHelperContainer getBusinessObjectStatusHelperContainer() { return businessObjectStatusHelperContainer; } @Autowired(required = true) public void setBusinessObjectStatusHelperContainer( BusinessObjectStatusHelperContainer businessObjectStatusHelperContainer) { this.businessObjectStatusHelperContainer = businessObjectStatusHelperContainer; } public ContractTrackService getContractTrackService() { return contractTrackService; } @Autowired(required = true) public void setContractTrackService(ContractTrackService contractTrackService) { this.contractTrackService = contractTrackService; } public TrackDao getTrackDao() { return trackDao; } @Autowired(required = true) public void setTrackDao(TrackDao trackDao) { this.trackDao = trackDao; } }
true
90d8565ff8caea97dcf147bcb658535833f797b1
Java
swvalerian/JavaCore
/src/main/java/com/swvalerian/javacore/module01/chapter18/TreeSetExample.java
UTF-8
1,086
3.765625
4
[]
no_license
package com.swvalerian.javacore.module01.chapter18; import java.util.TreeSet; public class TreeSetExample { public static void main(String[] args) { TreeSet treeSet = new TreeSet(); System.out.println("Initial treeset..."); treeSet.add(5); treeSet.add(1); treeSet.add(3); treeSet.add(2); treeSet.add(9); treeSet.add(0); treeSet.add(7); treeSet.add(6); treeSet.add(8); treeSet.add(4); treeSet.add(14); treeSet.add(44); treeSet.add(25); System.out.println(treeSet.ceiling(12)); //понял как работает, но зачем это может пригодиться? System.out.println("TreeSet content:"); System.out.println(treeSet); // выведет элементы отсортированные по возрастанию! Integer i = 0; System.out.println("Хешкод нуля = " + i.hashCode()); System.out.println("Хешкод нуля типа char = " + "0".hashCode()); } }
true
cffe8aba5774da9a94e1ea4c1b3ce80f8e5edf88
Java
charindu/singtel-assignment
/singtel-test/src/test/java/dev/singtel/interview/DuckTest.java
UTF-8
753
2.5
2
[ "MIT" ]
permissive
package dev.singtel.interview; import org.junit.Before; import org.junit.Test; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; public class DuckTest extends BaseTest{ private String singCheck = "Quack, quack\r\n"; private String swimCheck = "duck swimming\r\n"; private Duck b = new Duck(); @Before public void setup(){ System.setOut(out); } @Test public void sing() { b.makeSound(); String out = byteOut.toString(); assertThat(out, containsString(singCheck)); } @Test public void swim() { b.swim(); String out = byteOut.toString(); assertThat(out, containsString(swimCheck)); } }
true
cb9df877be6345ffc9935b332724549013346a84
Java
EmkaMk/monolith-structured
/book-management-event/src/main/java/com/seavus/bookstore/bookmanagement/BookCreatedEvent.java
UTF-8
289
1.671875
2
[]
no_license
package com.seavus.bookstore.bookmanagement; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @NoArgsConstructor @AllArgsConstructor @Data public class BookCreatedEvent { String uuid; String title; String author; String genre; }
true
7fece31a4078b02b512c621ba7cdf3177c99ec21
Java
hasannaqvi1/FlightManagement
/FlightManagement/src/main/java/com/cg/FlightManagement/service/BookingServiceImpl.java
UTF-8
1,188
2.390625
2
[]
no_license
package com.cg.FlightManagement.service; import java.util.ArrayList; import java.util.List; import com.cg.FlightManagement.dto.Booking; import com.cg.FlightManagement.dto.Passenger; public class BookingServiceImpl implements BookingService{ List<Booking> bookingList=new ArrayList<Booking>(); @Override public void addBooking(Booking b) { // TODO Auto-generated method stub bookingList.add(b); } @Override public List<Booking> viewBookingById(int bookingId) { // TODO Auto-generated method stub return null; } @Override public List<Booking> viewBooking() { // TODO Auto-generated method stub return bookingList; } @Override public boolean deleteBooking(int bookingId) { // TODO Auto-generated method stub boolean available=false; for(Booking b1:bookingList) { if(b1.getBookingId()==bookingId) { bookingList.remove(b1); available=true; break; } } return available; } @Override public void validateBooking(Booking b) { // TODO Auto-generated method stub } @Override public void validatePassenger(Passenger p) { // TODO Auto-generated method stub } }
true
a44774d6144c1f99dc66cd8cc6f2e5ef1f5b8929
Java
chenglinjava68/spring-boot-grpc-starter
/spring-grpc-server-starter/src/main/java/com/emt/grpc/server/AbstractGrpcServerBuilder.java
UTF-8
5,348
1.9375
2
[ "MIT" ]
permissive
package com.emt.grpc.server; import com.emt.grpc.annotation.GrpcServerInterceptor; import com.emt.grpc.annotation.GrpcService; import com.emt.grpc.spring.GrpcServerProperties; import io.grpc.BindableService; import io.grpc.Server; import io.grpc.ServerBuilder; import io.grpc.ServerInterceptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationContext; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.logging.Logger; /** * Created by emt on 10.05.2017. */ public abstract class AbstractGrpcServerBuilder { private final static Logger logger = Logger.getLogger(AbstractGrpcServerBuilder.class.getName()); private final static Class<GrpcService> GRPC_SERVICE_ANAT_CLASS = GrpcService.class; private final static Class<GrpcServerInterceptor> GRPC_INTERCEPTOR_CLASS = GrpcServerInterceptor.class; private final static Class<BindableService> BINDABLE_SERVICE_CLASS = BindableService.class; private final static Class<ServerInterceptor> SERVER_INTERCEPTOR_CLASS = ServerInterceptor.class; @Autowired private GrpcServerProperties grpcServerProperties; @Autowired private ApplicationContext applicationContext; @Autowired private AbstractServiceRegistry abstractServiceRegistry; private Server server; public abstract void serverBuilder(ServerBuilder serverBuilder); protected void init() throws Exception { final List<BindableService> grpcServiceInstances = getGrpcServiceInstances(); final List<ServerInterceptor> globalServerInterceptors = getGlobalInterceptors(); if (grpcServiceInstances.isEmpty()) { logger.warning(String.format("Not found grpc service")); return; } ServerBuilder serverBuilder = ServerBuilder.forPort(this.grpcServerProperties.getPort()); this.serverBuilder(serverBuilder); for (BindableService bindableService : grpcServiceInstances) { logger.info(String.format("Binding grpc service : %s", bindableService.getClass().getName())); this.bindService(serverBuilder, bindableService, new ArrayList<>(globalServerInterceptors)); } try { this.server = serverBuilder.build().start(); logger.info(String.format("Grpc server started port: %d ", this.server.getPort())); this.blockUntilShutdown(); } catch (IOException e) { throw new Exception(e); } } private void blockUntilShutdown() { Thread thread = new Thread(new Runnable() { @Override public void run() { try { server.awaitTermination(); } catch (InterruptedException e) { } } }); thread.start(); } public synchronized boolean getServerStatus() { return this.server != null && !this.server.isShutdown() && !this.server.isTerminated(); } protected void destroy() { if (server != null) server.shutdown(); } private void bindService(ServerBuilder serverBuilder, BindableService bindableService, List<ServerInterceptor> globalInterceptors) { GrpcService grpcService = bindableService.getClass().getAnnotation(GRPC_SERVICE_ANAT_CLASS); List<ServerInterceptor> grpcServiceInterceptors = this.getServicesInterceptor(grpcService); abstractServiceRegistry.bindService(serverBuilder, bindableService, globalInterceptors, grpcServiceInterceptors, new GrpcServiceAnatHolder(grpcService.applyOnGlobalInterceptors())); } private List<ServerInterceptor> getServicesInterceptor(GrpcService grpcService) { List<ServerInterceptor> interceptors = new ArrayList<>(); Class<? extends ServerInterceptor>[] aClass = grpcService.interceptors(); for (Class<? extends ServerInterceptor> each : aClass) { if (each.getName().equals(EmptyServerInterceptor.class.getName())) { continue; } ServerInterceptor serverInterceptor = applicationContext.getBean(each); interceptors.add(serverInterceptor); } return interceptors; } private List<BindableService> getGrpcServiceInstances() { List<Object> grpcServiceInstances = new ArrayList<>(applicationContext.getBeansWithAnnotation(GrpcService.class).values()); if (grpcServiceInstances.isEmpty()) return Collections.EMPTY_LIST; List<BindableService> validatedList = new ArrayList<>(); for (Object each : grpcServiceInstances) { if (each instanceof BindableService) validatedList.add(BINDABLE_SERVICE_CLASS.cast(each)); } return validatedList; } private List<ServerInterceptor> getGlobalInterceptors() { List<Object> globalServerInterceptors = new ArrayList<>(applicationContext .getBeansWithAnnotation(GRPC_INTERCEPTOR_CLASS).values()); if (globalServerInterceptors.isEmpty()) return Collections.EMPTY_LIST; List<ServerInterceptor> validatedList = new ArrayList<>(); for (Object each : globalServerInterceptors) { GrpcServerInterceptor anat = each.getClass().getAnnotation(GRPC_INTERCEPTOR_CLASS); if ((each instanceof ServerInterceptor) && anat.isGlobal()) validatedList.add(SERVER_INTERCEPTOR_CLASS.cast(each)); } return validatedList; } }
true
bbe381d81203bbea94210e102ae4bdf9f0b9e5aa
Java
solidfire/solidfire-sdk-java
/src/generated/java/com/solidfire/element/api/ListIdpConfigurationsRequest.java
UTF-8
7,065
1.851563
2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-unknown" ]
permissive
/* * Copyright &copy 2014-2016 NetApp, Inc. 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. */ /* * DO NOT EDIT THIS CODE BY HAND! It has been generated with jsvcgen. */ package com.solidfire.element.api; import com.solidfire.gson.Gson; import com.solidfire.core.client.Attributes; import com.solidfire.gson.annotations.SerializedName; import com.solidfire.core.annotation.Since; import com.solidfire.core.javautil.Optional; import java.io.Serializable; import java.util.Arrays; import java.util.HashMap; import java.util.Objects; /** * ListIdpConfigurationsRequest * List configurations for third party Identity Provider(s) (IdP), optionally providing either enabledOnly flag to retrieve the currently enabled IdP configuration, or an IdP metadata UUID or IdP name to query a specific IdP configuration information. **/ public class ListIdpConfigurationsRequest implements Serializable { public static final long serialVersionUID = -7149009286023934106L; @SerializedName("idpConfigurationID") private Optional<java.util.UUID> idpConfigurationID; @SerializedName("idpName") private Optional<String> idpName; @SerializedName("enabledOnly") private Optional<Boolean> enabledOnly = Optional.of(false); // empty constructor @Since("7.0") public ListIdpConfigurationsRequest() {} // parameterized constructor @Since("7.0") public ListIdpConfigurationsRequest( Optional<java.util.UUID> idpConfigurationID, Optional<String> idpName, Optional<Boolean> enabledOnly ) { this.idpConfigurationID = (idpConfigurationID == null) ? Optional.<java.util.UUID>empty() : idpConfigurationID; this.idpName = (idpName == null) ? Optional.<String>empty() : idpName; this.enabledOnly = (enabledOnly == null) ? Optional.<Boolean>empty() : enabledOnly; } /** * UUID for the third party Identity Provider (IdP) Configuration. **/ public Optional<java.util.UUID> getIdpConfigurationID() { return this.idpConfigurationID; } public void setIdpConfigurationID(Optional<java.util.UUID> idpConfigurationID) { this.idpConfigurationID = (idpConfigurationID == null) ? Optional.<java.util.UUID>empty() : idpConfigurationID; } /** * Filters the result to an IdP configuration information for a specific IdP name. **/ public Optional<String> getIdpName() { return this.idpName; } public void setIdpName(Optional<String> idpName) { this.idpName = (idpName == null) ? Optional.<String>empty() : idpName; } /** * Filters the result to return the currently enabled Idp configuration. **/ public Optional<Boolean> getEnabledOnly() { return this.enabledOnly; } public void setEnabledOnly(Optional<Boolean> enabledOnly) { this.enabledOnly = (enabledOnly == null) ? Optional.<Boolean>empty() : enabledOnly; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ListIdpConfigurationsRequest that = (ListIdpConfigurationsRequest) o; return Objects.equals(idpConfigurationID, that.idpConfigurationID) && Objects.equals(idpName, that.idpName) && Objects.equals(enabledOnly, that.enabledOnly); } @Override public int hashCode() { return Objects.hash( idpConfigurationID,idpName,enabledOnly ); } public java.util.Map<String, Object> toMap() { java.util.Map<String, Object> map = new HashMap<>(); map.put("idpConfigurationID", idpConfigurationID); map.put("idpName", idpName); map.put("enabledOnly", enabledOnly); return map; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); Gson gson = new Gson(); sb.append( "{ " ); if(null != idpConfigurationID && idpConfigurationID.isPresent()){ sb.append(" idpConfigurationID : ").append(gson.toJson(idpConfigurationID)).append(","); } else{ sb.append(" idpConfigurationID : ").append("null").append(","); } if(null != idpName && idpName.isPresent()){ sb.append(" idpName : ").append(gson.toJson(idpName)).append(","); } else{ sb.append(" idpName : ").append("null").append(","); } if(null != enabledOnly && enabledOnly.isPresent()){ sb.append(" enabledOnly : ").append(gson.toJson(enabledOnly)).append(","); } else{ sb.append(" enabledOnly : ").append("null").append(","); } sb.append( " }" ); if(sb.lastIndexOf(", }") != -1) sb.deleteCharAt(sb.lastIndexOf(", }")); return sb.toString(); } public static Builder builder() { return new Builder(); } public final Builder asBuilder() { return new Builder().buildFrom(this); } public static class Builder { private Optional<java.util.UUID> idpConfigurationID; private Optional<String> idpName; private Optional<Boolean> enabledOnly; private Builder() { } public ListIdpConfigurationsRequest build() { return new ListIdpConfigurationsRequest ( this.idpConfigurationID, this.idpName, this.enabledOnly); } private ListIdpConfigurationsRequest.Builder buildFrom(final ListIdpConfigurationsRequest req) { this.idpConfigurationID = req.idpConfigurationID; this.idpName = req.idpName; this.enabledOnly = req.enabledOnly; return this; } public ListIdpConfigurationsRequest.Builder optionalIdpConfigurationID(final java.util.UUID idpConfigurationID) { this.idpConfigurationID = (idpConfigurationID == null) ? Optional.<java.util.UUID>empty() : Optional.of(idpConfigurationID); return this; } public ListIdpConfigurationsRequest.Builder optionalIdpName(final String idpName) { this.idpName = (idpName == null) ? Optional.<String>empty() : Optional.of(idpName); return this; } public ListIdpConfigurationsRequest.Builder optionalEnabledOnly(final Boolean enabledOnly) { this.enabledOnly = (enabledOnly == null) ? Optional.<Boolean>empty() : Optional.of(enabledOnly); return this; } } }
true
67028db3c40f196a8aa66b8c3f044770568452e3
Java
godfreydesidery/orbixBE
/src/main/java/com/example/orbix_web/controllers/BillServiceController.java
UTF-8
2,565
2.296875
2
[]
no_license
/** * */ package com.example.orbix_web.controllers; import java.util.List; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.example.orbix_web.exceptions.ResourceNotFoundException; import com.example.orbix_web.models.Bill; import com.example.orbix_web.repositories.BillRepository; /** * @author GODFREY * */ @RestController @RequestMapping(value = "/api") @Service public class BillServiceController { @Autowired BillRepository billRepository; // Get All Bills @GetMapping("/bills") public List<Bill> getAllBills() { return billRepository.findAll(); } // Create a new Bill @PostMapping(value="/bills") @ResponseBody public Bill createBill(@Valid @RequestBody Bill bill) { return billRepository.save(bill); } // Get a Single Bill @GetMapping("/bills/{id}") public Bill getBillById(@PathVariable(value = "id") Long billId) { return billRepository.findById(billId) .orElseThrow(() -> new ResourceNotFoundException("Bill", "id", billId)); } // Update a Bill @PutMapping("/bills/{id}") public Bill updateNote(@PathVariable(value = "id") Long billId, @Valid @RequestBody Bill billDetails) { Bill bill = billRepository.findById(billId) .orElseThrow(() -> new ResourceNotFoundException("Bill", "id", billId)); Bill updatedBill = billRepository.save(bill); return updatedBill; } // Delete a Bill @DeleteMapping("/bills/{id}") public ResponseEntity<?> deleteBill(@PathVariable(value = "id") Long billId) { Bill bill = billRepository.findById(billId) .orElseThrow(() -> new ResourceNotFoundException("Bill", "id", billId)); billRepository.delete(bill); return ResponseEntity.ok().build(); } }
true
d826d07daab3fefba43b6816830f418b7110064d
Java
kichel98/kompilator
/src/main/java/syntax/declarations/ArrDeclaration.java
UTF-8
726
2.640625
3
[]
no_license
package syntax.declarations; import core.Visitor; public class ArrDeclaration extends Declaration { private Long startIndex, endIndex; public ArrDeclaration(String arrName, Long startIndex, Long endIndex) { super(arrName); this.startIndex = startIndex; this.endIndex = endIndex; } @Override public void accept(Visitor visitor) { visitor.visit(this); } public Long getStartIndex() { return startIndex; } public void setStartIndex(Long startIndex) { this.startIndex = startIndex; } public Long getEndIndex() { return endIndex; } public void setEndIndex(Long endIndex) { this.endIndex = endIndex; } }
true
03ee6588b0d3fb10971f4ca00940607784d0d072
Java
0jinxing/wechat-apk-source
/com/tencent/mm/d/a/l$b.java
UTF-8
312
1.570313
2
[]
no_license
package com.tencent.mm.d.a; public abstract interface l$b { public abstract void ds(String paramString); } /* Location: C:\Users\Lin\Downloads\dex-tools-2.1-SNAPSHOT\dex-tools-2.1-SNAPSHOT\classes6-dex2jar.jar * Qualified Name: com.tencent.mm.d.a.l.b * JD-Core Version: 0.6.2 */
true
fa6b44f330b2e64ec15c53df229060078e198d82
Java
yuttao/UtimateChess
/src/edu/ncepu/yutao/Chess/UI/PieceLabel.java
UTF-8
1,026
2.765625
3
[]
no_license
package edu.ncepu.yutao.Chess.UI; import edu.ncepu.yutao.Chess.DataStructure.ChessPlayer; import edu.ncepu.yutao.Chess.DataStructure.ChessState; import edu.ncepu.yutao.Chess.DataStructure.ChessType; import edu.ncepu.yutao.Chess.ImageManager; import javax.swing.*; /** * Created by AUTOY on 2016/6/13. */ public class PieceLabel extends JLabel { public ChessType type = ChessType.BLANK; public ChessPlayer player = ChessPlayer.BLANK; public ChessState state = ChessState.BLANK; public int x; public int y; public PieceLabel(int x, int y) { super(); this.x = x; this.y = y; } public void setAll(ChessType type, ChessPlayer chessPlayer, ChessState state) { this.type = type; this.player = chessPlayer; this.state = state; this.setIcon(ImageManager.getImage(state, player, type)); } public void setState(ChessState state) { this.state = state; this.setIcon(ImageManager.getImage(state, player, type)); } }
true
31d021e37584296d6c7c707a762f557286e2f76a
Java
farkalit76/workspace-sts
/fu-sboot-esearch/src/test/java/com/farkalit/sboot/esearch/BookServiceTest.java
UTF-8
3,549
2.359375
2
[]
no_license
package com.farkalit.sboot.esearch; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.domain.Page; import static org.springframework.data.domain.PageRequest.of; import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import com.farkalit.sboot.esearch.model.Book; import com.farkalit.sboot.esearch.service.BookService; import lombok.extern.slf4j.Slf4j; @Slf4j @RunWith(SpringRunner.class) @SpringBootTest(classes = ApplicationSpringBoot.class) @ContextConfiguration public class BookServiceTest { @Autowired private BookService bookService; @Autowired private ElasticsearchTemplate esTemplate; @Before public void before() throws UnknownHostException { esTemplate.deleteIndex(Book.class); esTemplate.createIndex(Book.class); esTemplate.putMapping(Book.class); esTemplate.refresh(Book.class); } @Test public void testSave() { Book book = new Book("1001", "Java 8 advance", "Jave", "23-FEB-2017", "Usmani Posa"); Book testBook = bookService.save(book); assertNotNull(testBook); assertEquals(testBook.getTitle(), book.getTitle()); assertEquals(testBook.getCategory(), book.getCategory()); assertEquals(testBook.getAuthor(), book.getAuthor()); assertEquals(testBook.getPublishedDate(), book.getPublishedDate()); } @Test public void testFindByTitle() { Book book = new Book("1003", "Java 8 advance", "Jave", "23-FEB-2017", "Usmani Posa"); bookService.save(book); List<Book> byTitle = bookService.findByTitle(book.getTitle()); assertThat(byTitle.size(), is(1)); } @Test public void testFindByAuthor() { List<Book> bookList = new ArrayList<>(); bookList.add(new Book("1001", "Java 8 advance", "Jave", "23-FEB-2017", "Tim Posa")); bookList.add(new Book("1002", "Java 8 advance", "Jave", "23-FEB-2017", "Tim Posa")); bookList.add(new Book("1003", "Java 8 advance", "Jave", "23-FEB-2017", "Tim Posa")); bookList.add(new Book("1004", "Java 8 advance", "Jave", "23-FEB-2017", "Tim Posa")); bookList.add(new Book("1005", "Java 8 advance", "Jave", "23-FEB-2017", "Usmani")); for (Book book : bookList) { bookService.save(book); log.debug("Book saved..."); } Page<Book> byAuthor = bookService.findByAuthor("Tim Posa", of(0, 10)); assertThat(byAuthor.getTotalElements(), is(4L)); Page<Book> byAuthor2 = bookService.findByAuthor("Usmani", of(0, 10)); assertThat(byAuthor2.getTotalElements(), is(1L)); } @Test public void testFindOne() { Book book = new Book("1002", "Java 8 advance", "Jave", "23-FEB-2017", "Usmani Posa"); bookService.save(book); Book testBook = bookService.findOne(book.getId()); assertNotNull(testBook.getId()); assertEquals(testBook.getTitle(), book.getTitle()); assertEquals(testBook.getCategory(), book.getCategory()); assertEquals(testBook.getAuthor(), book.getAuthor()); assertEquals(testBook.getPublishedDate(), book.getPublishedDate()); } }
true
ce15028e16e88910c5c719d3c02354ff134dc432
Java
warlok/jc-nov17-denys
/src/com/kademika/day12/f2/FlyingBall.java
UTF-8
1,922
3.421875
3
[]
no_license
package com.kademika.day12.f2; import javax.swing.*; import java.awt.*; /** * Created by dean on 5/11/15. */ public class FlyingBall extends JPanel { private long freq = 16; private int frameWidth=600; private int frameHeight=600; private int ovalWidth=10; private int ovalHeight=10; private int ovalX = 10; public static void main(String[] args) { final FlyingBall ball = new FlyingBall(); new Thread() { @Override public void run() { ball.myRepaint(ball); } }.start(); new Thread() { @Override public void run() { ball.move(); } }.start(); } public FlyingBall() { JFrame frame = new JFrame("Flying Ball v1.1"); frame.setContentPane(this); frame.setBounds(200, 200, frameWidth, frameHeight); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setVisible(true); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(new Color(255, 0, 0)); g.fillOval(ovalX, 10, ovalWidth, ovalHeight); } public void myRepaint(JPanel panel) { while (true) { panel.repaint(); mySleep(freq); } } public void move() { int direction = 1; while (true) { if (ovalX == frameWidth-10) { direction = -1; ovalX--; } else if (ovalX == 0) { direction = 1; ovalX++; } else { ovalX = ovalX+direction; } mySleep(freq); } } public void mySleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } } }
true
d38acb3dbed7a5fb729901fc1cfac3709d5a5bea
Java
elyasnoui/IP_Messenger
/src/system/ServerHandler.java
UTF-8
2,172
3.203125
3
[]
no_license
package system; import javax.swing.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; import java.util.ArrayList; /** * @author Elyas, Noui, elyas.noui@city.ac.uk [190053026] * @version Java SE 15 */ public class ServerHandler implements Runnable { private final BufferedReader in; private final JList<Object> messageList; private final ArrayList<String> chatLog; private final JScrollPane scrollPane; public ServerHandler(Socket server, JList<Object> messageList, ArrayList<String> chatLog, JScrollPane scrollPane) throws IOException { this.messageList = messageList; this.chatLog = chatLog; this.scrollPane = scrollPane; // Used to receive responses from the server in = new BufferedReader(new InputStreamReader(server.getInputStream())); // Bug fix: GUI JList would sometimes go blank and would need a reset, this keeps the list refreshing Timer timer = new Timer(500, arg0 -> messageList.setListData(chatLog.toArray())); timer.start(); } /** * This method is a member function of {@link Runnable}, which is used when a {@link Thread} is started. * <p> * This method allows for server responses for clients to be displayed on the client's GUI. * </p> */ @Override public void run() { try { String response; while (true) { response = in.readLine(); // Records the response if (response == null) continue; // Keep looping if the response is null if (response.equals("BYE?")) break; // Used to escape infinite loop // Displays the response on the client's JList chatLog.add(response); messageList.setListData(chatLog.toArray()); scrollPane.getVerticalScrollBar().setValue(scrollPane.getVerticalScrollBar().getMaximum()+1); } } catch (IOException e) { e.printStackTrace(); } finally { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } }
true
df3bb6419972c3a5d1e672fb58a48f84fd163097
Java
a641324093/ExchangeSystemAtWindows
/src/exchange/db/DBItem.java
GB18030
3,298
2.65625
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package exchange.db; import java.io.IOException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import utils.FileUtils; /** * * @author myy */ public class DBItem { public static int addItem(Connection conn, String name,String desc,String img_path,int cat_id) throws SQLException { // statementִSQL Statement statement = conn.createStatement(); // ҪִеSQL String sql = "INSERT INTO item (`name`,`desc`,img,cat_id) VALUES ('"+name+"','"+desc+"','"+img_path+"',"+cat_id+")"; statement.executeUpdate(sql,Statement.RETURN_GENERATED_KEYS); //زļ¼idֵ ResultSet rs = statement.getGeneratedKeys(); int num = -1; if (rs.next()) { num = rs.getInt(1); } return num; } public static ResultSet getItemById(Connection conn,int id)throws SQLException { // statementִSQL Statement statement = conn.createStatement(); // ҪִеSQL String sql = "SELECT * FROM item WHERE id="+id; ResultSet rs = statement.executeQuery(sql); return rs; } /** * ItemͬʱҲ·еͼƬ * @param conn * @param name * @param desc * @param img_path * @param item_id * @return 0Ϊִд * @throws SQLException */ public static int updateItem(Connection conn, String name,String desc,String img_path,int item_id,int cat_id) throws SQLException, IOException { // statementִSQL Statement statement = conn.createStatement(); // ҪִеSQL ResultSet rs = getItemById(conn, cat_id); String img=""; while(rs.next()) { img = rs.getString("img"); } //ͼƬҲ if(img.equals(img_path)==false) { //ɾԭͼƬ FileUtils.clearFile(img); } String sql = "UPDATE item SET NAME='"+name+"',`desc`='"+desc+"',img='"+img_path+"',cat_id="+cat_id+" WHERE id="+item_id; int num=statement.executeUpdate(sql); return num; } /** * ɾitem¼ʱҪĴ * @param item_id * @return */ public static void delectItem(Connection conn,int item_id) throws SQLException, IOException { Statement statement = conn.createStatement(); // ҪִеSQL String sql = "SELECT img FROM form,item\n" + "WHERE form.`item_id`=item.`id`\n" + "AND item.`id`="+item_id; ResultSet rs =statement.executeQuery(sql); String img_path=null; while(rs.next()) { img_path=rs.getString("img"); } //ɾļ FileUtils.clearFile(img_path); //ɾ¼ sql="DELETE FROM item WHERE id="+item_id+";"; statement.executeUpdate(sql); statement.close(); rs.close(); } }
true
960d711470dd294a45a68b48c761009be22cf826
Java
chenghaoStephen/springboot-demo
/shiro/src/main/java/com/abc/shiro/config/ShiroConfiguration.java
UTF-8
5,477
1.882813
2
[]
no_license
package com.abc.shiro.config; import com.abc.shiro.cache.RedisCacheManager; import com.abc.shiro.realm.CustomRealm; import com.abc.shiro.session.CustomSessionDao; import com.abc.shiro.session.CustomSessionManager; import org.apache.shiro.authc.credential.HashedCredentialsMatcher; import org.apache.shiro.cache.CacheManager; import org.apache.shiro.session.mgt.eis.SessionDAO; import org.apache.shiro.spring.LifecycleBeanPostProcessor; import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.apache.shiro.web.session.mgt.DefaultWebSessionManager; import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.DependsOn; import javax.servlet.Filter; import java.util.LinkedHashMap; import java.util.Map; @Configuration public class ShiroConfiguration { /** * 配置ShiroFilter */ @Bean public ShiroFilterFactoryBean shiroFilter(DefaultWebSecurityManager securityManager) { ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean(); bean.setSecurityManager(securityManager); // 配置登录的url(认证失败自动跳转)和验证权限失败的url bean.setLoginUrl("/login"); // bean.setUnauthorizedUrl("/error"); // 配置自定义的Filter Map<String, Filter> filterMap = new LinkedHashMap<>(); filterMap.put("customFilter", new CustomFilter()); bean.setFilters(filterMap); // 配置访问权限 // 使用LinkedHashMap,按照顺序进行过滤,匹配上则不在继续向下匹配 LinkedHashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<>(); filterChainDefinitionMap.put("/login", "anon"); // anon不认证 filterChainDefinitionMap.put("/dologin", "anon"); filterChainDefinitionMap.put("/roles", "roles[admin,user]"); // 同时具有admin,user角色 filterChainDefinitionMap.put("/custom", "customFilter[admin,user]"); // 具有admin,user角色之一 filterChainDefinitionMap.put("/permissions", "perms[user:update,user:select]"); // 同时具有多个权限 filterChainDefinitionMap.put("/**", "authc"); // authc需要认证,/**表示所有路径,放在最后 bean.setFilterChainDefinitionMap(filterChainDefinitionMap); return bean; } /** * 配置核心类SecurityManager */ @Bean public DefaultWebSecurityManager securityManager() { DefaultWebSecurityManager manager = new DefaultWebSecurityManager(); // 配置自定义Realm CustomRealm customRealm = customRealm(); manager.setRealm(customRealm); // 配置加密算法(秘钥在自定义Realm时配置) HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(); matcher.setHashAlgorithmName("md5"); matcher.setHashIterations(1); customRealm.setCredentialsMatcher(matcher); // 配置自定义sessionManager manager.setSessionManager(sessionManager()); manager.setCacheManager(cacheManager()); return manager; } /** * 自定义Realm */ @Bean public CustomRealm customRealm() { CustomRealm customRealm = new CustomRealm(); return customRealm; } /** * 定义SessionManager */ @Bean public DefaultWebSessionManager sessionManager() { CustomSessionManager sessionManager = new CustomSessionManager(); sessionManager.setSessionDAO(sessionDao()); return sessionManager; } /** * 自定义SessionDao */ @Bean public SessionDAO sessionDao() { CustomSessionDao sessionDao = new CustomSessionDao(); return sessionDao; } @Bean public CacheManager cacheManager() { RedisCacheManager cacheManager = new RedisCacheManager(); return cacheManager; } /** * Shiro生命周期处理器 */ @Bean public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() { return new LifecycleBeanPostProcessor(); } /** * 开启Shiro的注解(如@RequiresRoles,@RequiresPermissions),需借助SpringAOP扫描使用Shiro注解的类,并在必要时进行安全逻辑验证 * 配置以下两个bean(DefaultAdvisorAutoProxyCreator(可选)和AuthorizationAttributeSourceAdvisor)即可实现此功能 */ @Bean @DependsOn({"lifecycleBeanPostProcessor"}) public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator() { DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator(); advisorAutoProxyCreator.setProxyTargetClass(true); return advisorAutoProxyCreator; } @Bean public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor() { AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor(); authorizationAttributeSourceAdvisor.setSecurityManager(securityManager()); return authorizationAttributeSourceAdvisor; } }
true
ef4d26fe7c1996762c62ec71f1953cb2cf69d2c8
Java
liaoqifeng/szdisplays
/src/com/koch/dao/impl/BrandDaoImpl.java
UTF-8
665
1.765625
2
[]
no_license
package com.koch.dao.impl; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang.StringUtils; import org.hibernate.Criteria; import org.hibernate.criterion.CriteriaSpecification; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Order; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import org.springframework.stereotype.Repository; import com.koch.bean.Pager; import com.koch.bean.Pager.OrderType; import com.koch.dao.BrandDao; import com.koch.entity.Brand; @Repository("brandDao") public class BrandDaoImpl extends BaseDaoImpl<Brand> implements BrandDao{ }
true
98ad7675b276773cc6c09f78c9ecd2e090b9c591
Java
Gnanika98/TY_JAVA_ABRIDGE_GNANIKA_FEB24
/quiz/day5/Quiz41.java
UTF-8
170
2.125
2
[]
no_license
package com.capgemini.quiz.day5; public class Quiz41 { public static void main(String[] args) { Quiz4 q=new Quiz4(); q.method(10, 45); q.method(9, 4.3); } }
true
14a55bd6f0ed397771d4ff1d02f297e6aa38ae0c
Java
mirackorkmaz/homeworkDay3
/homeworkDay3/src/homeworkDay3/InstructorManager.java
UTF-8
310
2.96875
3
[]
no_license
package homeworkDay3; public class InstructorManager { public void addAbility(Instructor instructor) { System.out.println(instructor.getAbility() + " added to your skills"); } public void addCourse(Instructor instructor) { System.out.println(instructor.getCourse() + " added to your courses"); } }
true
af7cecc787f78ac4e81a059802de35b93f07337f
Java
noelstriangle/JavaScouting2
/app/src/main/java/com/javascouts/javascouting2/MainActivity.java
UTF-8
7,710
1.921875
2
[]
no_license
package com.javascouts.javascouting2; import android.content.Context; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; import android.support.v4.app.ActivityCompat; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; import com.javascouts.javascouting2.adapters.ActivityFragmentCommunication; import com.javascouts.javascouting2.fragments.AnalysisFragment; import com.javascouts.javascouting2.fragments.MatchesFragment; import com.javascouts.javascouting2.fragments.ScoutingFragment; import com.javascouts.javascouting2.room.TeamDatabase; import com.javascouts.javascouting2.room.UserDao; public class MainActivity extends AppCompatActivity implements ActivityFragmentCommunication { private String current; Fragment scoutingFragment, matchesFragment, analysisFragment; private UserDao dao; private TeamDatabase db; ActionBar bar; private final int REQUEST = 112; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new Thread(new Runnable() { @Override public void run() { db = TeamDatabase.getTeamDatabase(getApplicationContext()); dao = db.getTeamDao(); runOnUiThread(new Runnable() { @Override public void run() { scoutingFragment = new ScoutingFragment(); matchesFragment = new MatchesFragment(); analysisFragment = new AnalysisFragment(); FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.fragHolder, scoutingFragment); fragmentTransaction.commit(); current = "SCOUTING"; } }); } }).start(); bar = getSupportActionBar(); if (bar != null) { bar.setTitle(R.string.title); //bar.setDisplayHomeAsUpEnabled(true); //bar.setHomeButtonEnabled(true); } BottomNavigationView navigation = findViewById(R.id.navigation); navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener); if (Build.VERSION.SDK_INT >= 23) { String[] PERMISSIONS = {android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.WRITE_EXTERNAL_STORAGE}; if (!hasPermissions(MainActivity.this, PERMISSIONS)) { ActivityCompat.requestPermissions(MainActivity.this, PERMISSIONS, REQUEST); } } } @Override protected void onResume() { super.onResume(); if ((db == null) || (dao == null)) { new Thread(new Runnable() { @Override public void run() { db = TeamDatabase.getTeamDatabase(getApplicationContext()); dao = db.getTeamDao(); } }).start(); } } private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.navigation_scouting: if(current.equals("SCOUTING")){ return true; } FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.replace(R.id.fragHolder, scoutingFragment); transaction.commit(); current = "SCOUTING"; return true; case R.id.navigation_schedule: if(current.equals("SCHEDULE")){ return true; } FragmentTransaction transaction2 = getSupportFragmentManager().beginTransaction(); transaction2.replace(R.id.fragHolder, matchesFragment); transaction2.commit(); current = "SCHEDULE"; return true; case R.id.navigation_analysis: if(current.equals("ANALYSIS")){ return true; } FragmentTransaction transaction3 = getSupportFragmentManager().beginTransaction(); transaction3.replace(R.id.fragHolder, analysisFragment); transaction3.commit(); current = "ANALYSIS"; return true; } return false; } }; @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.cleanseTeams: return false; case R.id.cleanseMatches: return false; case R.id.deleteMatch: return false; case R.id.deleteTeam: return false; case R.id.export: return false; case R.id.export2: return false; case R.id.inport: return false; case R.id.inport2: return false; case R.id.settings: return true; } return super.onOptionsItemSelected(item); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case REQUEST: { if (grantResults.length <= 0 || grantResults[0] != PackageManager.PERMISSION_GRANTED) { Toast.makeText(MainActivity.this, "Permissions were not granted!", Toast.LENGTH_LONG).show(); } } } } @Override public UserDao getDao() { return dao; } @Override public void setDao(UserDao dao) { this.dao = dao; } @Override public TeamDatabase getDb() { return db; } @Override public void setDb(TeamDatabase db) { this.db = db; } @Override public String getCurrent() { return current; } @Override public void setCurrent(String current) { this.current = current; } private static boolean hasPermissions(Context context, String... permissions) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) { for (String permission : permissions) { if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) { return false; } } } return true; } }
true
7cfea476c93b703950cb1ff9fc22535f145b477b
Java
imsajib02/Sailors-Ecommerce
/app/src/main/java/com/b2gsoft/sailorsexpress/model/Product.java
UTF-8
9,624
1.9375
2
[ "Apache-2.0" ]
permissive
package com.b2gsoft.sailorsexpress.model; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.google.gson.JsonElement; import com.google.gson.annotations.SerializedName; import java.io.Serializable; import java.util.List; public class Product implements Comparable<Product>, Serializable { @SerializedName("_id") private String id; @SerializedName("name") @Nullable private String name; @SerializedName("thumbnail") @Nullable private String thumbnail; @SerializedName("slug") @Nullable private String slug; @SerializedName("sku") @Nullable private String sku; @SerializedName("price") @Nullable private JsonElement price; @SerializedName("vat") @Nullable private JsonElement vat; @SerializedName("freeDelivery") @Nullable private boolean freeDelivery; @SerializedName("status") @Nullable private boolean status; @SerializedName("forOnline") @Nullable private boolean forOnline; @SerializedName("featured") @Nullable private boolean featured; @SerializedName("newArrival") @Nullable private boolean newArrival; @SerializedName("active") @Nullable private boolean active; @SerializedName("topSelling") @Nullable private boolean topSelling; @SerializedName("description") @Nullable private String description; @SerializedName("vendorId") @Nullable private String vendorId; @SerializedName("vendorName") @Nullable private String vendorName; @SerializedName("barcode") @Nullable private String barcode; @SerializedName("sizes") @Nullable private List<Size> sizes; @SerializedName("expireDate") @Nullable private String expireDate; @SerializedName("currentStock") @Nullable private int currentStock; @SerializedName("images") @Nullable private List<String> images; @SerializedName("discount") @Nullable private Discount discount; @SerializedName("category") @Nullable private Category category; @SerializedName("subcategory") @Nullable private SubCategory subCategory; @SerializedName("brand") @Nullable private Brand brand; @SerializedName("quantity") @Nullable private int quantity; @SerializedName("size") @Nullable private Size size; @SerializedName("currentPrice") @Nullable private double currentPrice; public Product(String id, @Nullable String name, @Nullable String thumbnail, @Nullable String slug, @Nullable String sku, @Nullable JsonElement price, @Nullable JsonElement vat, boolean freeDelivery, boolean status, boolean forOnline, boolean featured, boolean newArrival, boolean active, boolean topSelling, @Nullable String description, @Nullable String vendorId, @Nullable String vendorName, @Nullable String barcode, @Nullable List<Size> sizes, @Nullable String expireDate, int currentStock, @Nullable List<String> images, @Nullable Discount discount, @Nullable Category category, @Nullable SubCategory subCategory, @Nullable Brand brand, @Nullable int quantity, @Nullable Size size, @Nullable double currentPrice) { this.id = id; this.name = name; this.thumbnail = thumbnail; this.slug = slug; this.sku = sku; this.price = price; this.vat = vat; this.freeDelivery = freeDelivery; this.status = status; this.forOnline = forOnline; this.featured = featured; this.newArrival = newArrival; this.active = active; this.topSelling = topSelling; this.description = description; this.vendorId = vendorId; this.vendorName = vendorName; this.barcode = barcode; this.sizes = sizes; this.expireDate = expireDate; this.currentStock = currentStock; this.images = images; this.discount = discount; this.category = category; this.subCategory = subCategory; this.brand = brand; this.quantity = quantity; this.size = size; this.currentPrice = currentPrice; } public String getId() { return id; } public void setId(String id) { this.id = id; } @Nullable public String getName() { return name; } public void setName(@Nullable String name) { this.name = name; } @Nullable public String getThumbnail() { return thumbnail; } public void setThumbnail(@Nullable String thumbnail) { this.thumbnail = thumbnail; } @Nullable public String getSlug() { return slug; } public void setSlug(@Nullable String slug) { this.slug = slug; } @Nullable public String getSku() { return sku; } public void setSku(@Nullable String sku) { this.sku = sku; } @Nullable public JsonElement getPrice() { return price; } public void setPrice(@Nullable JsonElement price) { this.price = price; } @Nullable public int getCurrentStock() { return currentStock; } public void setCurrentStock(@Nullable int currentStock) { this.currentStock = currentStock; } @Nullable public List<String> getImages() { return images; } public void setImages(@Nullable List<String> images) { this.images = images; } @Nullable public Discount getDiscount() { return discount; } public void setDiscount(@Nullable Discount discount) { this.discount = discount; } @Nullable public Brand getBrand() { return brand; } public void setBrand(@Nullable Brand brand) { this.brand = brand; } @Nullable public JsonElement getVat() { return vat; } public void setVat(@Nullable JsonElement vat) { this.vat = vat; } @Nullable public boolean isFreeDelivery() { return freeDelivery; } public void setFreeDelivery(@Nullable boolean freeDelivery) { this.freeDelivery = freeDelivery; } @Nullable public boolean isStatus() { return status; } public void setStatus(@Nullable boolean status) { this.status = status; } @Nullable public boolean isForOnline() { return forOnline; } public void setForOnline(@Nullable boolean forOnline) { this.forOnline = forOnline; } @Nullable public boolean isFeatured() { return featured; } public void setFeatured(@Nullable boolean featured) { this.featured = featured; } @Nullable public boolean isNewArrival() { return newArrival; } public void setNewArrival(@Nullable boolean newArrival) { this.newArrival = newArrival; } @Nullable public boolean isActive() { return active; } public void setActive(@Nullable boolean active) { this.active = active; } @Nullable public boolean isTopSelling() { return topSelling; } public void setTopSelling(@Nullable boolean topSelling) { this.topSelling = topSelling; } @Nullable public String getDescription() { return description; } public void setDescription(@Nullable String description) { this.description = description; } @Nullable public String getVendorId() { return vendorId; } public void setVendorId(@Nullable String vendorId) { this.vendorId = vendorId; } @Nullable public String getVendorName() { return vendorName; } public void setVendorName(@Nullable String vendorName) { this.vendorName = vendorName; } @Nullable public String getBarcode() { return barcode; } public void setBarcode(@Nullable String barcode) { this.barcode = barcode; } @Nullable public List<Size> getSizes() { return sizes; } public void setSizes(@Nullable List<Size> sizes) { this.sizes = sizes; } @Nullable public String getExpireDate() { return expireDate; } public void setExpireDate(@Nullable String expireDate) { this.expireDate = expireDate; } @Nullable public Category getCategory() { return category; } public void setCategory(@Nullable Category category) { this.category = category; } @Nullable public SubCategory getSubCategory() { return subCategory; } public void setSubCategory(@Nullable SubCategory subCategory) { this.subCategory = subCategory; } @Nullable public int getQuantity() { return quantity; } public void setQuantity(@Nullable int quantity) { this.quantity = quantity; } @Nullable public double getCurrentPrice() { return currentPrice; } public void setCurrentPrice(@Nullable double currentPrice) { this.currentPrice = currentPrice; } @Nullable public Size getSize() { return size; } public void setSize(@Nullable Size size) { this.size = size; } @Override public String toString() { return name; } @Override public int compareTo(@NonNull Product product) { return Double.valueOf(currentPrice).compareTo(product.currentPrice); } }
true
632eb1b7ae13ded3575bc34275defbca72b60f4f
Java
1519567196/faj
/crazydog-common-dao/src/main/java/com/resjz/common/dao/zmadmin/entity/FNewsEntity.java
UTF-8
3,572
2.0625
2
[]
no_license
package com.resjz.common.dao.zmadmin.entity; import com.baomidou.mybatisplus.annotations.TableField; import com.baomidou.mybatisplus.annotations.TableId; import com.baomidou.mybatisplus.annotations.TableName; import java.io.Serializable; import java.util.Date; /** * 房产资讯 * * @author erdandan * @email resjz1@163.com * @date 2020-08-31 10:57:10 */ @TableName("f_news") public class FNewsEntity implements Serializable { private static final long serialVersionUID = 1L; /** * */ @TableId private Integer itemid; /** * 标题 */ private String title; /** * 分类id */ private Integer typeid; /** * 主图url */ private String image; /** * 内容 */ private String content; /** * 来源 */ private String from; /** * 浏览量 */ private Integer views; /** * 是否推荐,默认0 , 1推荐 */ private Integer isRecommend; /** * 添加时间 */ private Date addtime; /** * 添加人id */ private Long addUserid; /** * 修改时间 */ private Date updatetime; /** * 所属地区id */ private Integer areaid; //分类名称 @TableField(exist = false) private String typeName; public String getTypeName() { return typeName; } public void setTypeName(String typeName) { this.typeName = typeName; } /** * 设置: */ public void setItemid(Integer itemid) { this.itemid = itemid; } /** * 获取: */ public Integer getItemid() { return itemid; } /** * 设置:标题 */ public void setTitle(String title) { this.title = title; } /** * 获取:标题 */ public String getTitle() { return title; } /** * 设置:分类id */ public void setTypeid(Integer typeid) { this.typeid = typeid; } /** * 获取:分类id */ public Integer getTypeid() { return typeid; } /** * 设置:主图url */ public void setImage(String image) { this.image = image; } /** * 获取:主图url */ public String getImage() { return image; } /** * 设置:内容 */ public void setContent(String content) { this.content = content; } /** * 获取:内容 */ public String getContent() { return content; } /** * 设置:来源 */ public void setFrom(String from) { this.from = from; } /** * 获取:来源 */ public String getFrom() { return from; } /** * 设置:浏览量 */ public void setViews(Integer views) { this.views = views; } /** * 获取:浏览量 */ public Integer getViews() { return views; } /** * 设置:是否推荐,默认0 , 1推荐 */ public void setIsRecommend(Integer isRecommend) { this.isRecommend = isRecommend; } /** * 获取:是否推荐,默认0 , 1推荐 */ public Integer getIsRecommend() { return isRecommend; } /** * 设置:添加时间 */ public void setAddtime(Date addtime) { this.addtime = addtime; } /** * 获取:添加时间 */ public Date getAddtime() { return addtime; } /** * 设置:添加人id */ public void setAddUserid(Long addUserid) { this.addUserid = addUserid; } /** * 获取:添加人id */ public Long getAddUserid() { return addUserid; } /** * 设置:修改时间 */ public void setUpdatetime(Date updatetime) { this.updatetime = updatetime; } /** * 获取:修改时间 */ public Date getUpdatetime() { return updatetime; } /** * 设置:所属地区id */ public void setAreaid(Integer areaid) { this.areaid = areaid; } /** * 获取:所属地区id */ public Integer getAreaid() { return areaid; } }
true
cbabdd7f9c9ebb283887c44d1fe32ae5a91bd787
Java
wgcm-1202/ssmkkmusic
/src/main/java/com/pojo/UwithSL.java
UTF-8
132
1.570313
2
[]
no_license
package com.pojo; public class UwithSL { private Integer USlid; private Integer userid; private Integer songListid; }
true