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
299e13a228701b8ab20c67450e2f78091b0802da
Java
phungcong3012/YouTubeDemo
/app/src/main/java/com/example/admin/youtubedemo/ErrorActivity.java
UTF-8
540
2.140625
2
[]
no_license
package com.example.admin.youtubedemo; import android.app.Activity; import android.os.Bundle; public class ErrorActivity extends Activity{ private ErrorFragment mErrorFragment1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_error); testError(); } private void testError() { mErrorFragment1 = new ErrorFragment(); getFragmentManager().beginTransaction().add(R.id.main_browse_fragment, mErrorFragment1).commit(); } }
true
f8d76146a609365a260bfc40364e27696c47dce6
Java
TheDudeFromCI/AwgenShell
/AwgenShell/src/test/java/commands/PrintTest.java
UTF-8
2,097
2.75
3
[ "MIT" ]
permissive
package commands; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.junit.Test; import net.whg.awgenshell.exec.CommandSender; import net.whg.awgenshell.exec.ShellEnvironment; import net.whg.awgenshell.perms.Permissions; public class PrintTest { @Test public void one_word() { CommandSender sender = mock(CommandSender.class); when(sender.getPermissions()).thenReturn(Permissions.ALL); ShellEnvironment shell = new ShellEnvironment(sender); shell.runCommand("print Hi"); verify(sender).println("Hi"); } @Test public void two_words() { CommandSender sender = mock(CommandSender.class); when(sender.getPermissions()).thenReturn(Permissions.ALL); ShellEnvironment shell = new ShellEnvironment(sender); shell.runCommand("print Hello world!"); verify(sender).println("Hello world!"); } @Test public void one_word_withSymbol() { CommandSender sender = mock(CommandSender.class); when(sender.getPermissions()).thenReturn(Permissions.ALL); ShellEnvironment shell = new ShellEnvironment(sender); shell.runCommand("print Sup ?"); verify(sender).println("Sup?"); } @Test public void no_args() { CommandSender sender = mock(CommandSender.class); when(sender.getPermissions()).thenReturn(Permissions.ALL); ShellEnvironment shell = new ShellEnvironment(sender); shell.runCommand("print"); verify(sender).println(""); } @Test public void quoted_string() { CommandSender sender = mock(CommandSender.class); when(sender.getPermissions()).thenReturn(Permissions.ALL); ShellEnvironment shell = new ShellEnvironment(sender); shell.runCommand("print \"This is a sentence.\""); verify(sender).println("This is a sentence."); } @Test public void single_quoted_string() { CommandSender sender = mock(CommandSender.class); when(sender.getPermissions()).thenReturn(Permissions.ALL); ShellEnvironment shell = new ShellEnvironment(sender); shell.runCommand("print 'This is a sentence.'"); verify(sender).println("This is a sentence."); } }
true
83cebf2bf848f62d1309499e778f88ee1f26ded7
Java
fff2000/wmsfly
/src/main/java/com/obtk/wmsfly/wh/service/IWhStorageService.java
UTF-8
407
1.671875
2
[]
no_license
package com.obtk.wmsfly.wh.service; import com.obtk.wmsfly.domain.*; import java.util.List; public interface IWhStorageService { //查询所有 List<WhStorageD> queryAll(String id); //查询仓库 List<BsWarehouse> queryWare(); List<BsNewitem> queryItem(); //查询品牌名称 List<BsBread> queryBread(); //查询台账 List<WhStorage> findAll(String result); }
true
5bfb1ab479eb4bd94778fdf8aa6b6cbbe87e2920
Java
vladimirivkovic/MBRS17
/XMI2NG/src/generator/model/FMProperty.java
UTF-8
7,137
2.03125
2
[ "MIT" ]
permissive
package generator.model; import java.util.ArrayList; import java.util.List; import generator.ParserEngine; import generator.model.profile.Calculated; import generator.model.profile.Id; import generator.model.profile.Lookup; import generator.model.profile.Next; import generator.model.profile.NoInsert; import generator.model.profile.ReadOnly; import generator.model.profile.Stereotype; import generator.model.profile.Tab; import generator.model.profile.UIElement; import generator.model.profile.UIProperty; import generator.model.profile.Zoom; public class FMProperty extends FMNamedElement { private String type; private String visibility; private Integer lower = 0; private Integer upper = 1; //Stereotypes private Id id; private Lookup lookup; private ReadOnly readOnly; private NoInsert noInsert; private Next next; private Zoom zoom; private Calculated calculated; private Tab tab; private UIProperty uIProperty = new UIProperty(); //anotacije private List<FMAnnotation> annotations = new ArrayList<FMAnnotation>(); private String associationId = null; private FMProperty inverseProperty = null; private Boolean jsonIgnore = false; public FMProperty(String name, String type, String visibility, int lower, int upper) { super(name); this.type = type; this.visibility = visibility; this.lower = lower; this.upper = upper; } public FMProperty(String name, String type, String visibility, int lower, int upper, String associationId) { super(name); this.type = type; this.visibility = visibility; this.lower = lower; this.upper = upper; this.associationId = associationId; } public FMEnumeration getFMEnumeration() { return ParserEngine.getEnum(type); } public FMClass getFMClass() { return ParserEngine.getClass(type); } public String getType() { return ParserEngine.getType(type); //return type; } public String getTypeId() { return type; } public void setType(String type) { this.type = type; } public String getVisibility() { return visibility; } public void setVisibility(String visibility) { this.visibility = visibility; } public Integer getLower() { return lower; } public void setLower(Integer lower) { this.lower = lower; } public Integer getUpper() { return upper; } public void setUpper(Integer upper) { this.upper = upper; } public List<FMAnnotation> getAnnotations() { return annotations; } public void addAnnotation(FMAnnotation annotation) { this.annotations.add(annotation); } public String getCapName() { String s = this.getName(); return s.substring(0, 1).toUpperCase() + s.substring(1); } public boolean getPrimitive() { return ParserEngine.isPrimitive(type); } public String getAssociationId() { return associationId; } public void setAssociationId(String associationId) { this.associationId = associationId; } public Id getId() { return id; } public Lookup getLookup() { return lookup; } public ReadOnly getReadOnly() { return readOnly; } public NoInsert getNoInsert() { return noInsert; } public Next getNext() { return next; } public Zoom getZoom() { return zoom; } public Calculated getCalculated() { return calculated; } public Tab getTab() { return tab; } public UIProperty getuIProperty() { return uIProperty; } public Boolean getIsClass(){ return ParserEngine.getElementMap().get(type) instanceof FMClass; } public Boolean getJsonIgnore() { return jsonIgnore; } public void setJsonIgnore(Boolean jsonIgnore) { this.jsonIgnore = jsonIgnore; } @Override public void addStereotype(Stereotype st) { super.addStereotype(st); //if (uIProperty == null) uIProperty = (UIProperty) st; if (st instanceof Id) { id = (Id) st; setUIElementAttributes((UIElement) id); setUIPropertyAttributes((UIProperty) id); } else if(st instanceof Lookup) { lookup = (Lookup) st; setUIElementAttributes((UIElement) lookup); setUIPropertyAttributes((UIProperty) lookup); } else if(st instanceof ReadOnly) { readOnly = (ReadOnly) st; setUIElementAttributes((UIElement) readOnly); setUIPropertyAttributes((UIProperty) readOnly); } else if(st instanceof NoInsert) { noInsert = (NoInsert) st; setUIElementAttributes((UIElement) noInsert); setUIPropertyAttributes((UIProperty) noInsert); } else if(st instanceof Next) { next = (Next) st; if(next.getJsonIgnore()){ setJsonIgnore(true); } setUIElementAttributes((UIElement) next); } else if(st instanceof Zoom) { zoom = (Zoom) st; if(zoom.getJsonIgnore()){ setJsonIgnore(true); } setUIElementAttributes((UIElement) zoom); } else if(st instanceof Calculated) { calculated = (Calculated) st; setUIElementAttributes((UIElement) calculated); setUIPropertyAttributes((UIProperty) calculated); } else if(st instanceof Tab) { tab = (Tab) st; if(tab.getJsonIgnore()){ setJsonIgnore(true); } setUIElementAttributes((UIElement) tab); } else if(st instanceof UIProperty) { UIProperty uip = (UIProperty) st; setUIElementAttributes((UIElement) uip); setUIPropertyAttributes(uip); } } private void setUIElementAttributes(UIElement uie){ if(this.uIProperty.getVisible() && !uie.getVisible()){ //menja u slucaju da ga niko nije postavio na false... this.uIProperty.setRequired(false); } if(this.uIProperty.getLabel().equals("") && !uie.getLabel().equals("")){ //menja label u slucaju da ga niko nije postavio na razlicito od "" this.uIProperty.setLabel(uie.getLabel()); } //TODO: implementirati za component! } private void setUIPropertyAttributes(UIProperty uip){ if(!this.uIProperty.getShowColumn() && uip.getShowColumn()){ //menja showColumn ako ga niko nije postavio na true this.uIProperty.setShowColumn(true); } if(!this.uIProperty.getToolTip().equals("") && !uip.getToolTip().equals("")){ this.uIProperty.setToolTip(uip.getToolTip()); } if(!this.uIProperty.getCopyable() && uip.getCopyable()){ //menja u slucaju da ga niko nije postavio na true... this.uIProperty.setCopyable(true); } if(!this.uIProperty.getSearchable() && uip.getSearchable()){ //menja u slucaju da ga niko nije postavio na true... this.uIProperty.setSearchable(true); } if(!this.uIProperty.getRequired() && uip.getRequired()){ //menja u slucaju da ga niko nije postavio na true... this.uIProperty.setRequired(true); } if(!this.uIProperty.getUnique() && uip.getUnique()){ //menja u slucaju da ga niko nije postavio na true... this.uIProperty.setUnique(true); } if(this.uIProperty.getFieldGroup().equals("Other") && !uip.getFieldGroup().equals("")){ //menja u slucaju da ga niko nije postavio na true... this.uIProperty.setFieldGroup(uip.getFieldGroup()); } } public FMProperty getInverseProperty() { return inverseProperty; } public void setInverseProperty(FMProperty inverseProperty) { this.inverseProperty = inverseProperty; } }
true
4f132a55df97d561acce2e2449764766f7b9163e
Java
Ph0tonic/CS451-2020-project
/308542/src/main/java/cs451/broadcast/CausalOrderBroadcastReceive.java
UTF-8
125
1.867188
2
[ "MIT" ]
permissive
package cs451.broadcast; public interface CausalOrderBroadcastReceive { void deliver(int originId, byte[] data); }
true
c6e52a495c6a109795522279b0a7d9aa37a54701
Java
Catfeeds/rog-backend
/src/main/java/com/rograndec/feijiayun/chain/business/basic/user/vo/BusinessVarietysVO.java
UTF-8
1,551
2.21875
2
[]
no_license
package com.rograndec.feijiayun.chain.business.basic.user.vo; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.io.Serializable; import java.util.List; @ApiModel public class BusinessVarietysVO implements Serializable { /** * 受限品种 */ @ApiModelProperty(value = "受限品种数组") @NotNull(message = "受限品种不能为空") @Size(message = "受限品种不能为空") private List<Integer> businessVarietys; /** * 类型 */ @ApiModelProperty(value = "员工管理:0;供应商员工:1,默认为0") private Integer type = 0; @ApiModelProperty(value = "如果查询类型是员工管理则传入企业id,如果选择是的供应商员工管理则传入的是供应商id") @NotNull(message = "企业id或者供应商id不能为空") private Long enterpriseId; public List<Integer> getBusinessVarietys() { return businessVarietys; } public void setBusinessVarietys(List<Integer> businessVarietys) { this.businessVarietys = businessVarietys; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public Long getEnterpriseId() { return enterpriseId; } public void setEnterpriseId(Long enterpriseId) { this.enterpriseId = enterpriseId; } }
true
e267303c9e2fa075b61266bb0a366eace25c6fa5
Java
MrLW/oa
/src/main/java/com/lw/oa/struts2/result/AjaxResult.java
UTF-8
901
2.25
2
[]
no_license
package com.lw.oa.struts2.result; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.Result; import org.apache.struts2.ServletActionContext; import javax.servlet.ServletContext; /** * Created by lw on 2017/5/7. * struts2的不刷新结果集 */ public class AjaxResult implements Result { private String dataA; private String dataB ; public String getDataA() { return dataA; } public void setDataA(String dataA) { this.dataA = dataA; } public String getDataB() { return dataB; } public void setDataB(String dataB) { this.dataB = dataB; } public void execute(ActionInvocation actionInvocation) throws Exception { System.out.println("dataA:" + dataA ); System.out.println("dataB:" + dataB ); ServletActionContext.getResponse().getWriter().print("aaa"); } }
true
eaca2bb17829df2165213037c2eb45bceab146cf
Java
Again-one/topic-
/LibreOJ/src/math/Test2.java
UTF-8
122
1.523438
2
[]
no_license
package math; public class Test2 { public static void main(String[] args) { int a; System.out.println(0%3); } }
true
60baed6b4ac431ca1200baf6b63bf318fbe4308c
Java
YehorHolyk/patternProj
/src/main/java/ua/nure/patternProj/dao/GenericDAO.java
UTF-8
293
2.1875
2
[]
no_license
package ua.nure.patternProj.dao; import ua.nure.patternProj.observer.EventManager; public interface GenericDAO<T> { EventManager events = new EventManager("create","read","update","delete"); boolean create(T obj); T read(T obj); void update(T obj); void delete(T obj); }
true
3b4aba0192462a77312e9caad5c695e04f6aa7c9
Java
Lusky87/gas_bpm
/uengine/src/main/java/com/webdeninteractive/xbotts/Mapping/compiler/LinkPath.java
UTF-8
2,762
2.6875
3
[ "GPL-3.0-or-later", "GPL-1.0-or-later", "GPL-3.0-only", "EPL-2.0", "Apache-2.0", "LGPL-2.1-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.0-or-later", "LicenseRef-scancode-proprietary-license" ]
permissive
/* ------------------------------------------------------------------- BIE is Copyright 2001-2004 Brunswick Corp. ------------------------------------------------------------------- Please read the legal notices (docs/legal.txt) and the license (docs/bie_license.txt) that came with this distribution before using this software. ------------------------------------------------------------------- */ /* * LinkPath.java * * Created on August 1, 2002, 1:16 PM */ package com.webdeninteractive.xbotts.Mapping.compiler; import java.util.LinkedList; import java.util.StringTokenizer; /** Contains an XPath path represented as a linked list. * XPath paths are backslash seperated strings representing each nested level, * terminated by an @attribute or #text atomic element. * @author bmadigan */ public class LinkPath extends java.util.LinkedList { Linkable atom; public LinkPath(Linkable atom){ this.atom = atom; this.atomType=atom.getType( ); this.atomName=atom.getName( ); this.addFirst(atom); //walk tree to root, add nodes root first; Linkable next = (Linkable)atom.getOwner( ); if(null!=next) { this.addFirst(next); Linkable tmp; while((tmp = next.getOwner())!=null){ next=tmp; this.addFirst(next); } } } String atomType; String atomName; public String getAtomType( ){ return atomType; } public void setAtomType(String t)throws IllegalArgumentException{ if(!t.equals("attribute")||t.equals("text")){ throw new IllegalArgumentException( "setAtomType( ) expects 'attribute' or 'text'. Value "+t +" not allowed."); } this.atomType=t; } public String getAtomName( ){ return atomName; } public void setAtomName(String name){ this.atomName=name; } public String toString( ){ String path = PathUtils.getPath(atom); System.out.println("path: "+path); return path; /* StringBuffer sb = new StringBuffer( ); if(this.size()==1) return "/"; for(int i=0;i<this.size( );i++){ Linkable elem = (Linkable)this.get(i); if(elem.equals(this.getLast())){ if(elem.getNodeType().equals(Linkable.ATTR_NODE)){ sb.append("/@"+elem.getName( )); }else{ sb.append("/"+elem.getName( )); } }else if(elem.equals(this.getFirst( ))){ //root, do nothing }else{ sb.append("/"+elem.getName( )); } } return sb.toString( ); */ } }
true
f406d84932e82c1146098bbd0e668a9b1b0e483b
Java
imtiazkalamabir/mvppractice
/app/src/main/java/com/androidtime/mvp/model/InvokeApi.java
UTF-8
1,236
2.265625
2
[]
no_license
package com.androidtime.mvp.model; import android.content.Context; import com.androidtime.mvp.POJO.MovieList; import com.androidtime.mvp.Retrofit.ApiInterface; import com.androidtime.mvp.Retrofit.Constant; import com.androidtime.mvp.Retrofit.RetrofitClient; import com.androidtime.mvp.interfaces.OnRequestComplete; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class InvokeApi { OnRequestComplete requestComplete; public InvokeApi(final Context context, final OnRequestComplete onRequestComplete) { this.requestComplete = onRequestComplete; ApiInterface apiInterface= RetrofitClient.getApiInterface(); Call<MovieList> call=apiInterface.getMovieList(Constant.Api); call.enqueue(new Callback<MovieList>() { @Override public void onResponse(Call<MovieList> call, Response<MovieList> response) { MovieList movieList=response.body(); onRequestComplete.onRequestComplete(movieList); } @Override public void onFailure(Call<MovieList> call, Throwable t) { onRequestComplete.onRequestError("Something went wrong.."); } }); } }
true
4a0d621f1a27cbe81bee18ebd0ea8212c34014bc
Java
Maciek-R/Tendo-Game
/pl/tendo/MainBoard.java
WINDOWS-1250
7,026
2.84375
3
[]
no_license
package pl.tendo; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionListener; import java.awt.geom.AffineTransform; import java.util.Vector; import javax.swing.JPanel; import pl.tendo.Obiekty.Direction; /** * Klasa abstrakcyjna przechowujca pola i metody wykorzystywane * po stronie serwera oraz klienta tj. obiekty wystpujce na planszy, * rozmiar planszy i klockw oraz metody odpowiedzialne za rysowanie * * @author Maciek Ruszczyk * @see Board * @see ClientBoard */ public abstract class MainBoard extends JPanel { protected final static int BOARD_WIDTH_PIX = 1024; protected final static int BOARD_HEIGHT_PIX = 820; protected final static int WIDTH_KLOCKA = 32; protected final static int HEIGHT_KLOCKA = 32; Player[] player; Helper helper; Vector<Dzialko> dzialo; Vector<Pocisk> pociski; double time_start; double time_elapsed; int wynik[]; long Time_end_round; boolean GameOver = false; public MainBoard(){ //System.out.println("Main"); player = new Player[2]; player[0] = new Player(0); player[1] = new Player(1); helper = new Helper(); dzialo = new Vector<Dzialko>(); createCannons(); pociski = new Vector<Pocisk>(); wynik = new int[2]; wynik[0]=0; wynik[1]=0; Map.init(); } protected void drawPlayer(Graphics g){ Graphics2D g2 = (Graphics2D)g; for(int i=0; i<2; ++i){ if(player[i].look==Direction.Right){ if(player[i].isMoving) g2.drawImage(player[i].im_move, (int)player[i].getPositionX(), (int)player[i].getPositionY(), null); else g2.drawImage(player[i].im, (int)player[i].getPositionX(), (int)player[i].getPositionY(), null); } else{ AffineTransform at = AffineTransform.getTranslateInstance(player[i].getPositionX(), player[i].getPositionY()); at.translate(player[i].WIDTH, 0); at.scale(-1, 1); if(player[i].isMoving){ g2.drawImage(player[i].im_move, at, null); } else{ g2.drawImage(player[i].im, at, null); } } } } protected void drawBullets(Graphics g){ for(int i=0; i<pociski.size(); ++i) g.drawImage(Pocisk.im, (int)pociski.elementAt(i).getPositionX(), (int)pociski.elementAt(i).getPositionY(), null); } protected void drawGifts(Graphics g){ for(int i=0; i<helper.gifts.size(); ++i) if(helper.gifts.elementAt(i).gift==0) g.drawImage(helper.im_hp, (int)helper.gifts.elementAt(i).getPositionX(), (int)helper.gifts.elementAt(i).getPositionY(), null); else if(helper.gifts.elementAt(i).gift==1) g.drawImage(helper.im_ammo, (int)helper.gifts.elementAt(i).getPositionX(), (int)helper.gifts.elementAt(i).getPositionY(), null); } protected void drawHelper(Graphics g){ if(helper.dir == Direction.Left) g.drawImage(helper.im, (int)helper.getPositionX(), (int)helper.getPositionY(), null); else{ g.drawImage(helper.im, (int)helper.getPositionX()+ helper.WIDTH, (int)helper.getPositionY(), -helper.WIDTH, helper.HEIGHT, null); } } protected void drawMap(Graphics g){ //g.setColor(Color.BLACK); for(int j=0; j<24; ++j){ for(int i=0; i<32; ++i){ if(Map.get(i, j)==1){ g.drawImage(Map.texture_grass, i*WIDTH_KLOCKA, j*HEIGHT_KLOCKA, null); //g.fillRect(i*WIDTH_KLOCA, j*HEIGHT_KLOCA, WIDTH_KLOCA, HEIGHT_KLOCA); } else if(Map.get(i, j)==2){ g.drawImage(Map.texture_wall, i*WIDTH_KLOCKA, j*HEIGHT_KLOCKA, null); } else if(Map.get(i, j)==3){ g.drawImage(Map.texture_kola_arm_r, i*WIDTH_KLOCKA, j*HEIGHT_KLOCKA, null); } else if(Map.get(i, j)==4){ //g.fillRect(i*WIDTH_KLOCKA, j*HEIGHT_KLOCKA, WIDTH_KLOCKA, HEIGHT_KLOCKA); double kat=0; for(int k=0; k<dzialo.size(); ++k) if(dzialo.get(k).getPositionX() == i*WIDTH_KLOCKA && dzialo.get(k).getPositionY() == j*HEIGHT_KLOCKA) kat = dzialo.get(k).kat; AffineTransform at = AffineTransform.getTranslateInstance(i*WIDTH_KLOCKA, j*HEIGHT_KLOCKA); at.rotate(Math.toRadians(kat), 0, Map.texture_lufa_r.getHeight(null)/2 - 4); Graphics2D g2 = (Graphics2D)g; g2.drawImage(Map.texture_lufa_r, at, null); } else if(Map.get(i, j)==5){ g.drawImage(Map.texture_kola_arm_l, i*WIDTH_KLOCKA, j*HEIGHT_KLOCKA, null); } else if(Map.get(i, j)==6){ double kat=0; for(int k=0; k<dzialo.size(); ++k) if(dzialo.get(k).getPositionX() == i*WIDTH_KLOCKA && dzialo.get(k).getPositionY() == j*HEIGHT_KLOCKA) kat = dzialo.get(k).kat; AffineTransform at = AffineTransform.getTranslateInstance(i*WIDTH_KLOCKA, j*HEIGHT_KLOCKA); at.rotate(Math.toRadians(-kat), Map.texture_lufa_l.getWidth(null), Map.texture_lufa_l.getHeight(null)/2 - 4); Graphics2D g2 = (Graphics2D)g; g2.drawImage(Map.texture_lufa_l, at, null); } else if(Map.get(i, j)==7){ g.drawImage(Map.texture_dirt, i*WIDTH_KLOCKA, j*HEIGHT_KLOCKA, null); } } } } protected void drawHealth(Graphics g){ g.setColor(Color.red); g.fillRect(50, 780, player[0].HP, 20); g.fillRect(1024-50-250, 780, player[1].HP, 20); g.setColor(Color.black); g.drawRect(50, 780, 100, 20); g.drawRect(1024-50-250, 780, 100, 20); //ammo g.setColor(Color.orange); g.fillRect(200, 780, (int)(((double)(player[0].ammo)/30)*100), 20); g.fillRect(1024-50-100, 780, (int)(((double)(player[1].ammo)/30)*100), 20); g.setColor(Color.black); g.drawRect(200, 780, 100, 20); g.drawRect(1024-50-100, 780, 100, 20); //wynik g.setColor(Color.red); g.drawString(new Integer(wynik[0]).toString(), 400, 800); g.drawString(new Integer(wynik[1]).toString(), 600, 800); } protected static void drawGrid(Graphics g){ g.setColor(Color.GREEN); for(int i=0; i<32; ++i){ g.drawLine(i*WIDTH_KLOCKA, 0, i*WIDTH_KLOCKA, BOARD_HEIGHT_PIX); } for(int i=0; i<24; ++i){ g.drawLine(0, i*HEIGHT_KLOCKA, BOARD_WIDTH_PIX, i*HEIGHT_KLOCKA); } } protected void drawNumbers(Graphics g){ g.setColor(Color.RED); Integer X = new Integer(0); Integer Y = new Integer(0); for(int j=0; j<24; ++j){ for(int i=0; i<32; ++i){ g.drawString(X.toString()+";"+Y.toString(), i*WIDTH_KLOCKA, j*HEIGHT_KLOCKA+20); ++X; } X=0; ++Y; } } public void paint(Graphics g){ super.paint(g); g.drawImage(Map.bg, 0, 0, null); drawMap(g); drawHealth(g); drawBullets(g); drawHelper(g); drawGifts(g); drawPlayer(g); } private void createCannons(){ for(int j=0; j<24; ++j){ for(int i=0; i<32; ++i){ if(Map.get(i, j)==4){ //right dzialo.addElement(new Dzialko(i*WIDTH_KLOCKA, j*HEIGHT_KLOCKA, Direction.Right)); //System.out.println("stworzono dzialo r"); } else if(Map.get(i, j)==6){ //left dzialo.addElement(new Dzialko(i*WIDTH_KLOCKA, j*HEIGHT_KLOCKA, Direction.Left)); //System.out.println("stworzono dzialo l"); } } } } }
true
08f59b5e3ba5dd5ccf6e8198a0bb236f207c16ff
Java
saber13812002/DeepCRM
/Code Snippet Repository/Log4j/Log4j2577.java
UTF-8
1,128
2.953125
3
[]
no_license
@Test public void testThreads() throws Exception { final Thread[] threads = new Thread[THREADS]; final UUID[] uuids = new UUID[COUNT * THREADS]; final long[] elapsed = new long[THREADS]; for (int i=0; i < THREADS; ++i) { threads[i] = new Worker(uuids, elapsed, i, COUNT); } for (int i=0; i < THREADS; ++i) { threads[i].start(); } long elapsedTime = 0; for (int i=0; i < THREADS; ++i) { threads[i].join(); elapsedTime += elapsed[i]; } System.out.println("Elapsed for " + COUNT * THREADS + " UUIDS = " + elapsedTime + " Average = " + elapsedTime / (COUNT * THREADS) + " ns"); int errors = 0; for (int i=0; i < COUNT * THREADS; ++i) { for (int j=i+1; j < COUNT * THREADS; ++j) { if (uuids[i].equals(uuids[j])) { ++errors; System.out.println("UUID " + i + " equals UUID " + j); } } } assertEquals(errors + " duplicate UUIDS", 0, errors); }
true
bd41eba1f410b515058aff196039086c8b76ac86
Java
lisongtaoJava/project1231
/lisongtao-manage-web/src/main/java/com/atlisongtao/project1231/manage/controller/SpuManageController.java
UTF-8
844
1.898438
2
[]
no_license
package com.atlisongtao.project1231.manage.controller; import com.alibaba.dubbo.config.annotation.Reference; import com.atlisongtao.project1231.bean.SpuInfo; import com.atlisongtao.project1231.service.ManageService; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.List; public class SpuManageController { @Reference private ManageService manageService; @RequestMapping("spuListPage") public String spuListPage() { return "spuListPage"; } @RequestMapping("spuList") @ResponseBody public List<SpuInfo> spuList(String catalog3Id) { //声明spuInfo对象 SpuInfo spuInfo = new SpuInfo(); spuInfo.setCatalog3Id(catalog3Id); return manageService.getSpuInfoList(spuInfo); } }
true
330518e330445b95b13292154de2b92ebc0f8923
Java
Hakroddun/ItemManager
/test/User/AddUser/usecases/AddUserInteractorImplTest.java
UTF-8
938
2.21875
2
[ "MIT" ]
permissive
package User.AddUser.usecases; import User.entities.User; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * Created by gideon on 7/28/2017. */ public class AddUserInteractorImplTest { private AddUserInteractorImpl interactor; @Before public void setUp() { interactor = new AddUserInteractorImpl(); } @Test public void AddNewUserSuccess() { GatewaySuccessfulStub gateway = new GatewaySuccessfulStub(); interactor.setGateway(gateway); User user = new User(); Assert.assertEquals(interactor.insertUser(user), interactor.USER_ADDITION_SUCCESS); } @Test public void AddNewUserFail() { GatewayFailureStub gateway = new GatewayFailureStub(); interactor.setGateway(gateway); User user = new User(); Assert.assertEquals(interactor.insertUser(user), interactor.USER_ADDITION_FAILURE); } }
true
cd281eef1df6a72c5ade0a8e7951ad3e01977cc0
Java
ondrasej/Sudoku-Solver
/src/cz/matfyz/sykora/sudoku/Field.java
UTF-8
4,459
3.28125
3
[]
no_license
/* This file is part of Sudoku Solver. Sudoku Solver is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Sudoku Solver is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Sudoku Solver. If not, see <http://www.gnu.org/licenses/>. */ package cz.matfyz.sykora.sudoku; /** * Represents a single cell in the game. * * @author Ondrej Sykora */ public class Field { /** * Set to <code>true</code> if a value is assigned to the cell. * * @see #assignedValue * @see #clearValue() * @see #hasFixedValue() * @see #setValue(int) */ private boolean valueFixed; /** * Contains the value assigned to the cell. * * @see #valueFixed * @see #getValue() * @see #setValue(int) */ private int assignedValue; /** * A bit mask that contains the list of all values that can be * assigned to this cell. * * @see #valueFixed * @see #clearPossibleValue(int) */ private int possibleValues; /** * Copies all values (assignment, possible values) from the given cell. * * @param source the cell, from which the values are copied. */ public final void assign(Field source) { valueFixed = source.valueFixed; assignedValue = source.assignedValue; possibleValues = source.possibleValues; } /** * If there is only one value that can be assigned to the cell, assigns * it to the cell. */ public final void assignSinglePossibleValue() { int pos_val = possibleValues; int val = 1; while(pos_val != 0 && ((pos_val & 1) == 0)) { pos_val >>= 1; val++; } assignedValue = val; valueFixed = true; } /** * Removes the given value from the list of possible values for this cell. * * @param value the value that is removed from the list. */ public final void clearPossibleValue(int value) { possibleValues &= ~(1 << (value - 1)); } /** * Removes the value assigned to the cell. */ public final void clearValue() { valueFixed = false; possibleValues = (1 << Sudoku.GAME_SIZE) - 1; } /** * Returns the value assigned to the cell. * * @return the value assigned to the cell. */ public final int getValue() { return assignedValue; } /** * Checks if a value is assigned to the cell. * * @return <code>true</code> if a value is assigned to the cell; otherwise, * <code>false</code>. */ public final boolean hasFixedValue() { return valueFixed; } /** * Checks that the list of possible values for this cell is not empty. * * @return <code>true</code> if the list is not empty; otherwise, <code>false</code>. */ public final boolean hasPossibleValues() { return possibleValues != 0; } /** * Checks that there is a single value that can be assigned to the cell. * * @return <code>true</code> if there is just a single value that can be * assigned to the cell; otherwise, <code>false</code>. */ public final boolean hasSinglePossibleValue() { int pos_val = possibleValues; while(pos_val != 0 && ((pos_val & 1) == 0)) pos_val >>= 1; return pos_val == 1; } /** * Checks whether <code>value</code> can be assigned to the cell. * * @param value the tested value. * @return <code>true</code> if <code>value</code> can be assigned to the * cell; otherwise, <code>false</code>. */ public final boolean isPossibleValue(int value) { int mask = 1 << (value - 1); return 0 != (possibleValues & mask); } /** * Assigns the given value to the cell. * * @param value the value assigned to the cell. */ public final void setValue(int value) { valueFixed = true; assignedValue = value; } /** * Creates a new unassigned cell. */ public Field() { clearValue(); } /** * Creates a clone of the given cell. * * @param source the cell, from which the values are cloned. */ public Field(Field source) { assign(source); } }
true
eb36721b6e7c562fc3ed96035aa66b3e58d3b4dd
Java
sunnyday94/annualconvention
/annualconvention-business/annualconvention-utils/src/main/java/com/chunmi/annualconvention/utils/Constant.java
UTF-8
150
1.507813
2
[]
no_license
package com.chunmi.annualconvention.utils; public interface Constant { String LOGIN_MANAGER = "loginManager"; String USER_TOKEN = "annualconvention:user"; }
true
f3b49da93ccb260cf23e13b4a33a5edab272a041
Java
MarchNineteen/spring-example
/spring-example-shiro/src/main/java/com/wyb/shiro/result/web/ErrorMessage.java
UTF-8
1,110
2.515625
3
[ "MIT" ]
permissive
package com.wyb.shiro.result.web; import org.springframework.util.StringUtils; /** * 错误消息对象 * * @author Kunzite */ public class ErrorMessage implements Comparable<ErrorMessage> { /** * 出错的property */ private String field; /** * 错误码 */ private String code; /** * 提示信息 */ private String message; /** * 构造方法 * * @param field * @param message */ public ErrorMessage(String field, String code, String message) { this.field = field; this.code = code; this.message = message; } public String getField() { return field; } public void setField(String field) { this.field = field; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } @Override public int compareTo(ErrorMessage errMsg) { if (!StringUtils.isEmpty(errMsg.getField()) && !StringUtils.isEmpty(this.field)) { return errMsg.getField().compareTo(field); } return 0; } }
true
568c130f34457ae7727c1cd1133dd44e101dec34
Java
singhrahulkumar/sapients
/MyTest/MyTest/src/com/inheritance/ChildPriority.java
UTF-8
356
3.21875
3
[]
no_license
package com.inheritance; class Parent{ public void m1(Object o) { System.out.println("Object --"+ o); } public void m1(String s) { System.out.println("String -- "+s); } } public class ChildPriority { public static void main(String[] args) { Parent p = new Parent(); p.m1("Abc"); p.m1(Integer.valueOf(10)); p.m1(null);// } }
true
17ced977c02f33be202d6e2212e87b3789b10f46
Java
MinhLuongVu/PhanMemQuanLyNhaHang
/Android/app/src/main/java/com/example/quanlynhahang/ui/tools/ThucDon.java
UTF-8
1,114
2.21875
2
[]
no_license
package com.example.quanlynhahang.ui.tools; public class ThucDon { private String TenMon; private String HinhAnh; private String DonGia; private String SoLuong; private String ThanhTien; private String MaGoiMon; private String MaMon; public ThucDon(String tenMon, String hinhAnh, String donGia, String soLuong, String thanhTien, String maGoiMon, String maMon) { TenMon = tenMon; HinhAnh = hinhAnh; DonGia = donGia; SoLuong = soLuong; ThanhTien = thanhTien; MaGoiMon = maGoiMon; MaMon = maMon; } public String getTenMon() { return TenMon; } public String getHinhAnh() { return HinhAnh; } public String getDonGia() { return DonGia; } public String getSoLuong() { return SoLuong; } public String getThanhTien() { return ThanhTien; } public String getMaGoiMon() { return MaGoiMon; } public String getMaMon() { return MaMon; } @Override public String toString() { return MaGoiMon; } }
true
080def4fadf9f0b27f22df4555d1a56a7221349d
Java
dydo32/springbasic
/src/jdbc/jdbc/EmpSystem.java
UTF-8
167
1.65625
2
[]
no_license
package jdbc.jdbc; public class EmpSystem { public static void main(String[] args) { MenuUI ui = new MenuUI(); while(true){ ui.show(); } } }
true
f48aa6a780372f673274d7d999f6df1d21032e16
Java
rvanbuijtenen/sqat-rug-project
/jpacman-instrumented/src/main/java/nl/tudelft/jpacman/board/Unit.java
UTF-8
3,309
3.25
3
[ "Apache-2.0" ]
permissive
package nl.tudelft.jpacman.board; import nl.tudelft.jpacman.sprite.Sprite; import nl.tudelft.jpacman.Api; public abstract class Unit { /** * The square this unit is currently occupying. */ private Square square; /** * The direction this unit is facing. */ private Direction direction; /** * Creates a unit that is facing east. */ protected Unit() { this.direction = Direction.EAST; } /** * Sets this unit to face the new direction. * @param newDirection The new direction this unit is facing. */ public void setDirection(Direction newDirection) {Api.hit("/src/main/java/nl/tudelft/jpacman/board/Unit.java", "setDirection", "lines 34:2 - 34:32"); this.direction = newDirection;} /** * Returns the current direction this unit is facing. * @return The current direction this unit is facing. */ public Direction getDirection() {Api.hit("/src/main/java/nl/tudelft/jpacman/board/Unit.java", "getDirection", "lines 42:2 - 42:24"); return this.direction;} /** * Returns the square this unit is currently occupying. * * @return The square this unit is currently occupying, or <code>null</code> * if this unit is not on a square. */ public Square getSquare() {Api.hit("/src/main/java/nl/tudelft/jpacman/board/Unit.java", "getSquare", "lines 52:2 - 52:21"); assert invariant(); Api.hit("/src/main/java/nl/tudelft/jpacman/board/Unit.java", "getSquare", "lines 53:2 - 53:16"); return square;} /** * Occupies the target square iff this unit is allowed to as decided by * {@link Square#isAccessibleTo(Unit)}. * * @param target * The square to occupy. */ public void occupy(Square target) {Api.hit("/src/main/java/nl/tudelft/jpacman/board/Unit.java", "occupy", "lines 64:2 - 64:24"); assert target != null; Api.hit("/src/main/java/nl/tudelft/jpacman/board/Unit.java", "occupy", "lines 66:2 - 68:3"); if (square != null) { square.remove(this); } Api.hit("/src/main/java/nl/tudelft/jpacman/board/Unit.java", "occupy", "lines 69:2 - 69:18"); square = target; Api.hit("/src/main/java/nl/tudelft/jpacman/board/Unit.java", "occupy", "lines 70:2 - 70:19"); target.put(this); Api.hit("/src/main/java/nl/tudelft/jpacman/board/Unit.java", "occupy", "lines 71:2 - 71:21"); assert invariant();} /** * Leaves the currently occupying square, thus removing this unit from the board. */ public void leaveSquare() {Api.hit("/src/main/java/nl/tudelft/jpacman/board/Unit.java", "leaveSquare", "lines 78:2 - 81:3"); if (square != null) { square.remove(this); square = null; } Api.hit("/src/main/java/nl/tudelft/jpacman/board/Unit.java", "leaveSquare", "lines 82:2 - 82:21"); assert invariant();} /** * Tests whether the square this unit is occupying has this unit listed as * one of its occupiers. * * @return <code>true</code> if the square this unit is occupying has this * unit listed as one of its occupiers, or if this unit is currently * not occupying any square. */ protected boolean invariant() {Api.hit("/src/main/java/nl/tudelft/jpacman/board/Unit.java", "invariant", "lines 94:2 - 94:64"); return square == null || square.getOccupants().contains(this);} /** * Returns the sprite of this unit. * * @return The sprite of this unit. */ public abstract Sprite getSprite(); }
true
4d2b317ea8f17550d7ad18a968e79aba11a949d6
Java
Ford-gxq/crm
/src/main/java/com/xxxx/crm/mapper/SaleChanceMapper.java
UTF-8
659
1.960938
2
[]
no_license
package com.xxxx.crm.mapper; import com.xxxx.crm.base.BaseMapper; import com.xxxx.crm.vo.SaleChance; import org.springframework.dao.DataAccessException; /** 由于考虑到多个模块均涉及多条件查询 这里对于多条件分页查询方法由父接口BaseMapper定义 */ public interface SaleChanceMapper extends BaseMapper<SaleChance,Integer> { // int deleteByPrimaryKey(Integer id); // // int insert(SaleChance record); // // int insertSelective(SaleChance record); // // SaleChance selectByPrimaryKey(Integer id); // // int updateByPrimaryKeySelective(SaleChance record); // // int updateByPrimaryKey(SaleChance record); }
true
428422e563b8ffc880002e800cbc251f623f9f36
Java
Bringordie/securityexam_backend
/src/main/java/entities/Friends.java
UTF-8
1,354
2.328125
2
[]
no_license
package entities; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.NamedQuery; import javax.persistence.Table; /** * * @author Frederik Braagaard */ @Entity @NamedQuery(name = "Friends.deleteAllRows", query = "DELETE from Friends") @Table(name = "friends") public class Friends implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "user_friend") private int friendUsernameID; public Friends() { } public Friends(int friendUsernameID) { this.friendUsernameID = friendUsernameID; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public int getFriendUsernameID() { return friendUsernameID; } public void addFriend(int friendUsernameID) { this.friendUsernameID = friendUsernameID; } @Override public String toString() { return "Friends{" + "id=" + id + ", friendUsernameID=" + friendUsernameID + '}'; } }
true
e5b0ec2952a9d3b3af59b4379bebea0b12a6f58d
Java
kajal414/Test11
/src/main/java/com/example/demo/Sport.java
UTF-8
449
2.390625
2
[]
no_license
package com.example.demo; public class Sport { private int spid; private String spname; public Sport() { super(); } public Sport(int spid, String spname) { super(); this.spid = spid; this.spname = spname; } public int getSpid() { return spid; } public void setSpid(int spid) { this.spid = spid; } public String getSpname() { return spname; } public void setSpname(String spname) { this.spname = spname; } }
true
8238b82653f769a86e39b3237d2c519153c07b9a
Java
papastar/Park
/app/src/main/java/com/ansai/uparking/mvp/presenter/MainFragmentPresenter.java
UTF-8
419
1.8125
2
[]
no_license
package com.ansai.uparking.mvp.presenter; import com.ansai.uparking.entity.database.BleData; import com.ansai.uparking.mvp.MainFragmentContract; /** * Created by Administrator on 2016/11/13. */ public class MainFragmentPresenter extends MainFragmentContract.Presenter { @Override public void checkLockers() { BleData bleData = mModel.queryLockers(); if(bleData!=null){ } } }
true
e597389c206895edeb3183a31496b013f595a322
Java
cpppwner/NoRiskNoFun
/core/src/gmbh/norisknofun/game/networkmessages/waitingforplayers/PlayerAccepted.java
UTF-8
1,050
2.609375
3
[ "MIT" ]
permissive
package gmbh.norisknofun.game.networkmessages.waitingforplayers; /** * Created by Philipp Mödritscher on 10.05.2017. */ import gmbh.norisknofun.game.Player; /** * If Player can Join then Server sends true otherwise PlayerRejected * * Server to Client */ public class PlayerAccepted extends PlayerJoined { private String playerId; private int playerColor; private int maxNumPlayers; private String mapName; public PlayerAccepted(Player player) { super(player.getPlayerName()); playerId = player.getId(); playerColor = player.getColor(); } public String getPlayerId() { return playerId; } public int getPlayerColor() { return playerColor; } public int getMaxNumPlayers() { return maxNumPlayers; } public void setMaxNumPlayers(int maxNumPlayers) { this.maxNumPlayers = maxNumPlayers; } public String getMapName() { return mapName; } public void setMapName(String mapName) { this.mapName = mapName; } }
true
1d4bacebb6516fc569b8a38b2627279b42c08919
Java
swethamudunri/StudentRegistration
/src/test/java/com/domain/StudentDTOsTest.java
UTF-8
618
2.390625
2
[]
no_license
package com.domain; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; import java.util.ArrayList; import java.util.List; import org.junit.Test; public class StudentDTOsTest { @Test public void testStudentDTO() { StudentDTO studentDAO = new StudentDTO(); studentDAO.setCourse("Java"); studentDAO.setId("1"); studentDAO.setName("abc"); List<StudentDTO> dtos = new ArrayList<StudentDTO>(); dtos.add(studentDAO); StudentDTOs studentDTOs = new StudentDTOs(dtos); assertThat(studentDTOs.student.get(0).getId(), equalTo("1")); } }
true
8a65b91dc6ba13b40b6980d6b3d49dbf164ecd5b
Java
aayushshahh/Soulpaints
/app/src/main/java/com/aayushh/profilepage/ShopListAdapter.java
UTF-8
3,128
2.21875
2
[]
no_license
package com.aayushh.profilepage; import android.content.Context; import android.media.Image; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import org.w3c.dom.Text; import java.util.List; public class ShopListAdapter extends RecyclerView.Adapter<ShopListAdapter.ViewHolder> { List<ShoplistModel> shoplistModelList; private ViewHolder.OnShopListener mOnShopListener; public ShopListAdapter(List<ShoplistModel> modelList, ViewHolder.OnShopListener onShopListener) { this.shoplistModelList = modelList; this.mOnShopListener = onShopListener; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { Context context = parent.getContext(); LayoutInflater inflater = LayoutInflater.from(context); View bIView = inflater.inflate(R.layout.shop_layout, parent, false); ShopListAdapter.ViewHolder viewHolder = new ShopListAdapter.ViewHolder(bIView, mOnShopListener); return viewHolder; } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { ShoplistModel shoplistModel = shoplistModelList.get(position); ImageView iView = holder.imageView; iView.setImageResource(shoplistModel.getImgsrc()); TextView tView = holder.textView; tView.setText(shoplistModel.getPaintingName()); TextView tView1 = holder.textView1; tView1.setText(shoplistModel.getDescription()); TextView tView2 = holder.textView2; String priceTag = "RS. " + shoplistModel.getPrice(); tView2.setText(priceTag); } @Override public int getItemCount() { return shoplistModelList.size(); } public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { public ImageView imageView; public TextView textView, textView1, textView2; OnShopListener onShopListener; public ViewHolder(@NonNull View itemView, OnShopListener onShopListener) { super(itemView); imageView = (ImageView) itemView.findViewById(R.id.imageView2); textView = (TextView) itemView.findViewById(R.id.textView5); textView1 = (TextView) itemView.findViewById(R.id.shopDesc); textView2 = (TextView) itemView.findViewById(R.id.price); this.onShopListener = onShopListener; itemView.setOnClickListener(this); } public ImageView getImageView(){return imageView;} public TextView getTextView(){return textView;} public TextView getTextView1() {return textView1;} public TextView getTextView2() {return textView2;} @Override public void onClick(View v) { onShopListener.onShopClick(getAdapterPosition()); } public interface OnShopListener{ void onShopClick(int position); } } }
true
bd836e8dea2a24610289e00e6ed7a955c7d84882
Java
Abdou-ch-d/La-Gazelle
/src/Classes/Salle.java
UTF-8
1,815
2.84375
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 Classes; /** * * @author Crash */ public class Salle { private String num_s ; private String type_s ; private double prix_s=0 ; private String disponible ; public Salle() { } public Salle(String num_s, String type_s, int prix_s, String disponible) { this.num_s = num_s; this.type_s = type_s; this.prix_s = prix_s; this.disponible = disponible; } public String getNum_s() { return num_s; } public String getType_s() { return type_s; } public double getPrix_s() { return prix_s; } public String isDisponible() { return disponible; } public void setNum_s(String num_s) { this.num_s = num_s; } public void setType_s(String type_s) { this.type_s = type_s; } public void setPrix_s(int prix_s) { this.prix_s = prix_s; } public void setDisponible(boolean disponible) { if(disponible==true){ this.disponible="despo"; }else { this.disponible="occup";} } public double PrixSalleJ(String Typesalle){ if(Typesalle.equals("salle des fetes")){ prix_s=prix_s+1500000; }else if (Typesalle.equals("salle des congrès")){ prix_s=prix_s+800000; }else if(Typesalle.equals("Auditorium")){ prix_s=prix_s+500000; } return prix_s; } @Override public String toString() { return "Salle{" + "num_s=" + num_s + ", type_s=" + type_s + ", prix_s=" + prix_s + ", disponible=" + disponible + '}'; } }
true
05ea0587656be93ca41fe85b3eff2561c74d02f1
Java
devacfr/capsicum
/capsicum-testing/src/main/java/org/cfr/capsicum/test/AbstractSimpleCayenneJUnitTests.java
UTF-8
5,047
1.796875
2
[ "Apache-2.0" ]
permissive
/** * Copyright 2014 devacfr<christophefriederich@mac.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.cfr.capsicum.test; import java.io.File; import java.io.FileNotFoundException; import javax.sql.DataSource; import org.apache.cayenne.access.dbsync.CreateIfNoSchemaStrategy; import org.apache.cayenne.access.dbsync.SchemaUpdateStrategy; import org.apache.cayenne.dba.DbAdapter; import org.apache.cayenne.dba.derby.DerbyAdapter; import org.apache.commons.dbcp.BasicDataSource; import org.apache.derby.jdbc.EmbeddedDriver; import org.cfr.capsicum.ICayenneRuntimeContext; import org.cfr.capsicum.access.CustomDataDomainDefinition; import org.cfr.capsicum.access.DataDomainDefinition; import org.cfr.capsicum.spring.server.ServerRuntimeFactoryBean; import org.cfr.commons.util.Assert; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.DisposableBean; import org.springframework.util.FileSystemUtils; import org.springframework.util.Log4jConfigurer; import com.google.common.collect.Lists; public abstract class AbstractSimpleCayenneJUnitTests extends EasyMockTestCase { protected static final File WORK_HOME = new File(getBasedir(), "target/work"); private static String basedir; /** * Logger available to subclasses. */ protected final Logger logger = LoggerFactory.getLogger(getClass()); private static BasicDataSource datasource; private static ICayenneRuntimeContext context; private String domainFileLocation; private String domainName; private Class<SchemaUpdateStrategy> overrideStrategy; static { try { Log4jConfigurer.initLogging("classpath:log4j.xml"); } catch (FileNotFoundException e) { e.printStackTrace(); } } public AbstractSimpleCayenneJUnitTests() { super(); } public AbstractSimpleCayenneJUnitTests(final String domainName, final String domainFileLocation) { super(); this.domainFileLocation = Assert.hasText(domainFileLocation); this.domainName = Assert.hasText(domainName); try { context = createCayenneContext(); } catch (Exception e) { throw new RuntimeException("Error when initialization of cayenne", e); } } public static String getBasedir() { if (basedir != null) { return basedir; } basedir = System.getProperty("basedir"); if (basedir == null) { basedir = new File("").getAbsolutePath(); } return basedir; } @BeforeClass public static void init() throws Exception { basedir = getBasedir(); } @Override @Before public void setUp() throws Exception { super.setUp(); FileSystemUtils.deleteRecursively(WORK_HOME); WORK_HOME.mkdirs(); } protected static DataSource createDatasource() { BasicDataSource ds = new BasicDataSource(); ds.setDriverClassName(EmbeddedDriver.class.getCanonicalName()); ds.setUrl("jdbc:derby:memory:testdb;create=true"); datasource = ds; return ds; } protected ICayenneRuntimeContext getCayenneContext() { return context; } @SuppressWarnings("unchecked") protected ICayenneRuntimeContext createCayenneContext() throws Exception { ServerRuntimeFactoryBean factory = new ServerRuntimeFactoryBean(); factory.setDefaultSchemaUpdateStrategy((Class<SchemaUpdateStrategy>) (overrideStrategy != null ? overrideStrategy : CreateIfNoSchemaStrategy.class)); factory.setDataSource(createDatasource()); CustomDataDomainDefinition dataDomainDefinition = new CustomDataDomainDefinition(); dataDomainDefinition.setName(domainName); dataDomainDefinition.setLocation(domainFileLocation); factory.setDataDomainDefinitions(Lists.<DataDomainDefinition> newArrayList(dataDomainDefinition)); factory.afterPropertiesSet(); return factory; } protected static Class<? extends DbAdapter> getDbAdapter() { return DerbyAdapter.class; } @AfterClass public static void shutdown() throws Exception { if (datasource != null) { datasource.close(); } datasource = null; if (context instanceof DisposableBean) { ((DisposableBean) context).destroy(); } context = null; } }
true
5c69f243b7f74934c8bec2c43948448082d23ea2
Java
raviasthana/DataStructuresAlgorithmsAndCollections
/DataStructuresAlgorithmsAndCollections/src/com/indef/sorting/BubbleSort.java
UTF-8
650
3.734375
4
[]
no_license
package com.indef.sorting; public class BubbleSort { public static void main(String[] args) { //int a[] = {5,1,6,2,4,3}; int a[] = {6,5,4,3,2,1}; int nItems = a.length; int temp = 0; boolean sorted = true; for(int i=0; i<nItems; i++){ sorted = true; for(int j=0; j<nItems-i-1; j++){ if(a[j] > a[j+1]){ temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; sorted = false; } } //System.out.println("i[" + i + "]"); if(sorted) break; } System.out.println("Sorted Array using Bubble Sort:"); for(int i=0; i<nItems; i++){ System.out.println(a[i]); } } }
true
3b52eb91969b34ea27beaf20648f72a21ddeb83d
Java
SombreLoup/Enseignement
/2017-2018/M1 INFO/TP_NOTE_ADW_2017-2018/src/bean/BeanMatiere.java
UTF-8
648
2.015625
2
[]
no_license
package bean; import java.io.Serializable; import java.util.List; import core.Matiere; import dao.DAOMatiere; import dao.mock.DAOMatiereMOCK; public class BeanMatiere implements Serializable { private List<Matiere> listeMatieres; private DAOMatiere daoMatiere = DAOMatiereMOCK.getInstance(); public BeanMatiere() { listeMatieres = daoMatiere.getToutesLesMatieres(); } public List<Matiere> getListeMatieres() { return listeMatieres; } public void setListeMatieres(List<Matiere> listeMatieres) { this.listeMatieres = listeMatieres; } /** * */ private static final long serialVersionUID = -2232822555928517369L; }
true
dfd5a5ef77dc5aa6ea6aa0f206d3c656404aa198
Java
waterpolo0822/AndroidPractice
/Spinner3/app/src/main/java/com/example/george/spinner3/Test.java
UTF-8
635
2.1875
2
[]
no_license
package com.example.george.spinner3; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ImageView; import android.widget.TextView; public class Test extends AppCompatActivity { TextView test; ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test); test = (TextView)findViewById(R.id.test); imageView = (ImageView)findViewById(R.id.testimage); DataBase helper = new DataBase(this); helper.show(test,imageView); } }
true
c893d12636de3df1351ce6c9fbe5286f565c68d2
Java
singller/spring-boot-elasticsearch-sample
/src/main/java/com/fengwenyi/spring_boot_elasticsearch_sample/entity/PhoneEntity.java
UTF-8
1,524
2.078125
2
[ "MIT" ]
permissive
package com.fengwenyi.spring_boot_elasticsearch_sample.entity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.experimental.Accessors; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; import java.io.Serializable; import java.math.BigDecimal; /** * 手机实体类 * @author Erwin Feng * @since 2020/7/4 */ //@ApiModel("手机实体类") @Data @Accessors(chain = true) @Document(indexName = "spring-boot-elasticsearch-sample-phone") public class PhoneEntity implements Serializable { /* ID */ @ApiModelProperty("ID") @Id private String id; /* 名称 */ @ApiModelProperty("名称") private String name; /* 推广广告 */ @ApiModelProperty("推广广告") private String ad; /* 售价 */ @ApiModelProperty("售价") private BigDecimal price; /* 图片URL */ @ApiModelProperty("图片URL") private String imgUrl; /* 内存 */ @ApiModelProperty("内存") private String memory; /* 存储 */ @ApiModelProperty("存储") private String storage; /* 屏幕 */ @ApiModelProperty("屏幕") private String screen; /* 创建时间,时间戳,毫秒 */ @ApiModelProperty("创建时间戳(毫秒)") private Long createTimeStamp; /* 创建时间,yyyy-MM-dd HH:mm:ss,SSS */ @ApiModelProperty("创建时间字符串") private String createTimeString; }
true
941fcd6d090f9891d01e61f1308577c57081ee5d
Java
jenkinsci/machine-learning-plugin
/src/test/java/io/jenkins/plugins/ml/IPythonServerGlobalConfigurationTest.java
UTF-8
4,747
1.773438
2
[ "MIT" ]
permissive
/* * The MIT License * * Copyright 2020 Loghi Perinpanayagam. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package io.jenkins.plugins.ml; import com.gargoylesoftware.htmlunit.html.*; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import org.xml.sax.SAXException; import java.io.IOException; import java.util.List; import static junit.framework.TestCase.assertEquals; public class IPythonServerGlobalConfigurationTest { private HtmlForm form; private HtmlPage configPage; @Rule public final JenkinsRule j = new JenkinsRule(); @Before public void setup() throws IOException, SAXException { configPage = j.createWebClient().goTo("configure"); form = configPage.getFormByName("config"); getButton(form, "Add new Kernel") .click(); getButton(form, "Add new Kernel") .click(); } @Test public void reloadConfigPageTest() throws Exception { List<HtmlInput> serverName = form.getInputsByName("_.serverName"); serverName.get(0).setValueAttribute("localHost"); serverName.get(1).setValueAttribute("IPython_Server"); List<HtmlInput> kernel = form.getInputsByName("_.kernel"); kernel.get(0).setValueAttribute("python"); kernel.get(1).setValueAttribute("ir"); List<HtmlInput> launchTimeout = form.getInputsByName("_.launchTimeout"); launchTimeout.get(0).setValueAttribute("5"); launchTimeout.get(1).setValueAttribute("1"); List<HtmlInput> maxResults = form.getInputsByName("_.maxResults"); maxResults.get(0).setValueAttribute("3"); maxResults.get(1).setValueAttribute("1"); j.submit(form); form = configPage.getFormByName("config"); serverName = form.getInputsByName("_.serverName"); kernel = form.getInputsByName("_.kernel"); launchTimeout = form.getInputsByName("_.launchTimeout"); maxResults= form.getInputsByName("_.maxResults"); assertEquals("localHost", serverName.get(0).getValueAttribute()); assertEquals("python", kernel.get(0).getValueAttribute()); assertEquals("5", launchTimeout.get(0).getValueAttribute()); assertEquals("3", maxResults.get(0).getValueAttribute()); assertEquals("IPython_Server", serverName.get(1).getValueAttribute()); assertEquals("ir", kernel.get(1).getValueAttribute()); assertEquals("1", launchTimeout.get(1).getValueAttribute()); assertEquals("1", maxResults.get(1).getValueAttribute()); configPage.refresh(); assertEquals("localHost", serverName.get(0).getValueAttribute()); assertEquals("python", kernel.get(0).getValueAttribute()); assertEquals("5", launchTimeout.get(0).getValueAttribute()); assertEquals("3", maxResults.get(0).getValueAttribute()); assertEquals("IPython_Server", serverName.get(1).getValueAttribute()); assertEquals("ir", kernel.get(1).getValueAttribute()); assertEquals("1", launchTimeout.get(1).getValueAttribute()); assertEquals("1", maxResults.get(1).getValueAttribute()); } /* * Helper function to get button with captions */ public static HtmlButton getButton(HtmlForm form, String caption) { List<HtmlButton> buttons = form.getElementsByAttribute("button", "type", "button"); HtmlButton rtn = null; for (HtmlButton button : buttons) { DomNode child = button.getFirstChild(); if (caption.equals(child.getNodeValue())) { rtn = button; break; } } return rtn; } }
true
4c646d85e761bfccef39e7d515faf122c353b6a6
Java
mainstringargs/alpaca-java
/src/main/java/io/github/mainstringargs/polygon/websocket/listener/PolygonStreamListenerAdapter.java
UTF-8
2,514
2.59375
3
[ "MIT" ]
permissive
package io.github.mainstringargs.polygon.websocket.listener; import io.github.mainstringargs.domain.polygon.websocket.PolygonStreamMessage; import io.github.mainstringargs.polygon.websocket.message.PolygonStreamMessageType; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * The Class PolygonStreamListenerAdapter. */ public class PolygonStreamListenerAdapter implements PolygonStreamListener { /** The stock channel types. */ private Map<String, Set<PolygonStreamMessageType>> stockChannels = new HashMap<>(); /** * Instantiates a new polygon stream listener adapter. * * @param ticker the ticker * @param channelTypes the channel types */ public PolygonStreamListenerAdapter(String ticker, PolygonStreamMessageType... channelTypes) { if (channelTypes != null && channelTypes.length > 0) { this.stockChannels.put(ticker, new HashSet<>(Arrays.asList(channelTypes))); } else { this.stockChannels.put(ticker, new HashSet<>(Arrays.asList(PolygonStreamMessageType.values()))); } } /** * Instantiates a new polygon stream listener adapter. * * @param tickers the tickers * @param channelTypes the channel types */ public PolygonStreamListenerAdapter(Set<String> tickers, PolygonStreamMessageType... channelTypes) { for (String ticker : tickers) { if (channelTypes != null && channelTypes.length > 0) { this.stockChannels.put(ticker, new HashSet<>(Arrays.asList(channelTypes))); } else { this.stockChannels.put(ticker, new HashSet<>(Arrays.asList(PolygonStreamMessageType.values()))); } } } /** * Instantiates a new polygon stream listener adapter. * * @param stockChannels the stock channel types */ public PolygonStreamListenerAdapter(Map<String, Set<PolygonStreamMessageType>> stockChannels) { for (Entry<String, Set<PolygonStreamMessageType>> entry : stockChannels.entrySet()) { this.stockChannels.put(entry.getKey(), new HashSet<>(entry.getValue())); } } @Override public Map<String, Set<PolygonStreamMessageType>> getStockChannels() { return stockChannels; } @Override public void onStreamUpdate(PolygonStreamMessageType streamMessageType, PolygonStreamMessage streamMessage) { } }
true
a8428760482a18d1f2cf131975050dcc139b3e4d
Java
shhashmi/Personal
/locator/src/main/java/com/gojek/locator/dao/DriverLocationDao.java
UTF-8
483
2.4375
2
[]
no_license
package com.gojek.locator.dao; import com.gojek.locator.model.Location; public interface DriverLocationDao { /**Given a driver id this method returns current location of driver. If data for driver * does not exist then null is returned * @param driverId * @return Location */ Location getLocation(Integer driverId); /** Update the current location of driver. * @param driverId * @param location */ void updateLocation(Integer driverId, Location location); }
true
d6d316dbac5ad6aa4ff04051be8a696e454417e5
Java
Hira011/LetsChat
/app/src/main/java/com/harshit/letschat/PasswordReset.java
UTF-8
3,009
2.09375
2
[]
no_license
package com.harshit.letschat; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; public class PasswordReset extends AppCompatActivity { private ImageView ivLogo, ivPWreset; private TextView tvInfo, tvSignin; private TextView email; private Button btnReset; private FirebaseAuth firebaseAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_password_reset); initializeGUI(); btnReset.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String myEmail = email.getText().toString(); if (myEmail.isEmpty()) { email.setError("Please, fill the email field.", null); } else { firebaseAuth.sendPasswordResetEmail(myEmail) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Toast.makeText(PasswordReset.this, "Email has been sent successfully.", Toast.LENGTH_SHORT).show(); finish(); startActivity(new Intent(PasswordReset.this, LoginPage.class)); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(PasswordReset.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } }); } } }); tvSignin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(PasswordReset.this, LoginPage.class)); } }); } private void initializeGUI() { ivLogo = findViewById(R.id.ivLogLogo); ivPWreset = findViewById(R.id.ivPassReset); tvInfo = findViewById(R.id.tvPWinfo); tvSignin = findViewById(R.id.tvGoBack); email = findViewById(R.id.email); btnReset = findViewById(R.id.btnReset); firebaseAuth = FirebaseAuth.getInstance(); } }
true
163a72630b78a67c7c2a6b3037a69c46f4c295ec
Java
popnob/ooptest
/mcp62/temp/src/minecraft/argo/jdom/JsonObject.java
UTF-8
1,571
1.953125
2
[]
no_license
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) braces deadcode fieldsfirst package argo.jdom; import java.util.*; // Referenced classes of package argo.jdom: // JsonRootNode, JsonNodeType final class JsonObject extends JsonRootNode { private final Map field_27222_a; JsonObject(Map p_i363_1_) { field_27222_a = new HashMap(p_i363_1_); } public Map func_27214_c() { return new HashMap(field_27222_a); } public JsonNodeType func_27218_a() { return JsonNodeType.OBJECT; } public String func_27216_b() { throw new IllegalStateException("Attempt to get text on a JsonNode without text."); } public List func_27215_d() { throw new IllegalStateException("Attempt to get elements on a JsonNode without elements."); } public boolean equals(Object p_equals_1_) { if(this == p_equals_1_) { return true; } if(p_equals_1_ == null || getClass() != p_equals_1_.getClass()) { return false; } else { JsonObject jsonobject = (JsonObject)p_equals_1_; return field_27222_a.equals(jsonobject.field_27222_a); } } public int hashCode() { return field_27222_a.hashCode(); } public String toString() { return (new StringBuilder()).append("JsonObject fields:[").append(field_27222_a).append("]").toString(); } }
true
27655e6e6f80c2542a9865bb3a2b5de600e1d529
Java
zohaibakmal/InterviewPrep
/src/com/test/OddFrequencies.java
UTF-8
1,058
3.34375
3
[]
no_license
package com.test; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Iterator; import java.util.Set; public class OddFrequencies { public static ArrayList oddFreq(String [] input){ ArrayList finalList = new ArrayList(); HashMap <String,Integer> map = new HashMap<String,Integer>(); for (int i=0; i<input.length; i++){ if (map.containsKey(input[i])){ int value = map.get(input[i]); map.put(input[i], value+1); } else { map.put(input[i],1); } } Iterator itr = map.entrySet().iterator(); /* while (itr.hasNext()){ Map.Entry <String,Integer> pair = (Map.Entry<String,Integer>) itr.next(); if (pair.getValue()%2==1){ finalList.add(pair.getKey()); } } */ for (String keys:map.keySet()){ if (map.get(keys)%2==1){ finalList.add(keys); } } return finalList; } public static void main(String[] args) { String[] input = {"1","1","1","2","2","2","3", "3"}; System.out.print(oddFreq(input)); } }
true
f1a8b4d6ce29494d420c4d07d5334e44b94df3b2
Java
alexandropg/ProjectCode
/supplier_form.java
UTF-8
11,420
2.1875
2
[]
no_license
package Code; public class SupplierForm extends javax.swing.JFrame { public SupplierForm() { initComponents(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jLabel7 = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); jTextField2 = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); jTextField3 = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jTextField4 = new javax.swing.JTextField(); jTextField5 = new javax.swing.JTextField(); jLabel6 = new javax.swing.JLabel(); jTextField6 = new javax.swing.JTextField(); jLabel8 = new javax.swing.JLabel(); jTextField7 = new javax.swing.JTextField(); jLabel9 = new javax.swing.JLabel(); jTextField8 = new javax.swing.JTextField(); jLabel10 = new javax.swing.JLabel(); jTextField9 = new javax.swing.JTextField(); jLabel11 = new javax.swing.JLabel(); jLabel7.setText("jLabel7"); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setText("Κωδικός Προμηθευτή"); jLabel2.setText("Επωνυμία Προμηθευτή"); jTextField2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField2ActionPerformed(evt); } }); jLabel3.setText("Υπεύθυνος"); jLabel4.setText("Διεύθυνση"); jLabel5.setText("ΤΚ"); jLabel6.setText("Πόλη"); jLabel8.setText("Τηλέφωνο"); jLabel9.setText("Email"); jLabel10.setText("Παρατηρήσεις"); jLabel11.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel11.setText("Καταχώριση Προμηθευτή"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(48, 48, 48) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel10) .addComponent(jLabel8, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, 139, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField7, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField8, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField9, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(31, 31, 31) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jTextField5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE) .addComponent(jTextField3, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jTextField4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE) .addComponent(jTextField2, javax.swing.GroupLayout.Alignment.TRAILING)) .addGap(0, 2, Short.MAX_VALUE)) .addComponent(jTextField1)))) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 176, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(61, 61, 61)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel11) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(25, 25, 25) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(21, 21, 21) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel8) .addComponent(jTextField7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel9) .addComponent(jTextField8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(24, 24, 24) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel10) .addComponent(jTextField9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(32, Short.MAX_VALUE)) ); pack(); }// </editor-fold> private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) { } public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new SupplierForm().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2; private javax.swing.JTextField jTextField3; private javax.swing.JTextField jTextField4; private javax.swing.JTextField jTextField5; private javax.swing.JTextField jTextField6; private javax.swing.JTextField jTextField7; private javax.swing.JTextField jTextField8; private javax.swing.JTextField jTextField9; }
true
441f91998d21e9f0f949431ba7c94682bce1e2dc
Java
Prasadpoojary/Assignment_Of_Java
/src/_05_Datastructure_and_algorithms/Stack/Stack.java
UTF-8
1,556
3.71875
4
[]
no_license
package Stack; public class Stack { int size; public Stack() { } public Stack(int size) { this.size=size; } Node head; public int top=-1; public void push(int data) { if(top<size-1) { Node node=new Node(); node.data=data; node.next=null; if(head==null) { head=node; } else { Node temp=new Node(); temp=head; while(temp.next!=null) { temp=temp.next; } temp.next=node; } top++; } else { System.out.println("\nStack Overflow"); } } public void show() { Node node=new Node(); node=head; try { while(node.next!=null) { System.out.print(node.data); System.out.print(" --> "); node=node.next; } System.out.println(node.data); } catch (Exception e) { System.out.println("No data Found"); } } public int pop() { Node temp; temp=head; int data; if(temp.next!=null) { while(temp.next.next!=null) { temp=temp.next; } data=temp.next.data; temp.next=null; top--; return data; } else { data=head.data; head=null; top--; return data; } } public int len() { return top+1; } public boolean isFound(int data) { Node temp=head; boolean found=false; if(temp.data==data) { found=true; return found; } while(temp.next!=null) { if(temp.data==data || temp.next.data==data) { found=true; break; } temp=temp.next; } return found; } }
true
a1a08cde3a0d2d44a9b86b059b9dc4febbc25348
Java
Kunpengv5/FruitSale
/src/main/java/com/fruitsalesplatform/dao/BaseDao.java
UTF-8
700
2.234375
2
[]
no_license
package com.fruitsalesplatform.dao; import java.io.Serializable; import java.util.List; import java.util.Map; /** * @author dukunpeng * @date 2018/11/15 14:28 * @doc 泛型类,基础的DAO接口,提供统一的增删改查功能 */ public interface BaseDao<T> { T get(Serializable id);//只查询一个数据,常用于修改 (这块有疑问) List<T> find(Map map);//根据条件查询多个结果 void insert(T entity);//插入,使用实体作为参数 void update(T entity);//更新,使用实体作为参数 void deleteById(Serializable id);//按id删除,删除一条;支持整形和字符串类型id void delete(Serializable[] ids);//批量删除 }
true
2e0f0433838c528111c85a11c99a0b791e00dfe3
Java
dnivra26/stuer-android
/app/src/main/java/dnivra26/github/io/stuer/parsemodels/Session.java
UTF-8
1,820
2.125
2
[]
no_license
package dnivra26.github.io.stuer.parsemodels; import com.parse.ParseClassName; import com.parse.ParseGeoPoint; import com.parse.ParseObject; import java.util.Date; @ParseClassName("session") public class Session extends ParseObject { public void setActivity(String activityName) { put("activity", activityName); } public String getActivityName() { return getString("activity"); } public void setSidBool(boolean sidBool) { put("sid_state", sidBool); } public boolean getSidBool() { return getBoolean("sid_state"); } public void setFare(int fare) { put("fare", fare); } public int getFare() { return getInt("fare"); } public void setLocation(ParseGeoPoint parseGeoPoint) { put("location", parseGeoPoint); } public ParseGeoPoint getLocation() { return getParseGeoPoint("location"); } public void setDuration(int duration) { put("duration", duration); } public int getDuration() { return getInt("duration"); } public void setUserId(String uuid) { put("user_uuid", uuid); } public String getUserId() { return getString("user_uuid"); } public void setTime(Date date) { put("time", date); } public String getTime() { Date time = getDate("time"); return time.getYear() + "-" + (time.getMonth() + 1) + "-" + time.getDate() + " " + time.getHours() + ":" + time.getMinutes(); } public void setSid(String uuid) { put("sid", uuid); } public String getSid() { return getString("sid"); } public void setAddress(String address) { put("address", address); } public String getAddress() { return getString("address"); } }
true
f95330cd5d52996b7ed4df4f7bf515b8c9c6eda1
Java
rajeshsht/DMA_ASSIGNMENT
/week2/lab/Activities and intents/TwoActivitiesChallenge/app/src/main/java/com/example/andriod/twoactivitieschallenge/MainActivity.java
UTF-8
1,445
2.328125
2
[]
no_license
package com.example.andriod.twoactivitieschallenge; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.content.res.Resources; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { public final static String Passage1 = "com.example.andriod.passsage1"; public final static String Passage2 = "com.example.andriod.passsage2"; public final static String Passage3 = "com.example.andriod.passsage3"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Resources res = getResources(); String passage1 = res.getString(R.string.passage_one_heading); String passage2 = res.getString(R.string.passage_two_heading); String passage3 = res.getString(R.string.passage_three_heading); } public void textOneLunch(View view){ Intent intent = new Intent(this, SecondActivity.class); // intent.putExtra(Passage1, passage1); startActivity(intent); } public void textTwoLunch(View view){ Intent intent = new Intent(this, SecondActivity.class); startActivity(intent); } public void textThreeLunch(View view){ Intent intent = new Intent(this, SecondActivity.class); startActivity(intent); } }
true
9a5d3e39fcbcf23468ad2fd2bb8539ee81c77a24
Java
altitdb/boletim
/domain/src/main/java/com/boletim/domain/Nota.java
UTF-8
1,392
2.40625
2
[]
no_license
package com.boletim.domain; import java.io.Serializable; import java.math.BigDecimal; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; @Entity public class Nota implements Serializable { private static final long serialVersionUID = 23L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long idNota; private BigDecimal nota; @ManyToOne @JoinColumn(name = "ID_ALUNO") private Aluno aluno; @ManyToOne @JoinColumn(name = "ID_DISCIPLINA") private Disciplina disciplina; @Enumerated(EnumType.STRING) private TipoNota tipo; public void setIdNota(Long idNota) { this.idNota = idNota; } public Long getIdNota() { return idNota; } public void setNota(BigDecimal nota) { this.nota = nota; } public BigDecimal getNota() { return nota; } public void setAluno(Aluno aluno) { this.aluno = aluno; } public Aluno getAluno() { return aluno; } public void setDisciplina(Disciplina disciplina) { this.disciplina = disciplina; } public Disciplina getDisciplina() { return disciplina; } public void setTipo(TipoNota tipo) { this.tipo = tipo; } public TipoNota getTipo() { return tipo; } }
true
5af17bde1d23de7422d821f206e42a864d97433a
Java
developerbhre/vzw-customer-profile-demo
/profile-service/src/main/java/com/vzw/profileservice/service/ProfileService.java
UTF-8
2,544
1.984375
2
[]
no_license
package com.vzw.profileservice.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.EurekaClient; import com.netflix.discovery.shared.Application; import com.vzw.profileservice.models.VZWCustomer; import com.vzw.profileservice.models.VZWEquipment; import com.vzw.profileservice.models.VZWProfile; import reactor.core.publisher.Mono; @Service public class ProfileService { @Value("${user.role}") private String role; @Value("${customer.service.name}") private String customerServiceName; @Value("${equipment.service.name}") private String equipmentServiceName; @Autowired private RestTemplate restTemplate; @Autowired @Lazy private EurekaClient eurekaClient; private static final Logger LOGGER = LoggerFactory.getLogger(ProfileService.class); public Mono<VZWProfile> fetchProfile(Long customerId) { LOGGER.info("Fetching Customer and Equipment details for CustomerId: {}", customerId); Application application = eurekaClient.getApplication(customerServiceName); InstanceInfo instanceInfo = application.getInstances().get(0); //VZWCustomer customer = restTemplate.getForObject("http://localhost:8080/customer/" + customerId, VZWCustomer.class); VZWCustomer customer = restTemplate.getForObject("http://"+application.getName()+"/customer/" + customerId, VZWCustomer.class); //VZWEquipment equipment = restTemplate.getForObject("http://localhost:8081/equipment/customer/" + customerId, VZWEquipment.class); VZWEquipment equipment = restTemplate.getForObject("http://"+eurekaClient.getApplication(equipmentServiceName).getName()+"/equipment/customer/" + customerId, VZWEquipment.class); VZWProfile vzwProfile = new VZWProfile(); vzwProfile.setCustomer_id(customerId); vzwProfile.setFirstName(customer.getFirstName()); vzwProfile.setLastName(customer.getLastName()); vzwProfile.setAddress(customer.getAddress()); vzwProfile.setEquipment(equipment.getEquipment()); return Mono.just(vzwProfile); } public Mono<String> getUserRole(Long customerId) { String message = "Customer Role for:"+customerId+", is-"+role; return Mono.justOrEmpty(message); } }
true
2e34ef9c21835746fe97bb47096edd242f6e6579
Java
rimatik/DrivingSchool-mobile
/app/src/main/java/com/slaven/radja/autoskola/activities/ucenje/znakovi/CommunicatorZnakovi.java
UTF-8
187
1.757813
2
[]
no_license
package com.slaven.radja.autoskola.activities.ucenje.znakovi; /** * Created by slaven.radja on 10.10.2014.. */ public interface CommunicatorZnakovi { public void respond(int i); }
true
31669502cc17c9d7728df675f119dc7379e9d2f0
Java
sandanitg/LotteryDistribution
/nlbdistribution/src/main/java/com/nlbdistribution/controller/DrawController.java
UTF-8
7,753
2.078125
2
[]
no_license
package com.nlbdistribution.controller; import com.nlbdistribution.dao.*; import com.nlbdistribution.entity.Draw; import com.nlbdistribution.entity.Drawsupervisor; import com.nlbdistribution.entity.Lotterytype; import com.nlbdistribution.util.ModuleList; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.data.repository.query.Param; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; @RestController public class DrawController { @Autowired private DrawDao dao; @Autowired private SupervisorDao daoSupervisor; @Autowired private DrawstatusDao daoDrawstatus; @Autowired private LotteryDao daoLottery; @RequestMapping(value = "/draws/list", method = RequestMethod.GET, produces = "application/json") public List<Draw> draw() { return dao.list(); } @RequestMapping(value ="/draws/list/bylottery", params = {"lotterytypeid","dayid"}, method = RequestMethod.GET, produces = "application/json") public List<Draw> draw(@CookieValue(value="username", required = false) String username, @CookieValue(value="password") String password, Integer lotterytypeid, Integer dayid){ if(AuthProvider.isUser(username, password)) return dao.listByLottery(lotterytypeid, dayid); else return null; } @RequestMapping(value ="/draws/list/bylotteryn", params = {"lotteryid"}, method = RequestMethod.GET, produces = "application/json") public List<Draw> draw(@CookieValue(value="username", required = false) String username, @CookieValue(value="password") String password,@Param("lotteryid") Integer lotteryid){ if(AuthProvider.isUser(username, password)) return dao.listByLotteryN(lotteryid); else return null; } @RequestMapping(value = "/draws", params = {"page", "size"}, method = RequestMethod.GET, produces = "application/json") public Page<Draw> findAll(@CookieValue(value = "username") String username, @CookieValue(value = "password") String password, @RequestParam("page") int page, @RequestParam("size") int size) { if (AuthProvider.isAuthorized(username, password, ModuleList.DRAW, AuthProvider.SELECT)) { return dao.findAll(PageRequest.of(page, size)); } return null; } @RequestMapping(value = "/draws", method = RequestMethod.POST) public String add(@CookieValue(value = "username", required = false) String username, @CookieValue(value = "password", required = false) String password, @Validated @RequestBody Draw draw) { if (AuthProvider.isAuthorized(username, password, ModuleList.DRAW, AuthProvider.INSERT)) { Draw drawbyno = dao.findByNoLottery(draw.getNo(),draw.getLotteryId()); if (drawbyno != null) return "Error-Validation : Draw No Exists"; try { for (Drawsupervisor ds : draw.getDrawsupervisorList()) ds.setDrawId(draw); dao.save(draw); return "0"; } catch (Exception e) { return "Error-Saving : " + e.getMessage(); } } return "Error-Inserting : You have no Permission"; } @RequestMapping(value = "/draws", method = RequestMethod.PUT) public String update(@CookieValue(value = "username", required = false) String username, @CookieValue(value = "password", required = false) String password, @Validated @RequestBody Draw draw) { if (AuthProvider.isAuthorized(username, password, ModuleList.DRAW, AuthProvider.UPDATE)) { try { Draw drawfrompersistent = dao.findByNoLottery(draw.getNo(),draw.getLotteryId()); drawfrompersistent.setPrintcount(draw.getPrintcount()); drawfrompersistent.setSuperprice(draw.getSuperprice()); drawfrompersistent.setLocation(draw.getLocation()); drawfrompersistent.setDrawstatusId(draw.getDrawstatusId()); drawfrompersistent.setDate(draw.getDate()); drawfrompersistent.getDrawsupervisorList().clear(); for (Drawsupervisor ds : draw.getDrawsupervisorList()) { drawfrompersistent.getDrawsupervisorList().add(ds); ds.setDrawId(drawfrompersistent); } dao.save(drawfrompersistent); return "0"; } catch (Exception e) { return "Error-Saving : " + e.getMessage(); } } else return "Error-Updating : You have no Permission"; } @RequestMapping(value = "/draws", method = RequestMethod.DELETE) public String delete(@CookieValue(value="username", required=false) String username, @CookieValue(value="password", required=false) String password,@RequestBody Draw draw ) { if(AuthProvider.isAuthorized(username,password,ModuleList.DRAW,AuthProvider.DELETE)) { try { Draw dw = dao.getOne(draw.getId()); dw.getDrawsupervisorList().clear(); dao.save(dw); dao.delete(dw); return "0"; } catch (Exception e) { return "Error-Deleting : " + e.getMessage(); } } else return "Error-Deleting : You have no Permission"; } @RequestMapping(value = "/draws", params = {"page", "size","supervisorid", "drawstatusid", "lotteryid"}, method = RequestMethod.GET, produces = "application/json") public Page<Draw> findAll(@CookieValue(value="username", required=false) String uname, @CookieValue(value="password", required=false) String pword,@RequestParam("page") int page, @RequestParam("size") int size, @RequestParam("supervisorid") Integer supervisorid, @RequestParam("drawstatusid") Integer drawstatusid, @RequestParam("lotteryid") Integer lotteryid) { //System.out.println(drawno+"-"+lotteryid+"-"+drawstatusid); if(AuthProvider.isAuthorized(uname,pword,ModuleList.DRAW,AuthProvider.SELECT)) { List<Draw> draws = dao.findAll(Sort.by(Sort.Direction.DESC, "id")); Stream<Draw> drawstream = draws.stream(); // drawstream = drawstream.filter(d -> !d.getUsername().equals("admin")); if (supervisorid != null) { drawstream = drawstream.filter(d -> { for (Drawsupervisor ds : d.getDrawsupervisorList()) if (ds.getSupervisorId().getId().equals(supervisorid)) return true; return false; }); } if (drawstatusid != null) drawstream = drawstream.filter(d -> d.getDrawstatusId().equals(daoDrawstatus.getOne(drawstatusid))); if (lotteryid != null) drawstream = drawstream.filter(d -> d.getLotteryId().equals(daoLottery.getOne(lotteryid))); List<Draw> draws2 = drawstream.collect(Collectors.toList()); int start = page * size; int end = start + size < draws2.size() ? start + size : draws2.size(); Page<Draw> drawpage = new PageImpl<>(draws2.subList(start, end), PageRequest.of(page, size), draws2.size()); return drawpage; } else return null; } }
true
815c0e0b73d011ef3126f606fa8dc63063ecfadb
Java
hehaoyuan/JAVA
/Java_SE/四种引用类型/WeakHashMap类及其实现.java
UTF-8
1,116
3.296875
3
[]
no_license
WeakHashMap类及其实现 WeakHashMap类在java.util包内,它实现了Map接口,是HashMap的一种实现,它使用弱引用作为内部数据的存储方案。WeakHashMap是弱引用的一种典型应用,它可以作为简单的缓存表解决方案。 一下两段代码分别使用WeakHashMap和HashMap保存大量的数据: @Test public void test4(){ Map map; map = new WeakHashMap<String,Object>(); for (int i =0;i<10000;i++){ map.put("key"+i,new byte[i]); } // map = new HashMap<String,Object>(); // for (int i =0;i<10000;i++){ // map.put("key"+i,new byte[i]); // } } 使用-Xmx2M限定堆内存,使用WeakHashMap的代码正常运行结束,而使用HashMap的代码段抛出异常 java.lang.OutOfMemoryError: Java heap space 由此可见,WeakHashMap会在系统内存紧张时使用弱引用,自动释放掉持有弱引用的内存数据。 但如果WeakHashMap的key都在系统内持有强引用,那么WeakHashMap就退化为普通的HashMap,因为所有的表项都无法被自动清理。
true
b2a6d4382102e8513bbb1ff0d6cad89b81725924
Java
jfcaraujo/LPOO
/projecto-lpoo-2019-lpoo_35-master/src/main/java/ViewLanterna/ShopStateViewLanterna.java
UTF-8
407
2.328125
2
[]
no_license
package ViewLanterna; import com.googlecode.lanterna.graphics.TextGraphics; public class ShopStateViewLanterna extends HeroStateViewLanterna { @Override public void draw(TextGraphics graphics, int width) { drawSentence(graphics, width, 19, "Food Shop(f)"); drawSentence(graphics, width, 20, "Weapon Shop(w)"); drawSentence(graphics, width, 21, "Armor Shop(a)"); } }
true
a9ac3b829fbb03e29a1238a311dca59e07b67800
Java
hiranneri/docevida-tcc
/src/main/java/br/com/doceVida/controller/pedido/SelecaoProdutoBean.java
UTF-8
1,705
1.875
2
[]
no_license
package br.com.doceVida.controller.pedido; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import org.primefaces.context.RequestContext; import br.com.doceVida.dao.ProdutoDAO; import br.com.doceVida.model.Produto; @ManagedBean(name="SelecaoProdutoBean") @ViewScoped public class SelecaoProdutoBean implements Serializable { private String valor; private static final long serialVersionUID = 1L; private List<Produto>produtosPesquisados; public ProdutoDAO service; private int numeroRegistrosLocalizados; public SelecaoProdutoBean() { // TODO Auto-generated constructor stub this.numeroRegistrosLocalizados=0; } public List<Produto> getProdutosPesquisados() { return produtosPesquisados; } public void setListaProdutosPesquisados(List<Produto> produtos) { this.produtosPesquisados = produtos; } public String getValor() { return valor; } public void setValor(String valor) { this.valor = valor; } public int getNumeroRegistrosLocalizados() { return this.numeroRegistrosLocalizados; } public void setNumeroRegistrosLocalizados(int numeroRegistrosLocalizados) { this.numeroRegistrosLocalizados = numeroRegistrosLocalizados; } public void pesquisarProduto(){ produtosPesquisados = new ArrayList<>(); this.service = new ProdutoDAO(); setListaProdutosPesquisados(service.findByName(this.valor)); this.setNumeroRegistrosLocalizados(this.getProdutosPesquisados().size()); } public String selecionar(Produto produto){ RequestContext.getCurrentInstance().closeDialog(produto); return "efetuar-pedido.xhtml?faces-redirect=true"; } }
true
acbd746a9633753f041d2472aa98319d899cf4e8
Java
tulis/multibattleship
/BattleShip/src/model/server/PlayerHandlingThread.java
UTF-8
9,004
2.875
3
[]
no_license
package model.server; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.Socket; import java.util.logging.Level; import java.util.logging.Logger; import model.util.BattleShipConstants; import model.util.Board; import model.util.EGameMenu; import model.util.NavalForce; import model.util.Ship; import model.util.ShipException; public class PlayerHandlingThread extends Thread { //private fields private Server server; private Socket socket; private String username; private Board boards[] = new Board[2]; private int nPlayer; private DataInputStream dataInputStream; private DataOutputStream dataOutputStream; //private static fields private static Integer myTurn = 0; private static Boolean isGameOver = false; private static String winner = ""; private static int NAVAL_FORCE_PLAYERS = 0; private static int hit; private static int loc; //constructor public PlayerHandlingThread(Server server, Socket socket, int nPlayer) { this.socket = socket; this.nPlayer = nPlayer; this.boards = server.getBoards(); this.username = server.getPlayerName()[nPlayer]; this.server = server; try { dataInputStream = new DataInputStream(socket.getInputStream()); dataOutputStream = new DataOutputStream(socket.getOutputStream()); } catch (IOException ex) { try { sleep(100); } catch (InterruptedException ex1) { Logger.getLogger(PlayerHandlingThread.class.getName()).log(Level.SEVERE, null, ex1); } } } public OutputStream getSocketOutputStream() throws IOException { return this.socket.getOutputStream(); } //Methods @Override public void run() { this.initBoard(); //game starting while (!isGameOver) { try { dataOutputStream.writeInt(myTurn); if (myTurn == nPlayer) { System.out.println("It's " + username + "'s turn"); loc = dataInputStream.readInt(); System.out.println(username + " is bombing at location " + loc); hit = bombing(loc); isWin(); if (myTurn == BattleShipConstants.GAMEOVER) { break; } myTurn = (nPlayer + 1) % 2; } else { while (true) { if (myTurn != nPlayer) { if (myTurn != BattleShipConstants.GAMEOVER) { try { this.sleep(100); } catch (InterruptedException ex) { } } else { break; } } else { break; } } } dataOutputStream.writeInt(loc); dataOutputStream.writeInt(hit); } catch (IOException ex) { } } try { dataOutputStream.writeInt(myTurn); dataOutputStream.writeUTF(server.getPlayerName()[(nPlayer + 1) % 2]); dataOutputStream.flush(); } catch (IOException ex) { try { sleep(100); } catch (InterruptedException ex1) { } } } public void initBoard() { for (int i = 0; i < 2; i++) { this.server.navalForces[i] = new NavalForce(); } while (this.server.navalForces[nPlayer].size() < 4) { //loops until all ships are inside navalForce try { System.out.println(String.format("%s is placing ship%d", this.username, server.navalForces[nPlayer].size() + 1)); int size = this.dataInputStream.readInt(); int orientation = this.dataInputStream.readInt(); int topLeftPosition = this.dataInputStream.readInt(); Ship ship = new Ship(size, orientation, topLeftPosition); this.server.navalForces[nPlayer].add(ship); System.out.println(String.format("%s's ship%d added into NavalForce", this.username, server.navalForces[nPlayer].size())); this.NavalForceToBoard(ship); } catch (IOException ioEx) { try { sleep(100); } catch (InterruptedException ex1) { } } catch (ShipException sx) { System.out.println("You try to put the ship in non-empty location"); } catch (Exception ex) { //ex.printStackTrace(); } } System.out.println(String.format("%s has add all ships into NavalForce.", this.username)); this.printNavalForce(); NAVAL_FORCE_PLAYERS++; if (NAVAL_FORCE_PLAYERS == 1) { System.out.println(String.format("%s is waiting for the enemy...", this.username)); } while (NAVAL_FORCE_PLAYERS < 2) { try { this.sleep(100); //Waiting for other player finishing setting-up the board } catch (InterruptedException ex) { Logger.getLogger(PlayerHandlingThread.class.getName()).log(Level.SEVERE, null, ex); } } try { dataOutputStream.writeUTF(EGameMenu.Playing.name()); } catch (IOException ex) { try { sleep(100); } catch (InterruptedException ex1) { } } } private void NavalForceToBoard(Ship ship) { char type = 0; switch (ship.size()) { case 1: type = 's'; break; case 2: type = 'd'; break; case 3: type = 'c'; break; case 4: type = 'b'; break; } for (Object location : ship.getAllLocs()) { this.boards[nPlayer].setBoard(type, (Integer) location); } } private void printNavalForce() { System.out.println("====================="); for (int i = 0; i < server.navalForces[nPlayer].size(); i++) { Ship ship = (Ship) server.navalForces[nPlayer].get(i); System.out.println(ship.toString()); } System.out.println(String.format("======%s's NavalForce======", username)); System.out.println(server.getPlayerName()[nPlayer] + "'s board"); boards[nPlayer].printBoard(); } private int bombing(int location) { char bomb = ' '; int enemy = (myTurn + 1) % 2; System.out.println("enemy navalForce remaining: " + server.navalForces[enemy].getTotalRemainingLocs()); System.out.println(server.getPlayerName()[enemy] + "'s board"); Ship ship = this.server.navalForces[enemy].getShipHit(location); if (ship != null) { Ship shipDestroyed = this.server.navalForces[enemy].getShipDestroyed(location); if (shipDestroyed != null) { switch (shipDestroyed.size()) { case 1: bomb = 'S'; break; case 2: bomb = 'D'; break; case 3: bomb = 'C'; break; case 4: bomb = 'B'; break; } System.out.println("The destroyed ship is " + BattleShipConstants.shipTypes[shipDestroyed.size() - 1]); for (Object loc : shipDestroyed.getAllLocs()) { boards[enemy].setBoard(bomb, (Integer) loc); } shipDestroyed.destroy(location); boards[enemy].printBoard(); return server.navalForces[enemy].shipToInteger(ship); } else { boards[enemy].setBoard('X', (Integer) location); boards[enemy].printBoard(); ship.destroy(location); return BattleShipConstants.SHIP_HIT; } } else { boards[enemy].setBoard('/', (Integer) location); boards[enemy].printBoard(); return BattleShipConstants.SHIP_MISS; } } private void isWin() { winner = server.getPlayerName()[myTurn]; if (this.server.navalForces[(nPlayer + 1) % 2].getTotalRemainingLocs() == 0) { myTurn = BattleShipConstants.GAMEOVER; System.out.println(winner + " Win! "); this.isGameOver = true; } } }
true
5e7d6d55998568c61e8b9e6d27dc45838eb394ca
Java
sergiiGitHub/Demo
/Android/TouchCatch/app/src/main/java/com/example/sergii/touchcatch/service/ValueHolderController.java
UTF-8
4,025
2.53125
3
[]
no_license
package com.example.sergii.touchcatch.service; import android.util.Log; import android.view.WindowManager; import com.example.sergii.touchcatch.appliers.BasicApplier; import com.example.sergii.touchcatch.appliers.PositionX; import com.example.sergii.touchcatch.appliers.PositionY; import com.example.sergii.touchcatch.appliers.SizeX; import com.example.sergii.touchcatch.appliers.SizeY; import com.example.sergii.touchcatch.filemanager.FileLineReader; import java.io.File; import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by sergii on 09.10.16. */ public class ValueHolderController { private static final String TAG = ValueHolderController.class.getSimpleName(); private FileLineReader.OnLineReadListener mOnLineReadListener; private static ValueHolderController mInstance; private HashMap< String, BasicApplier> mValueHolder; private Pattern mPattern = Pattern.compile("(\\w*)=\"(\\d*)\""); public static ValueHolderController getInstance(){ if ( mInstance == null ){ mInstance = new ValueHolderController(); } return mInstance; } private ValueHolderController( ){ initValueHolder(); initLineReadListener(); } private void initValueHolder() { mValueHolder = new HashMap<>(); addValue(new PositionX(100)); addValue(new PositionY(100)); addValue(new SizeX(250)); addValue(new SizeY(100)); } public void addValue(BasicApplier applier) { mValueHolder.put(applier.getName(), applier); } private void initLineReadListener() { mOnLineReadListener = new FileLineReader.OnLineReadListener() { private boolean mResult; @Override public void read(String aString) { mResult = true; Log.d(TAG, "read: " + aString); Matcher m = mPattern.matcher(aString); if (m.find()) { Log.d(TAG, "read: m.group : " + m.group(1) + " " + m.group(2)); mResult |= setValue(m.group(1), Integer.parseInt(m.group(2))); } else { Log.e(TAG, "read: could parse: " + aString ); } } @Override public int getMaxLine() { return mValueHolder.size(); } @Override public boolean getResult() { return mResult; } }; } public boolean setValue(String key, int value) { BasicApplier applier = mValueHolder.get(key); if ( applier != null && applier.getValue() != value ){ applier.setValue(value); return true; } return false; } public boolean scanConfig(File file) { Log.d(TAG, "scanConfig: " + file); new FileLineReader().read(file, mOnLineReadListener); return mOnLineReadListener.getResult(); } public void apply(WindowManager.LayoutParams layoutParams) { for( String key : mValueHolder.keySet()){ BasicApplier applier = mValueHolder.get(key); if ( applier != null ) { applier.apply(layoutParams); } } } public String generateConfig() { StringBuilder stringBuilder = new StringBuilder(); for( String key : mValueHolder.keySet()){ BasicApplier applier = mValueHolder.get(key); if ( applier != null ) { stringBuilder.append(getWriteString(applier)); } } return stringBuilder.toString(); } public String getWriteString(BasicApplier applier){ StringBuilder builder = new StringBuilder(); builder.append(applier.getName()) .append("=") .append("\"") .append(applier.getValue()) .append("\"") .append("\n"); return builder.toString(); } }
true
66eb26b764c7b52e1887b4dce59d3df9d5ef81d8
Java
yehudapashay/EmergencySystem
/src/main/java/View/TableUpdate.java
UTF-8
919
2.484375
2
[]
no_license
package View; import Model.EventUpdate; public class TableUpdate { private String _Date; private String _Content; private String _Event; private String _User; public TableUpdate(EventUpdate eventUpdate) { _Date = eventUpdate.get_Date(); _Content = eventUpdate.get_Content(); _Event = eventUpdate.get_Event().get_Title(); _User = eventUpdate.get_User().get_name(); } public String get_Date() { return _Date; } public void set_Date(String _Date) { this._Date = _Date; } public String get_Content() { return _Content; } public void set_Content(String _Content) { this._Content = _Content; } public String get_Event() { return _Event; } public void set_Event(String _Event) { this._Event = _Event; } public String get_User() { return _User; } }
true
901609f871fe106b99afcca89f732657cd67cd0d
Java
gaurav-nitks/code_reto
/MiniQ/src/main/java/com/company/miniq/broker/DefaultMiniQ.java
UTF-8
2,796
2.375
2
[]
no_license
package com.company.miniq.broker; import com.company.miniq.broker.IdGenerator.DefaultIdGenerator; import com.company.miniq.broker.IdGenerator.IdGenerator; import com.company.miniq.broker.config.Configuration; import com.company.miniq.broker.storage.MessagesStorage; import com.company.miniq.broker.storage.Store; import com.company.miniq.broker.storage.TransitMessagesStore; import com.company.miniq.broker.storage.TransitStorage; import com.company.miniq.message.Envelope; import com.company.miniq.message.InTransitEnvelop; import com.company.miniq.message.Message; import com.company.miniq.message.MessageId; import com.company.miniq.scheduler.Scheduler; import java.util.List; public class DefaultMiniQ implements MiniQ { private final Configuration config; private IdGenerator idGenerator; private final Store<Envelope> messageStorage; private final TransitStorage inTransitMessageStore; private final Scheduler scheduler; public DefaultMiniQ(Configuration config, IdGenerator idGenerator, Store<Envelope> messageStorage, TransitStorage inTransitMessageStore) { this.config = config; this.idGenerator = idGenerator; this.messageStorage = messageStorage; this.inTransitMessageStore = inTransitMessageStore; this.scheduler = new Scheduler(messageStorage, inTransitMessageStore); scheduler.start(); } public DefaultMiniQ(Configuration config) { this( config, new DefaultIdGenerator(), new MessagesStorage<Envelope>(), new TransitMessagesStore()); } @Override public MessageId publish(Message message) { MessageId id = idGenerator.generateNextId(); messageStorage.add(new Envelope(id, message)); return id; } @Override public List<Envelope> consume() { List<Envelope> messages = messageStorage.getAll(); addToInTransit(messages); return messages; } @Override public List<Envelope> consume(int count) { List<Envelope> messages = null; if(count > 0) { messages = messageStorage.get(count); addToInTransit(messages); } return messages; } @Override public void acknowledge(MessageId messageId) { inTransitMessageStore.remove(messageId); } @Override public void close() { scheduler.stop(); } private void addToInTransit(List<Envelope> messages){ long expiryTime = System.currentTimeMillis() + (config.getAcknowledgeWaitTimeOut() * 1000) ; for(Envelope message: messages) { inTransitMessageStore.add(new InTransitEnvelop(expiryTime, message)); } } }
true
684b0bd16393b6411a8aa0701e6e579d2a6fa0a6
Java
thoslin/ELF
/server/oms/elf.api.position/src/main/java/elf/api/position/query/reconciliation/PositionQuery.java
UTF-8
501
1.523438
2
[ "BSD-3-Clause" ]
permissive
package elf.api.position.query.reconciliation; import java.util.List; public interface PositionQuery { public List<PositionQueryResult> queryPositionQuantity(PositionQueryParameter parameter); public List<PositionQueryResult> queryNontradableQuantity(PositionQueryParameter parameter); public List<PositionQueryResult> queryPledgeAndStandarQuantity(PositionQueryParameter parameter); public List<PositionQueryResult> queryExpiresPosition(PositionQueryParameter parameter); }
true
e5f9a593332d1b3831c61081b8b65eded70cc98d
Java
tengyangdada/AndroidTest
/ContentProvider/app/src/main/java/com/example/contentprovider/MainActivity.java
UTF-8
1,350
2.3125
2
[]
no_license
package com.example.contentprovider; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity implements View.OnClickListener{ private Button music,photo,video; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); photo=(Button)findViewById(R.id.photo); music=(Button)findViewById(R.id.music); video=(Button)findViewById(R.id.video); photo.setOnClickListener(this); video.setOnClickListener(this); music.setOnClickListener(this); } @Override public void onClick(View v){ switch (v.getId()){ case R.id.music: Intent intent=new Intent(this,MusicActivity.class); startActivity(intent); break; case R.id.video: Intent intent1=new Intent(this,VideoActivity.class); startActivity(intent1); break; case R.id.photo: Intent intent2=new Intent(this,PhotoActivity.class); startActivity(intent2 ); break; } } }
true
fd68020fa273d3ae01135258d011f21caab4fa4e
Java
mkasapov/MentorMateDesignPatternsTasks
/src/facade/AppWithFacade.java
UTF-8
698
3.3125
3
[]
no_license
package facade; public class AppWithFacade { public static void main(String[] args) { Cooker cooker = new Cooker(true, 700); MoneyForPizzaMaking moneyForPizzaMaking = new MoneyForPizzaMaking(20, 50); Pizza pizza = new Pizza(PizzaType.MARGARITA, 10, 350, cooker); PizzaFacade pizzaFacade = new PizzaFacade(cooker, moneyForPizzaMaking, pizza); if (pizzaFacade.checkCooker() && pizzaFacade.checkMoney()) { System.out.println(pizzaFacade.getResult().toString()); System.out.println(pizza.getPizzaType() + " will be delivered shortly"); } else { System.out.println("NO delivery will be made"); } } }
true
c46bb2c7496db0a1e860fb8bafb5ce72e6932332
Java
zoogzog/acarast
/src/com/acarast/andrey/core/algorithm/DetectorChannelBorder.java
UTF-8
20,347
2.84375
3
[]
no_license
package com.acarast.andrey.core.algorithm; import java.awt.Point; import java.util.Arrays; import java.util.Vector; import org.opencv.core.Mat; import org.opencv.core.Scalar; import org.opencv.imgproc.Imgproc; import com.acarast.andrey.controller.SettingsController; import com.acarast.andrey.debug.DebugLogger; import com.acarast.andrey.debug.DebugLogger.LOG_MESSAGE_TYPE; import com.acarast.andrey.imgproc.ImageProcessingUtils; /** * Class for detecting locations of the channels in the input microscopy image. * @author Andrey G */ public class DetectorChannelBorder { //---------------------------------------------------------------- /** Finds intersection point between two lines. * @param Line1 * @param Line2 * @return */ static Point getIntersection(org.opencv.core.Point[] Line1, org.opencv.core.Point[] Line2) { org.opencv.core.Point x = new org.opencv.core.Point(Line2[0].x - Line1[0].x, Line2[0].y - Line1[0].y); org.opencv.core.Point d1 = new org.opencv.core.Point(Line1[1].x - Line1[0].x, Line1[1].y - Line1[0].y); org.opencv.core.Point d2 = new org.opencv.core.Point(Line2[1].x - Line2[0].x, Line2[1].y - Line2[0].y); double CrossProduct = d1.x * d2.y - d1.y * d2.x; if (Math.abs(CrossProduct) < /*EPS*/1e-8) { return null; } double t1 = (x.x * d2.y - x.y * d2.x) / CrossProduct; double OutputX = Line1[0].x + d1.x * t1; double OutputY = Line1[0].y + d1.y * t1; return new Point((int)Math.round(OutputX), (int)Math.round(OutputY)); } //---------------------------------------------------------------- /** Returns coordinates of the intersection between the segment, specified by 2 points with two line y = 0 and y = height * The output point contains point.x = [x coordinate of intersection with y = 0] = f(0), point.y = f(height) */ private static Point getIntersection (org.opencv.core.Point Vertex1, org.opencv.core.Point Vertex2, int MaxWidth, int MaxHeight) { //---- P.x = f(0), P.y = f(height) Point OutputPoint = new Point(0, 0); if (Vertex1.y == Vertex2.y) { return new Point(-1, -1); } //---- Y = 0 line segment org.opencv.core.Point SouthLine1 = new org.opencv.core.Point(0, 0); org.opencv.core.Point SouthLine2 = new org.opencv.core.Point(MaxWidth, 0); Point SouthPoint = getIntersection(new org.opencv.core.Point[] {Vertex1, Vertex2}, new org.opencv.core.Point[] {SouthLine1, SouthLine2}); org.opencv.core.Point NorthLine1 = new org.opencv.core.Point(0, MaxHeight); org.opencv.core.Point NorthLine2 = new org.opencv.core.Point(MaxWidth, MaxHeight); Point NorthPoint = getIntersection(new org.opencv.core.Point[] {Vertex1, Vertex2}, new org.opencv.core.Point[] {NorthLine1, NorthLine2}); if (SouthPoint != null) { OutputPoint.x = SouthPoint.x; } if (NorthPoint != null) { OutputPoint.y = NorthPoint.x; } if (OutputPoint.x < 0 || OutputPoint.y < 0 || OutputPoint.x > MaxWidth || OutputPoint.y > MaxWidth) { //---- This type of point indicates that the calculated intersection is out of range return new Point(-1, -1); } else { return OutputPoint; } } //---------------------------------------------------------------- /** * Detects all points for border candidates * @param inputImage * @return */ private static Point[] detectBorderLineCandidates (Mat inputImage) { double HoughTransformRho = SettingsController.CURRENT_SAMPLE_DETECTOR_HOUGH_TRANSFORM_RHO; double HoughTransformThetta = SettingsController.CURRENT_SAMPLE_DETECTOR_HOUGH_TRANSFORM_THETTA; int HoughTransformThreshold = SettingsController.CURRENT_SAMPLE_DETECTOR_HOUGH_TRANSFORM_THRESHOLD; double HoughTransformMinLineLength = SettingsController.CURRENT_SAMPLE_DETECTOR_HOUGH_TRANSFORM_MIN_LINE_LENGTH; double HoughTransformMaxLineGap = SettingsController.CURRENT_SAMPLE_DETECTOR_HOUGH_TRANSFORM_MAX_LINE_GAP; //---- Max angle tg for deleting all lines that have bigger inclination angle int DEFAILT_MAX_ANGLE = 90 - 5; int DEFAULT_MAX_ANGLE_DELTA = (int) Math.round(inputImage.rows() / Math.tan(Math.PI * DEFAILT_MAX_ANGLE / 180)); //---- Line segments container Mat LineCandidates = new Mat(); //---- Perform hough transform Imgproc.HoughLinesP(inputImage, LineCandidates, HoughTransformRho, HoughTransformThetta, HoughTransformThreshold, HoughTransformMinLineLength, HoughTransformMaxLineGap); Vector <Point> borderCandidatePoints = new Vector <Point>(); for (int i = 0; i < LineCandidates.rows(); i++) { //---- Get points of the line segments org.opencv.core.Point pt1 = new org.opencv.core.Point(LineCandidates.get(i, 0)[0], LineCandidates.get(i, 0)[1]); org.opencv.core.Point pt2 = new org.opencv.core.Point(LineCandidates.get(i, 0)[2], LineCandidates.get(i, 0)[3]); //---- We have to find intersection between the line candidate and y = 0, y = height Point AddPoint = getIntersection(pt1, pt2, inputImage.width(), inputImage.height()); //---- Check if the calculated point is in range if (AddPoint.x != -1 && AddPoint.y != -1) { int currentTanDelta = Math.abs(AddPoint.x - AddPoint.y); if (currentTanDelta < DEFAULT_MAX_ANGLE_DELTA) { borderCandidatePoints.addElement(AddPoint); } } } Point[] outputBorderCandidatePoint = new Point[borderCandidatePoints.size()]; for (int indexPoint = 0; indexPoint < borderCandidatePoints.size(); indexPoint++) { outputBorderCandidatePoint[indexPoint] = borderCandidatePoints.get(indexPoint); } return outputBorderCandidatePoint; } //---------------------------------------------------------------- /** Checks the left side and the right side of the border. Border should have dark region on the left or right side or both. */ private static Point[] selectBorderCandidatesIntensity (Mat inputImage, Point[] borderCandidatePoints, int thresholdDark, int thresholdBright) { int DEFAULT_PATCH_SIZE = SettingsController.CURRENT_SAMPLE_DETECTOR_BORDERCORRECTION_PATCH_SIZE; Vector <Point> outputBorderCandidates = new Vector <Point>(); Mat averageIntensity = ImageProcessingUtils.filterAveragePatch(inputImage, DEFAULT_PATCH_SIZE); int patchAmountRows = averageIntensity.rows(); int patchAmountCols = averageIntensity.cols(); for (int indexLine = 0; indexLine < borderCandidatePoints.length; indexLine++) { int patchIndexStart = borderCandidatePoints[indexLine].x / DEFAULT_PATCH_SIZE; int patchIndexEnd = borderCandidatePoints[indexLine].y / DEFAULT_PATCH_SIZE; double patchOffsetPerStep = (double) (patchIndexEnd - patchIndexStart ) / (patchAmountRows - 1); double sumIntensityCenter = 0; double sumIntensityLeft = 0; double sumIntensityRight = 0; int MaxIntensity = 0; int MinIntensity = 255; for (int patchRowIndex = 0; patchRowIndex < patchAmountRows; patchRowIndex++) { int patchColIndex = (int) Math.round((double)patchIndexStart + patchRowIndex * patchOffsetPerStep); if (patchColIndex >= 0 && patchColIndex < patchAmountCols) { sumIntensityCenter += averageIntensity.get(patchRowIndex, patchColIndex)[0]; MaxIntensity = Math.max(MaxIntensity, (int)averageIntensity.get(patchRowIndex, patchColIndex)[0]); MinIntensity = Math.min(MinIntensity, (int)averageIntensity.get(patchRowIndex, patchColIndex)[0]); } if (patchColIndex - 1 >= 0) { sumIntensityLeft += averageIntensity.get(patchRowIndex, patchColIndex - 1)[0]; } if (patchColIndex - 2 >= 0) { sumIntensityLeft += averageIntensity.get(patchRowIndex, patchColIndex - 2)[0]; } if (patchColIndex + 1 < patchAmountCols) { sumIntensityRight += averageIntensity.get(patchRowIndex, patchColIndex + 1)[0]; } if (patchColIndex + 2 < patchAmountCols) { sumIntensityRight += averageIntensity.get(patchRowIndex, patchColIndex + 2)[0]; } } sumIntensityCenter /= patchAmountRows; sumIntensityLeft /= patchAmountRows; sumIntensityRight /= patchAmountRows; if (sumIntensityLeft < thresholdDark || sumIntensityRight < thresholdDark) { if (sumIntensityCenter > thresholdBright) { outputBorderCandidates.add(borderCandidatePoints[indexLine]); } } } Point[] outputArray = new Point[outputBorderCandidates.size()]; for (int i = 0; i < outputArray.length; i++) { outputArray[i] = new Point(outputBorderCandidates.get(i).x, outputBorderCandidates.get(i).y); } if (outputArray.length == 0) { return borderCandidatePoints; } else { return outputArray; } } //---------------------------------------------------------------- /** Rotates all borders candidates to be parallel to each other. */ private static Point[] rotateBorders (Point[] borderCandidatePoints) { double averageDelta = 0; for (int i = 0; i < borderCandidatePoints.length; i++) { averageDelta += (borderCandidatePoints[i].x - borderCandidatePoints[i].y); } averageDelta /= borderCandidatePoints.length; Point[] outputArray = new Point[borderCandidatePoints.length]; for (int i = 0; i < borderCandidatePoints.length; i++) { int variation = (borderCandidatePoints[i].x - borderCandidatePoints[i].y) - (int) Math.round(averageDelta); int newX = borderCandidatePoints[i].x - variation / 2; int newY = borderCandidatePoints[i].y + variation / 2; outputArray[i] = new Point(newX, newY); } return outputArray; } //---------------------------------------------------------------- /** Merge all border candidates which are close to each other. Returns minX, maxX and angle for each border*/ private static int[][] mergeBorderCandidates (Mat inputImage, Point[] borderCandidatePoints, int thresholdMerge) { Point[] borderCandidatesRotated = rotateBorders(borderCandidatePoints); int currentAngle = borderCandidatesRotated[0].x - borderCandidatesRotated[0].y; //---- Prepare to sort int[] borderXCoordinate = new int[borderCandidatesRotated.length]; for (int i = 0; i < borderXCoordinate.length; i++) { borderXCoordinate[i] = borderCandidatesRotated[i].x; } //---- Temporary storage for found minX border coordinate and maxX Vector <Integer> borderMin = new Vector <Integer>(); Vector <Integer> borderMax = new Vector <Integer>(); //---- Sort the x = (0,f(0)) coordinates of the border line candidates Arrays.sort(borderXCoordinate); for (int i = 0; i < borderXCoordinate.length; i++) { int newBorderMin = borderXCoordinate[i]; int newBorderMax = borderXCoordinate[i]; int newLastBorder = borderXCoordinate[i]; //---- Check next i = i+1; //---- Stop loop flag boolean isContinue = true; do { if (i < borderXCoordinate.length) { if (borderXCoordinate[i] - newLastBorder < thresholdMerge) { newBorderMax = borderXCoordinate[i]; newLastBorder = borderXCoordinate[i]; i++; } else { isContinue = false; //---- Move index back, the for loop will put index back i--; } } else { isContinue = false; } } while (isContinue); borderMin.addElement(newBorderMin); borderMax.addElement(newBorderMax); } int[][] outputArray = new int[borderMin.size()][3]; for (int i = 0; i < outputArray.length; i++) { outputArray[i][0] = borderMin.get(i); outputArray[i][1] = borderMax.get(i); outputArray[i][2] = currentAngle; } return outputArray; } //---------------------------------------------------------------- /** Check if the size of all samples is quite the same. Sample size is the distance between two borders 2k and 2k+1. * Parameter of threshold shows what could be the maximum difference between sample sizes. Input array has to be */ private static boolean isSameSize (Point[] inputBorderCoodinates, int thresholdMax) { if (inputBorderCoodinates.length % 2 != 0) { return false; } int maxSampleSize = 0; int minSampleSize = Integer.MAX_VALUE; for (int i = 0; i < inputBorderCoodinates.length / 2; i++) { int currentSampleSize = inputBorderCoodinates[2 * i + 1].x - inputBorderCoodinates[2 * i].x; maxSampleSize = Math.max(currentSampleSize, maxSampleSize); minSampleSize = Math.min(currentSampleSize, minSampleSize); } if (maxSampleSize - minSampleSize< thresholdMax) { return true; } else { return false; } } //---------------------------------------------------------------- /** Delete redundant borders. Here we are assume that additional borders could be found only inside some samples. */ private static Point[] estimateBordersDelete (int[][] inputBorderCandidates, Mat inputIntensityImage, int samplesAmount) { //---- WHATS THAT? int DEFAULT_STRIP_OFFSET = 10; //---- Container for storing intensity level for each strip Vector <Double> intensityLevel = new Vector <Double>(); //---- Container for storing indexes of the borders which used to form a strip Vector <Point> stripBorderIndex = new Vector <Point>(); for (int i = 0; i < inputBorderCandidates.length - 1; i++) { stripBorderIndex.addElement(new Point(i, i++)); //---- Calculate intensity for the current strip int stripStart = inputBorderCandidates[i][1] + DEFAULT_STRIP_OFFSET; int stripWidth = inputBorderCandidates[i+1][0] - inputBorderCandidates[i][1]; double stripAngle = inputBorderCandidates[i][2] / inputIntensityImage.rows(); double averageIntensity = ImageProcessingUtils.averageIntensityParallelogram(inputIntensityImage, stripStart, stripWidth, stripAngle); intensityLevel.addElement(averageIntensity); } int[] minIntensityStripIndex = new int[samplesAmount - 1]; //---- Bold algorithm for locating (samplesAmount - 1) strips with min intensity for (int i = 0; i < samplesAmount - 1; i++) { double minIntensity = Double.MAX_VALUE; int minIntensityIndex = 0; for (int j = 0; j < intensityLevel.size(); j++) { if (intensityLevel.get(j) < minIntensity) { minIntensityIndex = j; minIntensity = intensityLevel.get(j); } } minIntensityStripIndex[i] = minIntensityIndex; } //---- Sort in order Arrays.sort(minIntensityStripIndex); //---- Store to the output array Point[] outputBorder = new Point[samplesAmount * 2]; outputBorder[0] = new Point(inputBorderCandidates[0][1], inputBorderCandidates[0][1] - inputBorderCandidates[0][2]); int indexOutput = 1; for (int k = 0; k < minIntensityStripIndex.length; k++) { int currentLeftStripIndex = stripBorderIndex.get(minIntensityStripIndex[k]).x; outputBorder[indexOutput] = new Point(inputBorderCandidates[currentLeftStripIndex][0], inputBorderCandidates[currentLeftStripIndex][0] - inputBorderCandidates[currentLeftStripIndex][2]); indexOutput++; int currentRightStripIndex = stripBorderIndex.get(minIntensityStripIndex[k]).y; outputBorder[indexOutput] = new Point(inputBorderCandidates[currentRightStripIndex][1], inputBorderCandidates[currentRightStripIndex][1] - inputBorderCandidates[currentRightStripIndex][2]); indexOutput++; } int lastIndex = inputBorderCandidates.length - 1; outputBorder[samplesAmount * 2 - 1] = new Point(inputBorderCandidates[lastIndex][0], inputBorderCandidates[lastIndex][0] - inputBorderCandidates[lastIndex][2]); return outputBorder; } //---------------------------------------------------------------- /** This method detects coordinates of the border candidates, returns an array of Points, where each point.x is a x coordinate of the border with y = 0 and * point.y is an x coordinate of the border with y = height */ public static Point[] detectSampleBorders (Mat inputImage, int samplesAmount) { Point[] outputBorders = new Point[samplesAmount * 2]; /*!*/DebugLogger.logMessage("Detecting border candidates", LOG_MESSAGE_TYPE.INFO); //---- Locate lines on an image, which could be sample borders Point[] borderCandidatePoints = detectBorderLineCandidates(inputImage); //--- Perform iterative search of the borders. On each iteration change the threshold for the //--- detection lines with high intensity and dark intensity on the left or right side. Mat ix = Mat.zeros(inputImage.size(), inputImage.type()); for (int i = 0; i < borderCandidatePoints.length; i++) { Imgproc.line(ix, new org.opencv.core.Point(borderCandidatePoints[i].x, 0), new org.opencv.core.Point(borderCandidatePoints[i].y, inputImage.height()), new Scalar(255)); } DebugLogger.debugSaveMat("testix.jpg", ix); int DEFAULT_MAX_SAMPLE_SIZE_DELTA = SettingsController.CURRENT_SAMPLE_DETECTOR_BORDERCORRECTION_MINSAMPLEWIDTH; int DEFAULT_MERGE_THRESHOLD = SettingsController.CURRENT_SAMPLE_DETECTOR_BORDERCORRECTION_BORDERWIDTH; int[][] thresholdDB = {{40, 40}, {50, 30}, {60, 20}, {SettingsController.CURRENT_SAMPLE_DETECTOR_BORDERCORRECTION_BORDERINTENSITY_MAX, SettingsController.CURRENT_SAMPLE_DETECTOR_BORDERCORRECTION_BORDERINTENSITY_MIN}, {120, 5}}; int DEFAULT_MAX_ITERATIONS = thresholdDB.length - 1; boolean isContinueLoop = true; int indexIteration = 0; /*!*/DebugLogger.logMessage("Locating " + samplesAmount + " sample borders among " + borderCandidatePoints.length + " found candidates", LOG_MESSAGE_TYPE.INFO); do { //---- Detect lines which are near the dark areas and are quite bright; Point[] borderCandidatePointsRefined = selectBorderCandidatesIntensity(inputImage, borderCandidatePoints, thresholdDB[indexIteration][0], thresholdDB[indexIteration][1]); int[][] borderCandidatePointsMerged = mergeBorderCandidates(inputImage, borderCandidatePointsRefined,DEFAULT_MERGE_THRESHOLD); //---- Found target amount of borders, check if they have equal gaps between if (borderCandidatePointsMerged.length == samplesAmount * 2) { for (int i = 0; i < borderCandidatePointsMerged.length; i++) { int currentX = 0; int currentY = 0; //---- Take max for the left borders, take min to the right borders if (i % 2 == 0) { currentX = borderCandidatePointsMerged[i][1]; currentY = borderCandidatePointsMerged[i][1] - borderCandidatePointsMerged[i][2]; } else { currentX = borderCandidatePointsMerged[i][0]; currentY = borderCandidatePointsMerged[i][0] - borderCandidatePointsMerged[i][2]; } outputBorders[i] = new Point(currentX, currentY); } //---- Check if the size of all samples is the same, if iteration limit is reached, return, what was found if (isSameSize(outputBorders, DEFAULT_MAX_SAMPLE_SIZE_DELTA) || indexIteration >= DEFAULT_MAX_ITERATIONS) { isContinueLoop = false; } else { isContinueLoop = true; } } //---- Not found target amount of borders else { //---- If not the max limit of iterations reached, try to estimate on the next iteration if (indexIteration != DEFAULT_MAX_ITERATIONS) { isContinueLoop = true; } //---- Last iteration, try to estimate borders from the acquired information else { //---- Amount of detected border candidates is less then the target amount: try to estimate borders if (borderCandidatePointsMerged.length < samplesAmount * 2) { //TODO FIXME (in current version in case this happens user has to chose different processing parameters) //---- Her we force the method to return null to indicate that it was not possible to detect outputBorders = null; isContinueLoop = false; } //---- Amount of detected border candidates is more then the target amount: delete some borders if (borderCandidatePointsMerged.length > samplesAmount * 2) { outputBorders = estimateBordersDelete(borderCandidatePointsMerged, inputImage, samplesAmount); isContinueLoop = false; } } } indexIteration++; } while (isContinueLoop); return outputBorders; } //---------------------------------------------------------------- }
true
95a3830b0fe843ddbfdeb62ced88d78ba9a47b04
Java
housong12590/JmmClient
/app/src/main/java/com/jmm/client/image/activity/ImagePreviewActivity.java
UTF-8
2,717
2.09375
2
[]
no_license
package com.jmm.client.image.activity; import android.content.Context; import android.content.Intent; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.jmm.client.R; import com.jmm.client.image.load.ImageLoaderUtils; import com.jmm.client.module.base.activity.BaseActivity; import com.jmm.common.utils.DensityUtils; import java.util.ArrayList; import butterknife.BindView; import butterknife.OnClick; public class ImagePreviewActivity extends BaseActivity { private static final String IMAGE_LIST = "imageList"; private static final String CURR_POSITION = "currentPosition"; private ArrayList<String> imageList; private int currentPosition; @BindView(R.id.viewPager) ViewPager viewPager; @Override public void parseIntent(Intent intent) { imageList = intent.getStringArrayListExtra(IMAGE_LIST); currentPosition = intent.getIntExtra(CURR_POSITION, 0); } public static void start(Context context, ArrayList<String> list, int currentPosition) { Intent intent = new Intent(context, ImagePreviewActivity.class); intent.putExtra(IMAGE_LIST, list); intent.putExtra(CURR_POSITION, currentPosition); context.startActivity(intent); } @Override public int getLayoutId() { return R.layout.activity_image_preview; } @Override public void initView() { viewPager.setPageMargin(DensityUtils.dp2px(mContext, 5)); viewPager.setAdapter(new ImagePreviewAdapter()); viewPager.setCurrentItem(currentPosition); } @Override public void initData() { } @OnClick(R.id.iv_back) public void onClick(View view) { finish(); } private class ImagePreviewAdapter extends PagerAdapter { @Override public int getCount() { return imageList.size(); } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public Object instantiateItem(ViewGroup container, int position) { View view = View.inflate(mContext, R.layout.item_image_preview, null); ImageView ivImage = (ImageView) view.findViewById(R.id.iv_image); ImageLoaderUtils.getInstance().loadImage(mContext, imageList.get(position), ivImage, false); container.addView(view); return view; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); } } }
true
be185487a0ef9a80906d42568421ead77d622705
Java
zhangkanghao/processManager
/src/cn/zkh/Process2.java
UTF-8
1,262
2.71875
3
[]
no_license
package cn.zkh; import cn.zkh.scheduler.CPU; import cn.zkh.scheduler.Process; import static cn.zkh.Main.semaphores; /** * Created by likole on 11/26/18. */ public class Process2 extends Process { @Override public void run(){ while (CPU.i<6){ switch (CPU.address){ case 0: System.out.println("process3 calls P on semaphore2\n"); CPU.address=1; if(P(semaphores[1]))return; case 1: System.out.println("process3 is executing on the cretical section \n"); CPU.address=2; if(stopped()) return; case 2: Main.res2++; System.out.println("s1="+Main.res2+"\n"); System.out.println("process3 calls V on semaphore2 and quit cretical section.\n"); CPU.address=3; V(semaphores[1]); if(stopped()) return; case 3: System.out.println("process3 cycle epoch="+CPU.i+"\n"); CPU.address=0; if(stopped())return; } CPU.i++; } finish(); } }
true
dc69b94f4ab69e069e76bf669479ea3495d9e0a1
Java
pragams/IpTweet
/src/ip/tweet/component/FileTransferProgressBar.java
UTF-8
5,588
2.0625
2
[ "BSD-3-Clause" ]
permissive
/* * Copyright (c) 2016, Vitthal Kavitake * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of IpTweet nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package ip.tweet.component; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics2D; import java.text.DecimalFormat; import javax.swing.JComponent; import javax.swing.JProgressBar; import javax.swing.LookAndFeel; import javax.swing.Painter; import javax.swing.UIDefaults; import javax.swing.UIManager; import ip.tweet.data.FileTransferStatus; /** * @author Vitthal Kavitake */ public class FileTransferProgressBar extends JProgressBar{ /** * */ private static final long serialVersionUID = 1L; private long readLength; private FileTransferStatus status = FileTransferStatus.IN_PROGRESS; //private String fileName; private String fileSize; private long max; private String transferType; public void setTransferType(String transferType){ this.transferType = transferType; } public long getMax(){ return max; } public static FileTransferProgressBar newInstance(long max,String fileName){ LookAndFeel pf = UIManager.getLookAndFeel(); try{UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");}catch(Exception e){} FileTransferProgressBar bar = new FileTransferProgressBar(max, fileName); try{UIManager.setLookAndFeel(pf);}catch(Exception e){} return bar; } private FileTransferProgressBar(long max,String fileName){ this.max = max; // this.fileName = fileName; this.fileSize = getFormattedString(max); setValue(0); if(max>2099999999) setMaximum((int)(max/4)); else setMaximum((int)(max)); setStringPainted(true); setString("0 bytes/"+fileSize); setPreferredSize(new Dimension(250,20)); UIDefaults defaults = new UIDefaults(); defaults.put("ProgressBar[Enabled].foregroundPainter", new MyPainter(new Color(125,125,255))); defaults.put("ProgressBar[Enabled+Finished].foregroundPainter", new MyPainter(new Color(150,255,150))); defaults.put("ProgressBar[Disabled].foregroundPainter", new MyPainter(Color.RED)); defaults.put("ProgressBar[Disabled].textForeground", Color.WHITE); putClientProperty("Nimbus.Overrides.InheritDefaults", Boolean.TRUE); putClientProperty("Nimbus.Overrides", defaults); } /*public void setFileName(String fileName){ this.fileName = fileName; }*/ private String getFormattedString(float value){ float kbLimit = 1024f; float mbLimit = 1024f*1024f; float gbLimit = 1024f*1024f*1024f; DecimalFormat df = new DecimalFormat(); df.setMaximumFractionDigits(2); df.setMinimumFractionDigits(2); if(value<kbLimit){ return value + " bytes"; } else if(value<mbLimit){ return df.format((value/kbLimit))+" Kb"; } else if(value<gbLimit){ return df.format((value/mbLimit))+" MB"; } else{ return df.format((value/gbLimit))+" GB"; } } public void setReadLength(long readLength){ if(max>2099999999){ setValue((int)(readLength/4)); } else{ setValue((int)readLength); } this.readLength = readLength; doValidation(); } public void setStatus(FileTransferStatus status){ this.status = status; doValidation(); } public FileTransferStatus getStatus(){ return this.status; } private void doValidation(){ if(status.equals(FileTransferStatus.ABORTED)){ setString("Failed"); setEnabled(false); //setIndeterminate(true); } else if(status.equals(FileTransferStatus.COMPLETE)){ setString("Completed: "+getFormattedString(readLength)+"/"+fileSize); } else{ setString(transferType +": "+getFormattedString(readLength)+"/"+fileSize); } } class MyPainter implements Painter<JComponent> { private final Color color; public MyPainter(Color c) { color = c; } //@Override public void paint(Graphics2D g, JComponent object, int width, int height) { g.setColor(color); g.fillRect(2, 2, width - 5, height - 5); //g.fill3DRect(2, 2, width - 4, height - 4, false); g.setColor(Color.BLUE); g.drawRect(2, 2, width - 5, height - 5); //g.draw3DRect(2, 2, width - 5, height - 5, false); } } }
true
f102bb3d0149c0f5461a508ef6415b5e13f32809
Java
qearly/VTC2016
/SUMOJavaDP/src/ClassNode.java
UTF-8
139
2.46875
2
[]
no_license
public class ClassNode { double x = 0; double y = 0; public ClassNode(double x, double y) { this.x = x; this.y = y; } }
true
6dd673a89d7f47c98589c771fef4fdb3ca30124a
Java
neha91192/CS5010-Programming-Design-Paradigm
/Assignment 10/submission/src/main/java/howtoinvestfordummies/model/StockInvestmentStrategiesModel.java
UTF-8
4,682
2.984375
3
[]
no_license
package howtoinvestfordummies.model; import java.util.Date; import howtoinvestfordummies.model.adapter.IStockAdapter; import howtoinvestfordummies.model.adapter.RemoteStockAdapterImpl; public class StockInvestmentStrategiesModel extends InvestmentStrategiesModel implements StockInvestmentStrategies { private IStockAdapter adapter; private ITradingInformation tradingInformation; /** * Constructor to create StockInvestmentStrategyModel object. */ public StockInvestmentStrategiesModel() { adapter = RemoteStockAdapterImpl.getInstance(); tradingInformation = new TradingInformation(); } /** * For a given valid date verified by {@link ITradingInformation#isTradingHours(Date)}, it buys * share for the company provided in stockSymbol at a given amount under a given portfolio. If any * of these entries are incorrect, it throws {@link IllegalArgumentException} otherwise returns * true. * * @param date for which user needs to buy stock in Date. * @param amount in double which describes total cost of investment of user for this * purchase. * @param stockSymbol unique company ticker symbol in String to identify stock of that company. * @param portfolioName name of the Portfolio in String for which user wants to buy stock. * @throws IllegalArgumentException in case parameters provided are incorrect. */ @Override public void buySharesOfStock(Date date, double amount, String stockSymbol, String portfolioName) throws IllegalArgumentException { IInvestment stockObj = buyHelper(date, amount, stockSymbol, portfolioName); IPortfolio portfolio = portfolios.get(portfolioName); portfolios.put(portfolioName, portfolio.addInvestments(stockObj)); } /** * For a given valid date verified by {@link ITradingInformation#isTradingHours(Date)}, it buys * share for the company provided in stockSymbol at a given amount under a given portfolio, adding * commission fee. If any of these entries are incorrect, it throws {@link * IllegalArgumentException} otherwise returns true. * * @param transaction object holds all the details of the stocks to be bought i.e. portfolio name, * stock symbol, amount to be invested, commission fee, frequency, date. * @throws IllegalArgumentException in case parameters provided are incorrect. */ @Override public void buyStocksWithCommission(Transaction transaction) throws IllegalArgumentException { String stock = transaction.getStocks().get(0); if (transaction.getCommissionFees().get(stock) < 0) { throw new IllegalArgumentException("Negative commission not allowed!"); } IInvestment stockObj = buyHelper(transaction.getTransactionStartDate(), transaction.getAmount(), stock, transaction.getPortfolioName()); if (transaction.getCommissionFees().get(stock) < 0 ) { throw new IllegalArgumentException("Negative commission not allowed!"); } stockObj.setCommissionFees(transaction.getCommissionFees().get(stock)); IPortfolio portfolio = portfolios.get(transaction.getPortfolioName()); portfolios.put(transaction.getPortfolioName(), portfolio.addInvestments(stockObj)); } /** * This helper method assists in calling adapter to find stock price per share. Once it is * identified, it creates a new stock object and returns with the parameters set in the same. * * @param date of buying this stock. * @param amount in double. * @param stock in String to buy. * @param portfolioName name of the Portfolio, * @return object of type IInvestment. */ private IInvestment buyHelper(Date date, double amount, String stock, String portfolioName) { if (!isPortfolioPresent(portfolioName)) { throw new IllegalArgumentException("Portfolio Not found"); } if (!tradingInformation.isTradingHours(date)) { throw new IllegalArgumentException("Trading is closed for this time. Please try " + "again later"); } if (amount <= TradingInformation.MINIMUM_INVESTMENT) { throw new IllegalArgumentException("Please enter a valid amount."); } double pricePerShare; try { pricePerShare = adapter.getStockPriceForBuying(stock, date); } catch (Exception e) { System.out.println("error in adapter"); throw new IllegalArgumentException(e.getMessage()); } double noOfShares = amount / pricePerShare; noOfShares = Math.round(noOfShares * 100); noOfShares = noOfShares / 100; return new Stock(stock, noOfShares, date, amount); } }
true
43f048c10dbcb929613ae54548c44c021662730b
Java
osharghi/JavaPlayGround
/Algorithms/src/BinaryTreeCreator3.java
UTF-8
681
2.6875
3
[]
no_license
public class BinaryTreeCreator3 { BinaryTreeNode root; BinaryTreeCreator3() { BinaryTreeNode b10 = new BinaryTreeNode(10); BinaryTreeNode b5 = new BinaryTreeNode(5); BinaryTreeNode b3 = new BinaryTreeNode(-3); BinaryTreeNode b3a = new BinaryTreeNode(3); BinaryTreeNode b2 = new BinaryTreeNode(2); BinaryTreeNode b11 = new BinaryTreeNode(11); BinaryTreeNode b3b = new BinaryTreeNode(3); BinaryTreeNode b2a = new BinaryTreeNode(-2); BinaryTreeNode b1 = new BinaryTreeNode(1); root = b10; b10.left = b5; b10.right = b3; b5.left = b3a; b5.right = b2; b3a.left = b3b; b3a.right = b2a; b2.right = b1; b3.right = b11; } }
true
2427928be4ef60bd3089ab85ce85aab1a1bbd074
Java
kannan1001/Java-Projects-Winter-2017-
/JavaAssignments/ProbB.java
UTF-8
1,081
3.671875
4
[]
no_license
public class ProbB { public static void main(String[] args) { final int lt = 1000; boolean perfect = false; int i; for(i = 2; i < lt; i++) { perfect = numPerfect(i); if(perfect==true) { System.out.println(i + " is a perfect number"); } } } public static boolean numPerfect(int i) { boolean perfect = false; int sum = 1; int x; for(x = 2; x <= i/2; x++) { if(i % x == 0) { sum += x; } } if(sum == i) { perfect = true; } return perfect; } } /* 1.Name of program:To display "Perfect Numbers between 2 and 1000" 2.Programmer's name:Geerthana Kannan 3.Current Date:1/24/2017 4.Computer system and compiler you are using:Lenovo Windows 10 ,Eclipse compiler for Java 5.Brief description of the program :To display perfect numbers between 2 and 1000 Output: 6 is a perfect number 28 is a perfect number 496 is a perfect number */
true
9032c6acc020c9a67494ba50653be89c1a8f8cbb
Java
vishalraosu/Ecommerce-Micro-Service-
/User/src/main/java/com/softvision/ecommerce/user/service/UserServiceImpl.java
UTF-8
1,880
2.171875
2
[]
no_license
package com.softvision.ecommerce.user.service; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.softvision.ecommerce.user.dao.UserDAOImpl; import com.softvision.ecommerce.user.model.FeedbackBo; import com.softvision.ecommerce.user.model.UserRegister; @Service("userService") public class UserServiceImpl implements UserService { private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class); @Autowired private UserDAOImpl userdao; public UserDAOImpl getUserdao() { return userdao; } public void setUserdao(UserDAOImpl userdao) { this.userdao = userdao; } @Override @Transactional public UserRegister addPerson(UserRegister p) { LOGGER.info("Calling UserServiceImpl :: addPerson()"); return this.userdao.addPerson(p); } @Override @Transactional public UserRegister updatePerson(UserRegister p) { LOGGER.info("Calling UserServiceImpl :: updatePerson()"); return this.userdao.updatePerson(p); } @Override @Transactional public List<UserRegister> listUsers() { return this.userdao.listUsers(); } @Override @Transactional public UserRegister getPersonByEmail(UserRegister userRegister) { LOGGER.info("Calling UserServiceImpl :: getPersonByEmail()"); return this.userdao.getDetails(userRegister); } @Override @Transactional public UserRegister getUserById(UserRegister userRegister) { LOGGER.info("Calling UserServiceImpl :: getUserById()"); return this.userdao.getUserById(userRegister); } @Override @Transactional public FeedbackBo addFeedback(FeedbackBo feedbackBo) { LOGGER.info("Calling UserServiceImpl :: addFeedback()"); return this.userdao.saveFeedback(feedbackBo); } }
true
1325ffbb86d5f9d968d206eb1b0a993267df4a39
Java
ziyaliuye/eclipse-workspace
/spring-cxf-server/src/main/java/cn/cnm/service/PersonService.java
UTF-8
238
1.90625
2
[]
no_license
package cn.cnm.service; import javax.jws.WebMethod; import javax.jws.WebService; import cn.cnm.pojo.Person; // 定义接口(SEI) @WebService public interface PersonService { @WebMethod Person getPerson(String id); }
true
d0d513926622b121d00928251004c430034c07bb
Java
LaDistance/api_rest_twic_client
/src/com/servlets/CompareVilles.java
UTF-8
2,752
2.59375
3
[]
no_license
package com.servlets; import java.io.IOException; import java.text.DecimalFormat; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.lucene.util.SloppyMath; import com.beans.Ville; import com.client.VilleClient; /** * Servlet implementation class Test */ @WebServlet("/CompareVilles") public class CompareVilles extends HttpServlet { private static final long serialVersionUID = 1L; private VilleClient villeClient; /** * @see HttpServlet#HttpServlet() */ public void init() throws ServletException { this.villeClient = new VilleClient(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ArrayList<Ville> listeVilles = villeClient.getAll(); request.setAttribute("villes", listeVilles); this.getServletContext().getRequestDispatcher( "/WEB-INF/compareVilles.jsp" ).forward( request, response ); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String insee1 = request.getParameter("insee1"); String insee2 = request.getParameter("insee2"); Ville ville1 = villeClient.getVille(Integer.parseInt(insee1)).get(0); Ville ville2 = villeClient.getVille(Integer.parseInt(insee2)).get(0); double longitude1, latitude1, longitude2, latitude2; latitude1 = Double.parseDouble(ville1.getLatitude()); longitude1 = Double.parseDouble(ville1.getLongitude()); latitude2 = Double.parseDouble(ville2.getLatitude()); longitude2 = Double.parseDouble(ville2.getLongitude()); double RawDelta = Math.acos(Math.cos(latitude1)*Math.cos(latitude2)*Math.cos(longitude1)*Math.cos(longitude2) + Math.cos(latitude1)*Math.sin(longitude1)*Math.cos(latitude2)*Math.sin(longitude2) + Math.sin(latitude1)*Math.sin(latitude2)); //double distance = RawDelta * 6378.0; double distanceMeters = SloppyMath.haversinMeters(latitude1, longitude1, latitude2, longitude2); double distanceKm = distanceMeters/1000; DecimalFormat df = new DecimalFormat("#.##"); String distance = df.format(distanceKm); request.setAttribute("ville1", ville1); request.setAttribute("ville2", ville2); request.setAttribute("distance", distance); System.out.println("La distance entre la ville "+ ville1.getNom() + " et la ville "+ ville2.getNom() + " est : "+ distance + "km."); doGet(request, response); } }
true
71691535122664f26b05a091c6dc6ad104503e1f
Java
alldatacenter/alldata
/lake/amoro/flink/v1.12/flink/src/main/java/com/netease/arctic/flink/catalog/factories/ArcticCatalogFactory.java
UTF-8
4,499
1.648438
2
[ "Apache-2.0", "BSD-3-Clause", "MIT" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netease.arctic.flink.catalog.factories; import com.netease.arctic.ams.api.properties.CatalogMetaProperties; import com.netease.arctic.flink.InternalCatalogBuilder; import com.netease.arctic.flink.catalog.ArcticCatalog; import com.netease.arctic.flink.catalog.descriptors.ArcticCatalogValidator; import org.apache.flink.table.catalog.Catalog; import org.apache.flink.table.descriptors.DescriptorProperties; import org.apache.flink.table.factories.CatalogFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.netease.arctic.flink.catalog.descriptors.ArcticCatalogValidator.METASTORE_URL; import static com.netease.arctic.flink.catalog.descriptors.ArcticCatalogValidator.PROPERTIES_PREFIX; import static org.apache.flink.table.descriptors.CatalogDescriptorValidator.CATALOG_DEFAULT_DATABASE; import static org.apache.flink.table.descriptors.CatalogDescriptorValidator.CATALOG_PROPERTY_VERSION; import static org.apache.flink.table.descriptors.CatalogDescriptorValidator.CATALOG_TYPE; /** * Factory for {@link ArcticCatalog} */ public class ArcticCatalogFactory implements CatalogFactory { private static final Logger LOG = LoggerFactory.getLogger(ArcticCatalogFactory.class); @Override public Catalog createCatalog(String name, Map<String, String> properties) { final DescriptorProperties descriptorProperties = getValidatedProperties(properties); final String defaultDatabase = descriptorProperties.getOptionalString(CATALOG_DEFAULT_DATABASE) .orElse(ArcticCatalog.DEFAULT_DB); String metastoreUrl = descriptorProperties.getString(METASTORE_URL); Map<String, String> arcticCatalogProperties = descriptorProperties.getPropertiesWithPrefix(PROPERTIES_PREFIX); return new ArcticCatalog(name, defaultDatabase, InternalCatalogBuilder.builder().metastoreUrl(metastoreUrl).properties(arcticCatalogProperties)); } private static DescriptorProperties getValidatedProperties(Map<String, String> properties) { final DescriptorProperties descriptorProperties = new DescriptorProperties(true); descriptorProperties.putProperties(properties); new ArcticCatalogValidator().validate(descriptorProperties); return descriptorProperties; } @Override public Map<String, String> requiredContext() { Map<String, String> context = new HashMap<>(); context.put(CATALOG_TYPE, ArcticCatalogValidator.CATALOG_TYPE_VALUE_ARCTIC); // backwards compatibility context.put(CATALOG_PROPERTY_VERSION, "1"); return context; } @Override public List<String> supportedProperties() { List<String> properties = new ArrayList<>(); // default database properties.add(CATALOG_DEFAULT_DATABASE); properties.add(METASTORE_URL); // storage config and authorization config properties.add(PROPERTIES_PREFIX + "." + CatalogMetaProperties.LOAD_AUTH_FROM_AMS); properties.add(PROPERTIES_PREFIX + "." + CatalogMetaProperties.AUTH_CONFIGS_KEY_HADOOP_USERNAME); properties.add(PROPERTIES_PREFIX + "." + CatalogMetaProperties.AUTH_CONFIGS_KEY_PRINCIPAL); properties.add(PROPERTIES_PREFIX + "." + CatalogMetaProperties.AUTH_CONFIGS_KEY_KRB_PATH); properties.add(PROPERTIES_PREFIX + "." + CatalogMetaProperties.AUTH_CONFIGS_KEY_KRB_ENCODE); properties.add(PROPERTIES_PREFIX + "." + CatalogMetaProperties.AUTH_CONFIGS_KEY_KEYTAB_PATH); properties.add(PROPERTIES_PREFIX + "." + CatalogMetaProperties.AUTH_CONFIGS_KEY_KEYTAB_ENCODE); properties.add(PROPERTIES_PREFIX + "." + CatalogMetaProperties.AUTH_CONFIGS_KEY_TYPE); return properties; } }
true
88a9734225da2a4d6f2f702170dcfd14ab0f392c
Java
k-Francisco/Aria
/app/src/main/java/com/example/ksfgh/aria/ViewModel/PlayerActivityViewModel.java
UTF-8
8,397
1.984375
2
[]
no_license
package com.example.ksfgh.aria.ViewModel; import android.databinding.BindingAdapter; import android.databinding.ObservableBoolean; import android.databinding.ObservableField; import android.databinding.ObservableInt; import android.databinding.ObservableLong; import android.databinding.adapters.SeekBarBindingAdapter; import android.media.Image; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.SeekBar; import com.bumptech.glide.Glide; import com.bumptech.glide.load.resource.bitmap.CircleCrop; import com.bumptech.glide.request.RequestOptions; import com.example.ksfgh.aria.Model.CustomSongModelForPlaylist; import com.example.ksfgh.aria.R; import com.example.ksfgh.aria.Singleton; import com.example.ksfgh.aria.View.activities.PlayerActivity; import org.simple.eventbus.EventBus; import org.simple.eventbus.Subscriber; import java.util.concurrent.TimeUnit; import io.reactivex.Observable; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Consumer; import jp.wasabeef.glide.transformations.BlurTransformation; import jp.wasabeef.glide.transformations.CropCircleTransformation; /** * Created by ksfgh on 05/02/2018. */ public class PlayerActivityViewModel { public PlayerActivity playerActivity; public ObservableField<CustomSongModelForPlaylist> song; public ObservableField<String> songDuration = new ObservableField<>(); public ObservableField<String> currentTime = new ObservableField<>(); public ObservableInt seekBarMax = new ObservableInt(); public ObservableInt seekBarProgress = new ObservableInt(); private Disposable disposable; public ObservableBoolean nextVisibility; public ObservableBoolean previousVisibility; public ObservableBoolean isShuffled; public ObservableBoolean isRepeated; public PlayerActivityViewModel(PlayerActivity playerActivity) { this.playerActivity = playerActivity; song = new ObservableField<>(); nextVisibility = new ObservableBoolean(); previousVisibility = new ObservableBoolean(); isShuffled = new ObservableBoolean(); isRepeated = new ObservableBoolean(); isThereANext(""); isThereAPrevious(""); EventBus.getDefault().register(this); onNextSong(""); isPlayerShuffled(); isPlayerRepeated(); } @BindingAdapter("bind:imgBlur") public static void imgBlur(ImageView view, String image){ Glide.with(view.getContext()).load(image) .apply(RequestOptions.overrideOf(500,500)) .apply(RequestOptions.bitmapTransform(new BlurTransformation(70))) .into(view); } @BindingAdapter("bind:imgUrl") public static void imgUrl(ImageView view, String image){ Glide.with(view.getContext()).load(image) .apply(RequestOptions.overrideOf(250,250)) .apply(RequestOptions.centerCropTransform()) .into(view); } @Subscriber(tag = "songTimer") public void songTimer(String empty){ if(disposable != null) if(!disposable.isDisposed()){ disposable.dispose(); playerActivity.clearDisposable(); } if(isPlayerPlaying()){ int timer = (int)(Singleton.homeScreen.exoPlayer.getCurrentPosition()/1000) + 1; disposable = Observable.interval(1, TimeUnit.SECONDS) .observeOn(AndroidSchedulers.mainThread()) .take((Singleton.homeScreen.exoPlayer.getDuration()/1000) - (Singleton.homeScreen.exoPlayer.getCurrentPosition() / 1000)) .map(x -> timer+x) .doOnNext(new Consumer<Long>() { @Override public void accept(Long aLong) throws Exception { seekBarProgress.set(Integer.parseInt(String.valueOf(aLong))); currentTime.set(Singleton.getInstance().utilities.timeToString((int) Singleton.homeScreen.exoPlayer.getCurrentPosition())); } }) .doOnError(new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { } }) .subscribe(); playerActivity.addDisposables(disposable); } } public void onProgressChanged(SeekBar view, int progress, boolean fromUser){ Log.d("sbSeek", String.valueOf(progress)); if(fromUser){ EventBus.getDefault().post(progress, "seekSongTo"); seekBarProgress.set((int) Singleton.homeScreen.exoPlayer.getCurrentPosition()/1000); currentTime.set(Singleton.getInstance().utilities.timeToString((int) Singleton.homeScreen.exoPlayer.getCurrentPosition())); } } public Boolean isPlayerPlaying(){ return Singleton.getInstance().isPlayerPlaying; } ImageView view; public void pauseOrPlay(View view){ this.view = (ImageView) view; if(Singleton.getInstance().isPlayerPlaying){ EventBus.getDefault().post(false, "playOrPause"); this.view.setImageResource(R.drawable.exo_controls_play); //EventBus.getDefault().post(false, "setFabSrc"); } else { EventBus.getDefault().post(true, "playOrPause"); this.view.setImageResource(R.drawable.exo_controls_pause); //EventBus.getDefault().post(true, "setFabSrc"); } } @Subscriber(tag="onNextSong") public void onNextSong(String empty){ song.set(Singleton.getInstance().song); songDuration.set(Singleton.getInstance().utilities.timeToString((int)Singleton.homeScreen.exoPlayer.getDuration())); currentTime.set(Singleton.getInstance().utilities.timeToString((int) Singleton.homeScreen.exoPlayer.getCurrentPosition())); seekBarMax.set((int)Singleton.homeScreen.exoPlayer.getDuration()/1000); seekBarProgress.set((int) Singleton.homeScreen.exoPlayer.getCurrentPosition()/1000); songTimer(""); } public void nextSong(){ EventBus.getDefault().post("", "nextSong"); } public void previousSong(){ EventBus.getDefault().post("", "previousSong"); } @Subscriber(tag = "isThereAPrevious") public void isThereAPrevious(String empty){ if(Singleton.homeScreen.windowIndex-1 >= 0) previousVisibility.set(true); else previousVisibility.set(false); } @Subscriber(tag = "isThereANext") public void isThereANext(String empty){ if(Singleton.homeScreen.windowIndex+1 < Singleton.homeScreen.songList.size()) nextVisibility.set(true); else nextVisibility.set(false); } public void isPlayerShuffled(){ if(Singleton.homeScreen.exoPlayer.getShuffleModeEnabled()) isShuffled.set(true); else isShuffled.set(false); } public void shufflePlayer(){ if(Singleton.homeScreen.exoPlayer.getShuffleModeEnabled()){ //Singleton.homeScreen.exoPlayer.setShuffleModeEnabled(false); EventBus.getDefault().post("", "shufflePlaylist"); isShuffled.set(false); } else{ EventBus.getDefault().post("", "shufflePlaylist"); //Singleton.homeScreen.exoPlayer.setShuffleModeEnabled(true); isShuffled.set(true); } } public void isPlayerRepeated(){ if(Singleton.homeScreen.exoPlayer.getRepeatMode() == 0) isRepeated.set(false); else isRepeated.set(true); } public void repeatPlayer(){ if(Singleton.homeScreen.exoPlayer.getRepeatMode() == 0){ EventBus.getDefault().post(2, "repeatPlaylist"); isRepeated.set(true); } else { EventBus.getDefault().post(0,"repeatPlaylist"); isRepeated.set(false); } } @Subscriber(tag = "playerEndOfQueue") public void playerEndOfQueue(String empty){ view.setImageResource(R.drawable.exo_controls_play); } public void destroyActivity(){ playerActivity.finish(); } }
true
130c6961fb0f0ee92af004a2c33b88752e9f6927
Java
779295027/RetrofitOkHttpDemo
/retrofit2okhttp3/src/main/java/demo/materialdesign/sss/com/retrofit2okhttp3/RetrofitService.java
UTF-8
2,970
2.21875
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2016. Sss * 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 demo.materialdesign.sss.com.retrofit2okhttp3; import java.util.Map; import okhttp3.MultipartBody; import okhttp3.RequestBody; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.Multipart; import retrofit2.http.POST; import retrofit2.http.Part; import retrofit2.http.PartMap; import retrofit2.http.Path; import retrofit2.http.QueryMap; /** * Created by sunshaoshuai on 16/9/5. */ public interface RetrofitService { /** * json数据格式 post 方式请求 * * @param path 服务器相对路径 * @param map 参数列表 * @return 返回已经格式化好的数据,格式化成User类型 */ @POST("{path}") Call<ResopnseData> jsonPost(@Path("path") String path, @Body Map map); /** * Get 方式请求 * 调用方法与post请求一样 * * @param path 服务器相对路径 * @param map 参数列表 * @return 返回jsonobject的数据对象 */ @GET("{path}") Call<ResopnseData> get(@Path("path") String path, @QueryMap Map<String, String> map); /** * from表单格式post请求 * 用于上传资源 * * @param path 相对路径 * @param file 资源文件 * @param map 参数列表 * @return 返回jsonobject的数据对象 */ @Multipart @POST("{path}") Call<ResopnseData> fromPost(@Path("path") String path, @Part MultipartBody.Part file, @PartMap Map<String, RequestBody> map); /** * json数据格式 Get 方式请求 用于单个文件下载 * * @param path 服务器相对路径 * @return 返回数据流 */ @GET("{path}") Call<ResponseBody> downloadForGet(@Path("path") String path); /** * json数据格式 Get 方式请求 用于单个文件下载(带参数) * * @param path 服务器相对路径 * @return 返回数据流 */ @GET("{path}") Call<ResponseBody> downloadForGet(@Path("path") String path, @QueryMap Map<String, String> map); /** * json数据格式 Post 方式请求 * * @param path 服务器相对路径 * @param map 参数列表 * @return 返回已经格式化好的数据,格式化成User类型 */ @POST("{path}") Call<ResponseBody> downloadForPost(@Path("path") String path, @Body Map map); }
true
94cf653312ca1e910e162afea8f331d385c8fd19
Java
wentianqi7/JaveSmartphoneProjects
/VocalArtistDisplayer/app/src/main/java/tianqiw/vocalartistdisplayer/fragments/VideoFragment.java
UTF-8
4,195
2.28125
2
[]
no_license
package tianqiw.vocalartistdisplayer.fragments; import android.media.MediaRecorder; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.SurfaceHolder; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.MediaController; import android.widget.VideoView; import java.io.File; import tianqiw.vocalartistdisplayer.activities.R; import tianqiw.vocalartistdisplayer.activities.SongActivity; import tianqiw.vocalartistdisplayer.activities.VideoActivity; import tianqiw.vocalartistdisplayer.activities.WallPaperActivity; import tianqiw.vocalartistdisplayer.utils.GestureHandler; /** * Created by STuotuo.Wen on 2015/11/13. * * can play two videos */ public class VideoFragment extends Fragment implements SurfaceHolder.Callback { private VideoView videoView; private MediaRecorder recorder = null; private Button startBtn = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); View rootView = getActivity().getWindow().getDecorView().findViewById(android.R.id.content); rootView.setOnTouchListener(new GestureHandler(getActivity(), SongActivity.class, WallPaperActivity.class)); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.video_fragment, parent, false); startBtn = (Button) v.findViewById(R.id.bgnBtn); Button playRecordingBtn = (Button) v.findViewById(R.id.playRecordingBtn); Button stpPlayingRecordingBtn = (Button) v.findViewById(R.id.stpPlayingRecordingBtn); videoView = (VideoView) v.findViewById(R.id.videoView); final SurfaceHolder holder = videoView.getHolder(); holder.addCallback(this); holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); startBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { try { playRecording(0); } catch (Exception e) { e.printStackTrace(); } } }); playRecordingBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { try { playRecording(1); } catch (Exception e) { e.printStackTrace(); } } }); stpPlayingRecordingBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { try { stopPlayingRecording(); } catch (Exception e) { e.printStackTrace(); } } }); return v; } @Override public void surfaceCreated(SurfaceHolder holder) { startBtn.setEnabled(true); } @Override public void surfaceDestroyed(SurfaceHolder holder) { } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } private void playRecording(int i) { MediaController mc = new MediaController(getActivity()); videoView.setMediaController(mc); switch (i) { case 0: videoView.setVideoURI(Uri.parse("android.resource://tianqiw.vocalartistdisplayer/" + R.raw.video1)); break; case 1: videoView.setVideoURI(Uri.parse("android.resource://tianqiw.vocalartistdisplayer/" + R.raw.video2)); default: videoView.setVideoURI(Uri.parse("android.resource://tianqiw.vocalartistdisplayer/" + R.raw.video2)); } videoView.start(); } private void stopPlayingRecording() { videoView.stopPlayback(); } @Override public void onDestroy() { super.onDestroy(); if (recorder != null) { recorder.release(); } } }
true
882bbc96f9ff1741d5e4122a7ed841ae3d870774
Java
takayanagi2087/dataforms2
/debug/sample/dao/MaterialOrderTable.java
UTF-8
4,780
2.5625
3
[ "MIT" ]
permissive
package sample.dao; import java.util.Map; import dataforms.dao.Table; import sample.field.OrderIdField; import sample.field.OrderNoField; import sample.field.SupplierIdField; import sample.field.OrderDateField; import sample.field.MemoField; /** * 発注テーブルクラス。 * */ public class MaterialOrderTable extends Table { /** * コンストラクタ。 */ public MaterialOrderTable() { this.setAutoIncrementId(true); this.setComment("発注テーブル"); this.addPkField(new OrderIdField()); //発注ID this.addField(new OrderNoField()); //発注番号 this.addField(new SupplierIdField()); //仕入先ID this.addField(new OrderDateField()); //発注日 this.addField(new MemoField()); //メモ this.addUpdateInfoFields(); } @Override public String getJoinCondition(final Table joinTable, final String alias) { MaterialOrderTableRelation r = new MaterialOrderTableRelation(this); return r.getJoinCondition(joinTable, alias); } /** * Entity操作クラスです。 */ public static class Entity extends dataforms.dao.Entity { /** 発注IDのフィールドID。 */ public static final String ID_ORDER_ID = "orderId"; /** 発注番号のフィールドID。 */ public static final String ID_ORDER_NO = "orderNo"; /** 仕入先IDのフィールドID。 */ public static final String ID_SUPPLIER_ID = "supplierId"; /** 発注日のフィールドID。 */ public static final String ID_ORDER_DATE = "orderDate"; /** メモのフィールドID。 */ public static final String ID_MEMO = "memo"; /** * コンストラクタ。 */ public Entity() { } /** * コンストラクタ。 * @param map 操作対象マップ。 */ public Entity(final Map<String, Object> map) { super(map); } /** * 発注IDを取得します。 * @return 発注ID。 */ public java.lang.Long getOrderId() { return (java.lang.Long) this.getMap().get(Entity.ID_ORDER_ID); } /** * 発注IDを設定します。 * @param orderId 発注ID。 */ public void setOrderId(final java.lang.Long orderId) { this.getMap().put(Entity.ID_ORDER_ID, orderId); } /** * 発注番号を取得します。 * @return 発注番号。 */ public java.lang.String getOrderNo() { return (java.lang.String) this.getMap().get(Entity.ID_ORDER_NO); } /** * 発注番号を設定します。 * @param orderNo 発注番号。 */ public void setOrderNo(final java.lang.String orderNo) { this.getMap().put(Entity.ID_ORDER_NO, orderNo); } /** * 仕入先IDを取得します。 * @return 仕入先ID。 */ public java.lang.Long getSupplierId() { return (java.lang.Long) this.getMap().get(Entity.ID_SUPPLIER_ID); } /** * 仕入先IDを設定します。 * @param supplierId 仕入先ID。 */ public void setSupplierId(final java.lang.Long supplierId) { this.getMap().put(Entity.ID_SUPPLIER_ID, supplierId); } /** * 発注日を取得します。 * @return 発注日。 */ public java.sql.Date getOrderDate() { return (java.sql.Date) this.getMap().get(Entity.ID_ORDER_DATE); } /** * 発注日を設定します。 * @param orderDate 発注日。 */ public void setOrderDate(final java.sql.Date orderDate) { this.getMap().put(Entity.ID_ORDER_DATE, orderDate); } /** * メモを取得します。 * @return メモ。 */ public java.lang.String getMemo() { return (java.lang.String) this.getMap().get(Entity.ID_MEMO); } /** * メモを設定します。 * @param memo メモ。 */ public void setMemo(final java.lang.String memo) { this.getMap().put(Entity.ID_MEMO, memo); } } /** * 発注IDフィールドを取得します。 * @return 発注IDフィールド。 */ public OrderIdField getOrderIdField() { return (OrderIdField) this.getField(Entity.ID_ORDER_ID); } /** * 発注番号フィールドを取得します。 * @return 発注番号フィールド。 */ public OrderNoField getOrderNoField() { return (OrderNoField) this.getField(Entity.ID_ORDER_NO); } /** * 仕入先IDフィールドを取得します。 * @return 仕入先IDフィールド。 */ public SupplierIdField getSupplierIdField() { return (SupplierIdField) this.getField(Entity.ID_SUPPLIER_ID); } /** * 発注日フィールドを取得します。 * @return 発注日フィールド。 */ public OrderDateField getOrderDateField() { return (OrderDateField) this.getField(Entity.ID_ORDER_DATE); } /** * メモフィールドを取得します。 * @return メモフィールド。 */ public MemoField getMemoField() { return (MemoField) this.getField(Entity.ID_MEMO); } }
true
c8255ee1dd381dfbe682ac8ced3104f16080f9a2
Java
niuzhimeng/DesignpatternsDemo
/src/main/java/pio/impl/PoliceIdentity.java
UTF-8
568
2.015625
2
[]
no_license
package pio.impl; import pio.PoiTest; import java.util.List; /** * 身份证一致性 * Created by Nzm on 2017/8/2. */ public class PoliceIdentity extends PoiTest { /** * 访问url */ private String url = "http://localhost:8080/tianXingDataApi/rest/police/identity"; public void appendAccountInfo(String account, String token) { url = super.appendAccountInfo(url, account, token); } @Override public String appendUrl(List<String> cell) { return url + "&name=" + cell.get(0) + "&idCard=" + cell.get(1); } }
true
cc4bb7c95cc02bd52f2eaa403ed671c00c828e99
Java
RayanYanat/Go4Lunch
/app/src/main/java/com/example/go4lunch/ViewModel/adapter/RestaurantRecyclerAdapter.java
UTF-8
9,462
2
2
[]
no_license
package com.example.go4lunch.ViewModel.adapter; import android.annotation.SuppressLint; import android.content.Context; import android.location.Location; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.example.go4lunch.BuildConfig; import com.example.go4lunch.Model.Restaurant.Result; import com.example.go4lunch.Model.Users.User; import com.example.go4lunch.Model.Users.UserHelper; import com.example.go4lunch.R; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationServices; import com.google.android.gms.maps.model.LatLng; import com.google.firebase.firestore.CollectionReference; import com.google.firebase.firestore.QueryDocumentSnapshot; import java.util.ArrayList; import java.util.List; public class RestaurantRecyclerAdapter extends RecyclerView.Adapter<RestaurantRecyclerAdapter.ImageViewHolder> { private List<Result> mData; private static final int MAX_WIDTH = 75; private static final int MAX_HEIGHT = 75; private float[] distanceResults = new float[1]; private Context context; private String currentLocation; private LatLng currentPosition; private List<User> usersList; private String API_KEY = BuildConfig.google_maps_api_key; public RestaurantRecyclerAdapter(List<Result> data) { mData = data; } @NonNull @Override public RestaurantRecyclerAdapter.ImageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.restaurant_item_recyclerview, parent, false); context=view.getContext(); return new ImageViewHolder(view); } public void setResults(List<Result> restauResults) { this.mData=restauResults; notifyDataSetChanged(); } @SuppressLint("SetTextI18n") @Override public void onBindViewHolder(@NonNull RestaurantRecyclerAdapter.ImageViewHolder holder, int position) { LatLng paris = new LatLng(48.806860, 2.272980); String Defaultlocation = paris.latitude+"," + paris.longitude; //get the last position known of the user FusedLocationProviderClient fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(context); fusedLocationProviderClient.getLastLocation().addOnCompleteListener(task -> { Result restauItem = mData.get(position); Location location = task.getResult(); Log.d("TAG", "Response = Adapterlocation " + location); if(location != null){ currentPosition = new LatLng(location.getLatitude(),location.getLongitude()); currentLocation = currentPosition.latitude+"," + currentPosition.longitude; //display distance between user and restaurant Log.d("TAG", "Response = AdapterLocationResponse" + currentLocation); getDistance(currentLocation, restauItem.getGeometry().getLocation()); String distance = Integer.toString(Math.round(distanceResults[0])); holder.restaurantDistance.setText(distance + "m"); }else{ getDistance(Defaultlocation, restauItem.getGeometry().getLocation()); String distance = Integer.toString(Math.round(distanceResults[0])); holder.restaurantDistance.setText(distance + "m"); } }); usersList = new ArrayList<>(); Log.d("TAG", "Response = onBindViewHolder "); Result restauItem = mData.get(position); holder.restaurantWorkmates.setText(""); //display name holder.restaurantName.setText(restauItem.getName()); //display adresse holder.restaurantAdresse.setText(restauItem.getVicinity()); //display user icon holder.nbUserImg.setVisibility(View.VISIBLE); //display photo if (!(restauItem.getPhotos() == null)) { if (!(restauItem.getPhotos().isEmpty())) { Glide.with(holder.itemView.getContext()).load("https://maps.googleapis.com/maps/api/place/photo" + "?maxwidth=" + MAX_WIDTH + "&maxheight=" + MAX_HEIGHT + "&photoreference=" + restauItem.getPhotos().get(0).getPhotoReference() + "&key=" + API_KEY).into(holder.restaurantImg); } } //display distance between user and restaurant Log.d("TAG", "Response = AdapterlocationDistance " + currentLocation); if (currentLocation != null) { getDistance(currentLocation, restauItem.getGeometry().getLocation()); String distance = Integer.toString(Math.round(distanceResults[0])); holder.restaurantDistance.setText(distance + "m"); }else{ getDistance(Defaultlocation, restauItem.getGeometry().getLocation()); String distance = Integer.toString(Math.round(distanceResults[0])); holder.restaurantDistance.setText(distance + "m"); } //display opening hours if(restauItem.getOpeningHours() != null) { if ( restauItem.getOpeningHours().getOpenNow()) { holder.restaurantOpeningHour.setText("OPEN"); } else { holder.restaurantOpeningHour.setText("CLOSE"); } } //display the stars according to the rating if(restauItem.getRating() != null){ double rating = restauItem.getRating(); if (rating > 1) { holder.ratingStars1.setVisibility(View.VISIBLE); if (rating > 2.5) { holder.ratingStars2.setVisibility(View.VISIBLE); if (rating > 4) { holder.ratingStars3.setVisibility(View.VISIBLE); } } } } //display the number of users who have selected a restaurant CollectionReference collectionReference = UserHelper.getUsersCollection(); collectionReference.get().addOnCompleteListener(task -> { if (task.isSuccessful()) { usersList.clear(); for (QueryDocumentSnapshot document : task.getResult()) { String uid = document.getData().get("uid").toString(); String username = document.getData().get("username").toString(); Log.d("TAG", "Response = workmateRecycler " + username); String urlPicture = document.getData().get("urlPicture").toString(); String restoId = document.getData().get("restoId").toString(); User userToAdd = new User(uid,username,urlPicture); if (restoId.equals(restauItem.getPlaceId())) { usersList.add(userToAdd); holder.restaurantWorkmates.setText("(" + usersList.size() + ")"); } } } }); } public Result getRestaurant(int position){ return this.mData.get(position); } @Override public int getItemCount() { int itemCount=0; if (mData != null) itemCount = mData.size(); return itemCount; } static class ImageViewHolder extends RecyclerView.ViewHolder { TextView restaurantName; TextView restaurantAdresse; TextView restaurantDistance; TextView restaurantOpeningHour; TextView restaurantWorkmates; ImageView restaurantImg; ImageView nbUserImg; ImageView ratingStars1; ImageView ratingStars2; ImageView ratingStars3; ImageViewHolder(View itemView) { super(itemView); restaurantName = itemView.findViewById(R.id.restau_recycler_view_item_name); restaurantAdresse = itemView.findViewById(R.id.restau_recycler_view_item_address); restaurantDistance = itemView.findViewById(R.id.restau_recycler_view_item_distance); restaurantOpeningHour = itemView.findViewById(R.id.restau_recycler_view_item_opening_hours); restaurantWorkmates = itemView.findViewById(R.id.restau_recycler_view_item_nb_workmates); restaurantImg = itemView.findViewById(R.id.restau_recycler_view_item_img); ratingStars1 = itemView.findViewById(R.id.res_list_star_1); ratingStars2 = itemView.findViewById(R.id.res_list_star_2); ratingStars3 = itemView.findViewById(R.id.res_list_star_3); nbUserImg = itemView.findViewById(R.id.res_list_workmates_ic); } } private void getDistance(String startLocation, com.example.go4lunch.Model.Restaurant.Location endLocation){ String[] separatedStart = startLocation.split(","); double startLatitude = Double.parseDouble(separatedStart[0]); double startLongitude = Double.parseDouble(separatedStart[1]); double endLatitude = endLocation.getLat(); double endLongitude = endLocation.getLng(); android.location.Location.distanceBetween(startLatitude, startLongitude, endLatitude, endLongitude,distanceResults); } }
true
b9dfc3b97350a6b8e33f7a0a3cbedd7739f76c95
Java
sengeiou/BaiMeiYouXuan
/app/src/test/java/www/example/mrw/baimeiyouxuan/ExampleUnitTest.java
UTF-8
1,015
2.328125
2
[]
no_license
package www.example.mrw.baimeiyouxuan; import android.util.Log; import org.junit.Test; import io.reactivex.Observable; import io.reactivex.ObservableEmitter; import io.reactivex.ObservableOnSubscribe; import io.reactivex.Scheduler; import io.reactivex.functions.BiFunction; import io.reactivex.functions.Consumer; import io.reactivex.schedulers.Schedulers; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { private static final String TAG = "ExampleUnitTest"; @Test public void testRxJavaZip() { // System.out.println("apply: " + Thread.currentThread().getName()); // Observable.just("I", "am", "RxJava").subscribe(new Consumer<Object>() { // public void accept(Object t) throws Exception { // System.out.println("apply: " + t); // } // }); } }
true
bbd8143f6b87befbdd9d0a473b170bbf4f0f4796
Java
champagne/CacheIO
/cacheio-core/src/test/java/com/mobilejazz/cacheio/CacheIOTest.java
UTF-8
3,679
2.09375
2
[ "Apache-2.0" ]
permissive
/* * Copyright (C) 2016 Mobile Jazz * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mobilejazz.cacheio; import android.content.Context; import com.mobilejazz.cacheio.logging.LogLevel; import com.mobilejazz.cacheio.serializer.JavaSerializer; import com.mobilejazz.cacheio.serializer.Serializer; import org.assertj.core.api.Assertions; import org.junit.Before; import org.junit.Test; import static org.mockito.Mockito.mock; public class CacheIOTest extends ApplicationTestCase { public static final String FAKE_IDENTIFIER = "fake.identifier"; private Context context; private Serializer serializer; @Before public void setUp() throws Exception { context = mock(Context.class); serializer = mock(JavaSerializer.class); } @Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionIfSerializerIsNull() throws Exception { CacheIO cacheIO = CacheIO.with(context) .identifier(FAKE_IDENTIFIER) .logLevel(LogLevel.FULL) .serializer(null) .build(); } @Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionIfIdentifierIsNull() throws Exception { CacheIO cacheIO = CacheIO.with(context) .identifier(null) .logLevel(LogLevel.FULL) .serializer(serializer) .build(); } @Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionIfIdentifierIsEmpty() throws Exception { CacheIO cacheIO = CacheIO.with(context).identifier("").logLevel(LogLevel.FULL).serializer(serializer).build(); } @Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionIfLogLevelIsNull() throws Exception { CacheIO cacheIO = CacheIO.with(context) .identifier(FAKE_IDENTIFIER) .logLevel(null) .serializer(serializer) .build(); } @Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionIfContextIsNull() throws Exception { CacheIO cacheIO = CacheIO.with(null) .identifier(FAKE_IDENTIFIER) .logLevel(LogLevel.FULL) .serializer(serializer) .build(); } @Test public void shouldCreateAValidCacheObject() throws Exception { CacheIO cacheIO = CacheIO.with(context) .identifier(FAKE_IDENTIFIER) .logLevel(LogLevel.FULL) .serializer(serializer) .build(); Cache cache = cacheIO.cacheDataSource(); Assertions.assertThat(cache).isNotNull(); } @Test public void shouldCreateDiferentsCacheIOInstanceWithBuildMethod() throws Exception { CacheIO.Builder builder = new CacheIO.Builder(context); builder.identifier(FAKE_IDENTIFIER); builder.logLevel(LogLevel.FULL); builder.serializer(serializer); CacheIO cacheIOOne = builder.build(); cacheIOOne.cacheDataSource(); CacheIO cacheIOTwo = builder.build(); cacheIOOne.cacheDataSource(); Assertions.assertThat(cacheIOOne).isNotEqualTo(cacheIOTwo); } @Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionIfCallToBuildWithoutArguments() throws Exception { CacheIO.with(context).build(); } }
true
ca5b413a81649beabbbb2c8e2747be68b541f1fb
Java
MaRodeR/orika-extension
/src/main/java/org/bp/labs/orika/extension/ExtendedConfigurableMapper.java
UTF-8
10,354
2.15625
2
[]
no_license
package org.bp.labs.orika.extension; import ma.glasnost.orika.MappingContext; import ma.glasnost.orika.MappingContextFactory; import ma.glasnost.orika.impl.ConfigurableMapper; import ma.glasnost.orika.impl.DefaultMapperFactory; import ma.glasnost.orika.metadata.Type; import java.util.*; public abstract class ExtendedConfigurableMapper extends ConfigurableMapper { static final String SOURCE_LIST_CTX_PROPERTY_NAME = "rel_objects_ext_source"; private static MappingContextFactory contextFactory = new MappingContext.Factory(); public static MappingContext createMappingContextWith(Map<Object, Object> properties){ MappingContext context = contextFactory.getContext(); properties.forEach(context::setProperty); return context; } public ExtendedConfigurableMapper() { } public ExtendedConfigurableMapper(boolean autoInit) { super(autoInit); } @Override protected void configureFactoryBuilder(DefaultMapperFactory.Builder factoryBuilder) { super.configureFactoryBuilder(factoryBuilder); // TODO: add custom specification for generating code. It would make using this extension simpler than now. // factoryBuilder.getCodeGenerationStrategy() // .addSpecification(); } @Override public <S, D> Set<D> mapAsSet(Iterable<S> source, Type<S> sourceType, Type<D> destinationType) { MappingContext context = initCtxWithObjects(source); return super.mapAsSet(source, sourceType, destinationType, context); } @Override public <S, D> Set<D> mapAsSet(Iterable<S> source, Type<S> sourceType, Type<D> destinationType, MappingContext context) { addObjectsToCtx(context, source); return super.mapAsSet(source, sourceType, destinationType, context); } @Override public <S, D> Set<D> mapAsSet(S[] source, Type<S> sourceType, Type<D> destinationType) { MappingContext context = initCtxWithObjects(Arrays.asList(source)); return super.mapAsSet(source, sourceType, destinationType, context); } @Override public <S, D> Set<D> mapAsSet(S[] source, Type<S> sourceType, Type<D> destinationType, MappingContext context) { addObjectsToCtx(context, Arrays.asList(source)); return super.mapAsSet(source, sourceType, destinationType, context); } @Override public <S, D> List<D> mapAsList(Iterable<S> source, Type<S> sourceType, Type<D> destinationType) { MappingContext context = initCtxWithObjects(source); return super.mapAsList(source, sourceType, destinationType, context); } @Override public <S, D> List<D> mapAsList(Iterable<S> source, Type<S> sourceType, Type<D> destinationType, MappingContext context) { addObjectsToCtx(context, source); return super.mapAsList(source, sourceType, destinationType, context); } @Override public <S, D> List<D> mapAsList(S[] source, Type<S> sourceType, Type<D> destinationType) { MappingContext context = initCtxWithObjects(Arrays.asList(source)); return super.mapAsList(source, sourceType, destinationType, context); } @Override public <S, D> List<D> mapAsList(S[] source, Type<S> sourceType, Type<D> destinationType, MappingContext context) { addObjectsToCtx(context, Arrays.asList(source)); return super.mapAsList(source, sourceType, destinationType, context); } @Override public <S, D> D[] mapAsArray(D[] destination, Iterable<S> source, Type<S> sourceType, Type<D> destinationType) { MappingContext context = initCtxWithObjects(source); return super.mapAsArray(destination, source, sourceType, destinationType, context); } @Override public <S, D> D[] mapAsArray(D[] destination, S[] source, Type<S> sourceType, Type<D> destinationType) { MappingContext context = initCtxWithObjects(Arrays.asList(source)); return super.mapAsArray(destination, source, sourceType, destinationType, context); } @Override public <S, D> D[] mapAsArray(D[] destination, Iterable<S> source, Type<S> sourceType, Type<D> destinationType, MappingContext context) { addObjectsToCtx(context, source); return super.mapAsArray(destination, source, sourceType, destinationType, context); } @Override public <S, D> D[] mapAsArray(D[] destination, S[] source, Type<S> sourceType, Type<D> destinationType, MappingContext context) { addObjectsToCtx(context, Arrays.asList(source)); return super.mapAsArray(destination, source, sourceType, destinationType, context); } @Override public <S, D> void mapAsCollection(Iterable<S> source, Collection<D> destination, Class<D> destinationClass) { MappingContext context = initCtxWithObjects(source); super.mapAsCollection(source, destination, destinationClass, context); } @Override public <S, D> void mapAsCollection(Iterable<S> source, Collection<D> destination, Class<D> destinationClass, MappingContext context) { addObjectsToCtx(context, source); super.mapAsCollection(source, destination, destinationClass, context); } @Override public <S, D> void mapAsCollection(S[] source, Collection<D> destination, Class<D> destinationCollection) { MappingContext context = initCtxWithObjects(Arrays.asList(source)); super.mapAsCollection(source, destination, destinationCollection, context); } @Override public <S, D> void mapAsCollection(S[] source, Collection<D> destination, Class<D> destinationCollection, MappingContext context) { addObjectsToCtx(context, Arrays.asList(source)); super.mapAsCollection(source, destination, destinationCollection, context); } @Override public <S, D> void mapAsCollection(Iterable<S> source, Collection<D> destination, Type<S> sourceType, Type<D> destinationType) { MappingContext context = initCtxWithObjects(source); super.mapAsCollection(source, destination, sourceType, destinationType, context); } @Override public <S, D> void mapAsCollection(S[] source, Collection<D> destination, Type<S> sourceType, Type<D> destinationType) { MappingContext context = initCtxWithObjects(Arrays.asList(source)); super.mapAsCollection(source, destination, sourceType, destinationType, context); } @Override public <S, D> void mapAsCollection(Iterable<S> source, Collection<D> destination, Type<S> sourceType, Type<D> destinationType, MappingContext context) { addObjectsToCtx(context, source); super.mapAsCollection(source, destination, sourceType, destinationType, context); } @Override public <S, D> void mapAsCollection(S[] source, Collection<D> destination, Type<S> sourceType, Type<D> destinationType, MappingContext context) { addObjectsToCtx(context, Arrays.asList(source)); super.mapAsCollection(source, destination, sourceType, destinationType, context); } @Override public <S, D> Set<D> mapAsSet(Iterable<S> source, Class<D> destinationClass) { MappingContext context = initCtxWithObjects(source); return super.mapAsSet(source, destinationClass, context); } @Override public <S, D> Set<D> mapAsSet(Iterable<S> source, Class<D> destinationClass, MappingContext context) { addObjectsToCtx(context, source); return super.mapAsSet(source, destinationClass, context); } @Override public <S, D> Set<D> mapAsSet(S[] source, Class<D> destinationClass) { MappingContext context = initCtxWithObjects(Arrays.asList(source)); return super.mapAsSet(source, destinationClass, context); } @Override public <S, D> Set<D> mapAsSet(S[] source, Class<D> destinationClass, MappingContext context) { addObjectsToCtx(context, Arrays.asList(source)); return super.mapAsSet(source, destinationClass, context); } @Override public <S, D> List<D> mapAsList(Iterable<S> source, Class<D> destinationClass) { MappingContext context = initCtxWithObjects(source); return super.mapAsList(source, destinationClass, context); } @Override public <S, D> List<D> mapAsList(Iterable<S> source, Class<D> destinationClass, MappingContext context) { addObjectsToCtx(context, source); return super.mapAsList(source, destinationClass, context); } @Override public <S, D> List<D> mapAsList(S[] source, Class<D> destinationClass) { MappingContext context = initCtxWithObjects(Arrays.asList(source)); return super.mapAsList(source, destinationClass, context); } @Override public <S, D> List<D> mapAsList(S[] source, Class<D> destinationClass, MappingContext context) { addObjectsToCtx(context, Arrays.asList(source)); return super.mapAsList(source, destinationClass, context); } @Override public <S, D> D[] mapAsArray(D[] destination, Iterable<S> source, Class<D> destinationClass) { MappingContext context = initCtxWithObjects(source); return super.mapAsArray(destination, source, destinationClass, context); } @Override public <S, D> D[] mapAsArray(D[] destination, S[] source, Class<D> destinationClass) { MappingContext context = initCtxWithObjects(Arrays.asList(source)); return super.mapAsArray(destination, source, destinationClass, context); } @Override public <S, D> D[] mapAsArray(D[] destination, Iterable<S> source, Class<D> destinationClass, MappingContext context) { addObjectsToCtx(context, source); return super.mapAsArray(destination, source, destinationClass, context); } @Override public <S, D> D[] mapAsArray(D[] destination, S[] source, Class<D> destinationClass, MappingContext context) { addObjectsToCtx(context, Arrays.asList(source)); return super.mapAsArray(destination, source, destinationClass, context); } private <S> MappingContext initCtxWithObjects(Iterable<S> source) { MappingContext context = contextFactory.getContext(); addObjectsToCtx(context, source); return context; } private <S> void addObjectsToCtx(MappingContext context, Iterable<S> source) { context.setProperty(SOURCE_LIST_CTX_PROPERTY_NAME, source); } }
true
2ab2c6843a938be083bc8381297894553632918d
Java
windmxa1/TendaEHome
/src/org/dao/imp/UserDaoImp.java
UTF-8
1,655
2.609375
3
[]
no_license
package org.dao.imp; import org.dao.UserDao; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import org.model.User; import org.util.HibernateSessionFactory; public class UserDaoImp implements UserDao { public User getUser(String phone, String password) { try { Session session = HibernateSessionFactory.getSession(); String sql = "from User where phone=? and password = ?"; Query query = session.createQuery(sql); query.setParameter(0, phone); query.setParameter(1, password); query.setMaxResults(1); User u = (User) query.uniqueResult(); return u; } catch (Exception e) { e.printStackTrace(); return null; } finally { HibernateSessionFactory.closeSession(); } } public Long saveOrUpdate(User user) { Long id = 0L; try { Session session = HibernateSessionFactory.getSession(); Transaction ts = session.beginTransaction(); if (user.getId() != null) { session.update(user); } else { id = (Long) session.save(user); } ts.commit(); return id; } catch (Exception e) { e.printStackTrace(); return -1L; } finally { HibernateSessionFactory.closeSession(); } } public boolean delete(Long id) { try { Session session = HibernateSessionFactory.getSession(); Transaction ts = session.beginTransaction(); String sql = "delete from User where id=?"; Query query = session.createQuery(sql); query.setParameter(0, id); query.executeUpdate(); ts.commit(); return true; } catch (Exception e) { e.printStackTrace(); return false; } finally { HibernateSessionFactory.closeSession(); } } }
true
b4f185363d856465943b7abfe65c801a06eff950
Java
CooperUrich/Enterprise-Computing
/Project2/Threads.java
UTF-8
2,641
3.640625
4
[]
no_license
/* Name: Cooper Urich * Course: CNT 4714Spring 2021Assignment * title: Project2–Synchronized, Cooperating ThreadsUnder Locking * Due Date:February 14, 2021 */ import java.util.*; public class Threads { public static void main(String[] args) { // Make new bank account BankAccount account = new BankAccount(); // Make the Deposit threads Bank_Deposit_Threads d1 = new Bank_Deposit_Threads(account); Bank_Deposit_Threads d2 = new Bank_Deposit_Threads(account); Bank_Deposit_Threads d3 = new Bank_Deposit_Threads(account); Bank_Deposit_Threads d4 = new Bank_Deposit_Threads(account); Bank_Deposit_Threads d5 = new Bank_Deposit_Threads(account); // Make the Withdrawal threads Bank_Withdrawal_Threads w1 = new Bank_Withdrawal_Threads(account); Bank_Withdrawal_Threads w2 = new Bank_Withdrawal_Threads(account); Bank_Withdrawal_Threads w3 = new Bank_Withdrawal_Threads(account); Bank_Withdrawal_Threads w4 = new Bank_Withdrawal_Threads(account); Bank_Withdrawal_Threads w5 = new Bank_Withdrawal_Threads(account); Bank_Withdrawal_Threads w6 = new Bank_Withdrawal_Threads(account); Bank_Withdrawal_Threads w7 = new Bank_Withdrawal_Threads(account); Bank_Withdrawal_Threads w8 = new Bank_Withdrawal_Threads(account); Bank_Withdrawal_Threads w9 = new Bank_Withdrawal_Threads(account); // Name the deposit threads (d1 - d5) d1.setName("d1"); d2.setName("d2"); d3.setName("d3"); d4.setName("d4"); d5.setName("d5"); // Name 9 withdrawal threads (w1 - w9) w1.setName("w1"); w2.setName("w2"); w3.setName("w3"); w4.setName("w4"); w5.setName("w5"); w6.setName("w6"); w7.setName("w7"); w8.setName("w8"); w9.setName("w9"); // Print out the header information println("Deposit Threads\t\t\tWithdrawl Threads\t\t Balance \t\t\t"); println("---------------\t\t\t-----------------\t\t-----------------\t\t\t"); // start() is built in method for threads that begins running each thread // Start and run the threads d1.start(); // Run more withdraw threads so the account can be populated at first w1.start(); w2.start(); w3.start(); w4.start(); // Second Deposit Thread d2.start(); // Start the next few deposit threads w5.start(); w6.start(); // Third Deposit Thread d3.start(); // Fourth Deposit Thread d4.start(); w7.start(); w8.start(); // Fifth Deposit Thread d5.start(); w9.start(); } // print methods for cleaner looking print statements public static void print(String s) { System.out.print(s); } public static void println(String s) { System.out.println(s); } }
true
4c05db4973db6430dfcc35612af5110728c93e79
Java
kelu124/pyS3
/org/apache/poi/poifs/dev/POIFSViewable.java
UTF-8
239
1.851563
2
[ "MIT" ]
permissive
package org.apache.poi.poifs.dev; import java.util.Iterator; public interface POIFSViewable { String getShortDescription(); Object[] getViewableArray(); Iterator<Object> getViewableIterator(); boolean preferArray(); }
true
e3b61a13ba389bf4a02e705e3ffc741816627488
Java
JetBrains/intellij-community
/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/trivialMethodReference/afterLambda.java
UTF-8
119
1.734375
2
[ "Apache-2.0" ]
permissive
// "Replace with qualifier" "true-preview" class Test { void f(Runnable runnable) { Runnable r = runnable; } }
true
9b559fa944625dc54369b86f301fe0f6621d01c1
Java
Vibhor116/java-datastructures-implementation
/src/main/java/com/leetcode/easy/arrays/ThirdMaximumNumber.java
UTF-8
1,471
3.515625
4
[]
no_license
//https://leetcode.com/problems/third-maximum-number/ //414 package com.leetcode.easy.arrays; import java.io.BufferedReader; import java.io.InputStreamReader; public class ThirdMaximumNumber { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] input_Array = br.readLine().split("\\s+"); int[] final_Array = new int[input_Array.length]; for (int i = 0; i < final_Array.length; i++) { final_Array[i] = Integer.parseInt(input_Array[i]); } System.out.println(ThirdMaximumNumber.thirdMax(final_Array)); } public static int thirdMax(int[] nums) { int firstMax = Integer.MIN_VALUE; int secondMax = Integer.MIN_VALUE; int thirdMax = Integer.MIN_VALUE; if (nums.length < 3) { thirdMax = secondMax; } for (int i = 0; i < nums.length; i++) { if (nums[i] > firstMax) { secondMax = firstMax; firstMax = nums[i]; } else if (nums[i] > secondMax && nums[i] != firstMax) { thirdMax=secondMax; secondMax = nums[i]; } else if (nums[i] > thirdMax && nums[i] != secondMax) { thirdMax = nums[i]; } } System.out.println(firstMax + " " + secondMax+" "+thirdMax); return thirdMax; } }
true
c6311498dcc89351292d9128f06509142504df60
Java
anilkumar23/bank-service
/src/main/java/com/bank/app/enums/AccountTypeEnum.java
UTF-8
92
1.539063
2
[]
no_license
package com.bank.app.enums; public enum AccountTypeEnum { CURRENT, SAVINGS, CHECKING }
true
10d8b5f1a2f88179591b66cf258c6b716f520094
Java
yishuo/Web-Semantic
/src/main/java/semweb/ClassifierImpl.java
UTF-8
4,954
2.015625
2
[]
no_license
package semweb; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Map; import javax.security.auth.Subject; import org.semarglproject.jena.rdf.rdfa.JenaRdfaReader; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.RDFNode; import com.hp.hpl.jena.rdf.model.ResIterator; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.Selector; import com.hp.hpl.jena.rdf.model.SimpleSelector; import com.hp.hpl.jena.rdf.model.Statement; import com.hp.hpl.jena.rdf.model.StmtIterator; import com.hp.hpl.jena.vocabulary.RDF; import com.hp.hpl.jena.vocabulary.RDFS; public class ClassifierImpl implements Classifier { protected ClassifierImpl() throws RemoteException { super(); // TODO Auto-generated constructor stub } public Collection<String> retrieveTypes(String iri) { // TODO Auto-generated method stub JenaRdfaReader.inject(); Model m = null; Collection <String> list_resource = new HashSet <String>(); RDFNode r; try { m = ModelFactory.createDefaultModel(); m.read(iri,"TTL"); } catch ( org.apache.jena.riot.RiotException e) { // TODO Auto-generated catch block try { m = ModelFactory.createDefaultModel(); m.read(iri,"RDF/XML"); } catch ( org.apache.jena.riot.RiotException a) { // TODO Auto-generated catch block try { m = ModelFactory.createDefaultModel(); m.read(iri,"RDFA"); } catch ( org.apache.jena.riot.RiotException c) { c.printStackTrace(); } } }finally{ // m.write(System.out); } Resource subject = m.createResource(iri); StmtIterator iter = m.listStatements(subject,RDF.type,(RDFNode)null ); if (iter.hasNext()) { System.out.println("The model contains those rdf:type :"); // int n=0; while (iter.hasNext()) { r = iter.nextStatement().getObject(); // System.out.println(" " + r); String resource =r.toString(); list_resource.add(resource); // n++; // System.out.println(n); } }else { System.out.println("No rdf:type were found in the model"); } for(String i:list_resource ){ System.out.println(i); } return list_resource; } public Collection<String> retrieveSuperClasses(String iri) { // TODO Auto-generated method stub JenaRdfaReader.inject(); Model m = null; Collection <String> list_resource = new HashSet <String>(); Collection <String> list_subClassOf = new HashSet <String>(); RDFNode r; try { m = ModelFactory.createDefaultModel(); m.read(iri,"TTL"); } catch ( org.apache.jena.riot.RiotException e) { // TODO Auto-generated catch block try { m = ModelFactory.createDefaultModel(); m.read(iri,"RDF/XML"); } catch ( org.apache.jena.riot.RiotException a) { // TODO Auto-generated catch block try { m = ModelFactory.createDefaultModel(); m.read(iri,"RDFA"); } catch ( org.apache.jena.riot.RiotException c) { c.printStackTrace(); } } }finally{ // m.write(System.out); } Resource subject = m.createResource(iri); StmtIterator iter = m.listStatements(subject ,RDFS.subClassOf,(RDFNode)null ); if (iter.hasNext()) { System.out.println("The model contains those rdfs:subClassOf :"); while (iter.hasNext()) { r = iter.nextStatement().getObject(); String resource =r.toString(); System.out.println(resource); list_resource.add(resource); } }else { System.out.println("No rdfs:subClassOf were found in the model"); } list_subClassOf.addAll(list_resource); for(String i:list_resource ){ System.out.println("_________________________"); System.out.println("I will do the next research with iri"); System.out.println(i); System.out.println("result:"); list_subClassOf.addAll(this.retrieveSuperClasses(i)); } return list_subClassOf; } public Collection<String> getAllTypes(String url) { // TODO Auto-generated method stub Collection <String> list_type = new HashSet <String>(); Collection <String> list_alltype = new HashSet <String>(); list_type=this.retrieveTypes(url); list_alltype.addAll(list_type); for(String iri : list_type ){ list_alltype.addAll(this.retrieveSuperClasses(iri)); } return list_alltype; } public boolean isOfType(String entityIRI, String classIRI) { // TODO Auto-generated method stub Collection <String> list_alltypes = new HashSet <String>(); Boolean result=false; if((entityIRI==null)||(classIRI==null)){ return result; }else{ list_alltypes=this.getAllTypes(entityIRI); for(String i : list_alltypes){ if(i.equals(classIRI)){ result=true; break; } } return result; } } }
true
dbda72361ecef39a0f3306c4961d1092976f450d
Java
sevendeveloper77/SpringBootThymeleafCustomerApp
/src/main/java/com/app/controller/CustomerController.java
UTF-8
3,114
2.515625
3
[]
no_license
package com.app.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.Errors; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.app.model.Customer; import com.app.service.ICustomerService; import com.app.validator.CustomerValidator; @Controller @RequestMapping("/customer") public class CustomerController { @Autowired private ICustomerService service; @Autowired private CustomerValidator validator; //1.Display Reg with form backing object @RequestMapping("/reg") public String showReg(Model map) { map.addAttribute("customer", new Customer()); return "Register"; } //2.On click submit read data form and save into db @RequestMapping(value="/save", method = RequestMethod.POST) public String saveData(@ModelAttribute Customer customer, Model map, Errors errors) { //First Call validator validator.validate(customer, errors); if(!errors.hasErrors()) { //insert into db Integer id=service.saveCustomer(customer); map.addAttribute("message", "Customer '"+id+"' Created"); //clean form backing object map.addAttribute("customer", new Customer()); }else { //goto back same page map.addAttribute("message", "Please Check All Errors"); } return "Register"; } //3.Display all records in db at UI @RequestMapping("/all") public String showAll(Model map) { //fetch data from db List<Customer> cobs=service.getAllCoustomers(); //send data to ui map.addAttribute("list", cobs); return "Data"; } //4.fetch Data Based on id and display @RequestMapping("/view/{id}") public String viewOne(@PathVariable Integer id, Model map) { Customer c=service.getOneCustomer(id); map.addAttribute("ob", c); return "View"; } //5.delete row based on id @RequestMapping("/delete/{id}") public String deleteOne(@PathVariable Integer id, Model map) { service.deleteCustomer(id); //fetch all new data List<Customer> cobs=service.getAllCoustomers(); //send data to ui map.addAttribute("list",cobs); //success message map.addAttribute("message", "Customer '"+id+"' deleted"); return "Data"; } //6.edit row based on id @RequestMapping("/edit/{id}") public String showEditPage(@PathVariable Integer id, Model map) { Customer c=service.getOneCustomer(id); map.addAttribute("customer", c); return "Edit"; } //7.update row based on id @RequestMapping(value="/update", method = RequestMethod.POST) public String updateData(@ModelAttribute Customer customer, Model map) { //update into db Integer id = customer.getCustId(); service.updateCustomer(id, customer); //response.sendRedirect return "redirect:all"; } }
true
722d32c3f7fadad5e2751573229ebee688273c01
Java
amrizal/ContactPicker
/app/src/main/java/com/example/amrizalzainuddin/contactpicker/ContactPicker.java
UTF-8
2,688
2.140625
2
[]
no_license
package com.example.amrizalzainuddin.contactpicker; import android.app.Activity; import android.content.ContentUris; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.provider.ContactsContract; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.SimpleCursorAdapter; public class ContactPicker extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_contact_picker); final Cursor c = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null,null,null,null); String[] from = new String[]{ContactsContract.Contacts.DISPLAY_NAME_PRIMARY}; int[] to = new int[]{R.id.itemTextView}; SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.listitemlayout, c, from, to); ListView lv = (ListView)findViewById(R.id.contactListView); lv.setAdapter(adapter); lv.setOnItemClickListener(new ListView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //move the cursor to the selected item c.moveToPosition(position); //extract the row id int rowId = c.getInt(c.getColumnIndexOrThrow("_id")); //construct the result URI Uri outURI = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, rowId); Intent outData = new Intent(); outData.setData(outURI); setResult(Activity.RESULT_OK, outData); finish(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_contact_picker, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
true
5d162df27f41eebedb4a8418379b7eb485cbd9b3
Java
xjpro/keepcraft
/src/keepcraft/data/UserStatsDataManager.java
UTF-8
8,299
2.609375
3
[]
no_license
package keepcraft.data; import keepcraft.Keepcraft; import keepcraft.data.models.UserStats; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import java.util.UUID; public class UserStatsDataManager { private Database database; public UserStatsDataManager(Database database) { this.database = database; init(); } private void init() { try { PreparedStatement statement = database.createStatement("CREATE TABLE IF NOT EXISTS userStats " + "(RecordStart, UserName, WorldSeed, WorldGUID, PlaySeconds, BlocksPlaced, BlocksRemoved, BlocksAddedToChests, " + "BlocksRemovedFromChests, BlocksAddedToTeamChests, BlocksRemovedFromTeamChests, " + "PlayerKills, PlayerDeaths, AttackingKills, DefendingKills, AttackingDeaths, DefendingDeaths, " + "ArrowShots, ArrowHits, SwordHits, AxeHits, OtherHits, ArrowBlocks, MeleeBlocks, ArrowStrikes, " + "CriticalHits, IronMined, GoldMined, DiamondMined)"); statement.execute(); } catch (Exception e) { Keepcraft.error("Error initializing table: " + e.getMessage()); } finally { database.close(); } } public void saveData(String userName, UUID worldGUID, UserStats stats) { Keepcraft.log("Updating stats for " + userName); try { PreparedStatement statement = database.createStatement("UPDATE userStats SET " + "PlaySeconds = PlaySeconds + ?, " + "BlocksPlaced = BlocksPlaced + ?, " + "BlocksRemoved = BlocksRemoved + ?, " + "BlocksAddedToChests = BlocksAddedToChests + ?, " + "BlocksRemovedFromChests = BlocksRemovedFromChests + ?, " + "BlocksAddedToTeamChests = BlocksAddedToTeamChests + ?, " + "BlocksRemovedFromTeamChests = BlocksRemovedFromTeamChests + ?, " + "PlayerKills = PlayerKills + ?, " + "PlayerDeaths = PlayerDeaths + ?, " + "AttackingKills = AttackingKills + ?, " + "DefendingKills = DefendingKills + ?, " + "AttackingDeaths = AttackingDeaths + ?, " + "DefendingDeaths = DefendingDeaths + ?, " + "ArrowShots = ArrowShots + ?, " + "ArrowHits = ArrowHits + ?, " + "SwordHits = SwordHits + ?, " + "AxeHits = AxeHits + ?, " + "OtherHits = OtherHits + ?, " + "ArrowBlocks = ArrowBlocks + ?, " + "MeleeBlocks = MeleeBlocks + ?, " + "ArrowStrikes = ArrowStrikes + ?, " + "CriticalHits = CriticalHits + ?, " + "IronMined = IronMined + ?, " + "GoldMined = GoldMined + ?, " + "DiamondMined = DiamondMined + ? " + "WHERE UserName = ? AND WorldGUID = ?"); statement.setInt(1, (int) stats.playSeconds); statement.setInt(2, stats.blocksPlaced); statement.setInt(3, stats.blocksRemoved); statement.setInt(4, stats.blocksAddedToChests); statement.setInt(5, stats.blocksRemovedFromChests); statement.setInt(6, stats.blocksAddedToTeamChests); statement.setInt(7, stats.blocksRemovedFromTeamChests); statement.setInt(8, stats.playerKills); statement.setInt(9, stats.playerDeaths); statement.setInt(10, stats.attackingKills); statement.setInt(11, stats.defendingKills); statement.setInt(12, stats.attackingDeaths); statement.setInt(13, stats.defendingDeaths); statement.setInt(14, stats.arrowShots); statement.setInt(15, stats.arrowHits); statement.setInt(16, stats.swordHits); statement.setInt(17, stats.axeHits); statement.setInt(18, stats.otherHits); statement.setInt(19, stats.arrowBlocks); statement.setInt(20, stats.meleeBlocks); statement.setInt(21, stats.arrowStrikes); statement.setInt(22, stats.criticalHits); statement.setInt(23, stats.ironMined); statement.setInt(24, stats.goldMined); statement.setInt(25, stats.diamondMined); statement.setString(26, userName); statement.setString(27, worldGUID.toString()); int rowsAffected = statement.executeUpdate(); if (rowsAffected == 0) { statement = database.createStatement("INSERT INTO userStats " + "(PlaySeconds, BlocksPlaced, BlocksRemoved, BlocksAddedToChests, " + "BlocksRemovedFromChests, BlocksAddedToTeamChests, BlocksRemovedFromTeamChests, " + "PlayerKills, PlayerDeaths, AttackingKills, DefendingKills, AttackingDeaths, DefendingDeaths, " + "ArrowShots, ArrowHits, SwordHits, AxeHits, OtherHits, ArrowBlocks, MeleeBlocks, ArrowStrikes, " + "CriticalHits, IronMined, GoldMined, DiamondMined, UserName, WorldGUID, RecordStart) " + "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))"); statement.setInt(1, (int) stats.playSeconds); statement.setInt(2, stats.blocksPlaced); statement.setInt(3, stats.blocksRemoved); statement.setInt(4, stats.blocksAddedToChests); statement.setInt(5, stats.blocksRemovedFromChests); statement.setInt(6, stats.blocksAddedToTeamChests); statement.setInt(7, stats.blocksRemovedFromTeamChests); statement.setInt(8, stats.playerKills); statement.setInt(9, stats.playerDeaths); statement.setInt(10, stats.attackingKills); statement.setInt(11, stats.defendingKills); statement.setInt(12, stats.attackingDeaths); statement.setInt(13, stats.defendingDeaths); statement.setInt(14, stats.arrowShots); statement.setInt(15, stats.arrowHits); statement.setInt(16, stats.swordHits); statement.setInt(17, stats.axeHits); statement.setInt(18, stats.otherHits); statement.setInt(19, stats.arrowBlocks); statement.setInt(20, stats.meleeBlocks); statement.setInt(21, stats.arrowStrikes); statement.setInt(22, stats.criticalHits); statement.setInt(23, stats.ironMined); statement.setInt(24, stats.goldMined); statement.setInt(25, stats.diamondMined); statement.setString(26, userName); statement.setString(27, worldGUID.toString()); statement.execute(); } } catch (Exception e) { Keepcraft.error("Error saving stats data: " + e.getMessage()); } finally { database.close(); } } public List<String> getRecentlyPlayedUserNamesByPlayTime() { List<String> previouslyPlayedUserNames = new ArrayList<>(); // Gather all users from the past map try { PreparedStatement statement = database.createStatement("SELECT WorldGUID FROM userStats " + "WHERE WorldGUID IS NOT NULL AND ((julianday(datetime('now')) - julianday(RecordStart)) < ?) " + "GROUP BY WorldGUID " + "ORDER BY RecordStart DESC"); // Fake UUID if one not provided, used for testing statement.setFloat(1, 5.0f); ResultSet result = statement.executeQuery(); ArrayList<String> recentWorldGUIDs = new ArrayList<>(); while (result.next()) { recentWorldGUIDs.add(result.getString("WorldGUID")); } if (recentWorldGUIDs.size() > 0) { // We have world or more worlds in the past week StringBuilder whereClause = new StringBuilder(); for (int i = 0; i < recentWorldGUIDs.size(); i++) { whereClause.append(String.format("WorldGUID = \"%s\"", recentWorldGUIDs.get(i))); if (i != recentWorldGUIDs.size() - 1) { whereClause.append(" OR "); } } statement = database.createStatement("SELECT UserName, SUM(PlaySeconds) AS TotalPlayed FROM userStats " + "WHERE " + whereClause + " " + "GROUP BY UserName " + "ORDER BY TotalPlayed DESC"); result = statement.executeQuery(); while (result.next()) { previouslyPlayedUserNames.add(result.getString("UserName")); } } } catch (Exception e) { Keepcraft.error("Error looking up recent activity: " + e.getMessage()); } finally { database.close(); } return previouslyPlayedUserNames; } public long getSecondsPlayedOnServer(String userName) { long secondsPlayed = 0; Keepcraft.log(String.format("Checking for time spent on server for '%s'", userName)); try { PreparedStatement statement = database.createStatement("SELECT SUM(PlaySeconds) AS TotalPlayed FROM userStats WHERE UserName = ?"); statement.setString(1, userName); ResultSet result = statement.executeQuery(); boolean found = result.next(); if (found) { secondsPlayed = result.getLong("TotalPlayed"); } result.close(); } catch (Exception e) { Keepcraft.error("Error during time spent on server lookup: " + e.getMessage()); } finally { database.close(); } return secondsPlayed; } }
true
d8b9db0b80c4b6e344ce80d8cdea92229163f01f
Java
JoelZhu/WorldofWarships
/app/src/main/java/com/joelzhu/worldofwarships/present/task/command/BaseHttpStrategy.java
UTF-8
1,254
2.3125
2
[ "Apache-2.0" ]
permissive
package com.joelzhu.worldofwarships.present.task.command; import android.content.Intent; import com.joelzhu.base.present.HttpRequestTask; import com.joelzhu.base.present.LogUtil; import com.joelzhu.common.http.OnPostRequestListener; public abstract class BaseHttpStrategy implements IHttpStrategy { private final static String TAG = BaseHttpStrategy.class.getSimpleName(); private HttpRequestTask task; abstract Class<? extends HttpRequestTask> bindingTask(); public BaseHttpStrategy() { createTaskInstance(); } @Override public void executeStrategy(Intent intent) { if (task != null) { task.execute(task.requestParam(intent)); } else { LogUtil.e(TAG, "Task is null, ignore executing."); } } public void subscribeListener(OnPostRequestListener listener) { if (task != null) { task.subscribeRequestListener(listener); } } private void createTaskInstance() { try { task = bindingTask().newInstance(); } catch (IllegalAccessException | InstantiationException e) { LogUtil.e(TAG, "Create the instance of task failed."); LogUtil.e(TAG, e.getMessage()); } } }
true
967fcda71b7aec5e02793575a9f854e074a56555
Java
Team3482Arrowbotics/Offseason2017
/SteamWorks2017CompetitionCode/src/org/usfirst/frc/team3482/robot/commands/RotateManipulator.java
UTF-8
829
2.296875
2
[]
no_license
package org.usfirst.frc.team3482.robot.commands; import org.usfirst.frc.team3482.robot.Robot; import org.usfirst.frc.team3482.robot.subsystems.ManipulatorPosition; import edu.wpi.first.wpilibj.command.Command; public class RotateManipulator extends Command { ManipulatorPosition angle; public RotateManipulator(ManipulatorPosition angle) { this.angle = angle; } protected void initialize() { Robot.gearManipulator.moveGearManipStartPos(); System.out.println(Robot.gearManipulator.manipulatorTalon.getSetpoint()); } protected void execute() { } protected boolean isFinished() { return false; } protected void interrupted() { System.out.println("interrupted"); //Robot.gearManipulator.stopGearManipWheels(); Robot.gearManipulator.moveGearManipReadyPos(); } protected void end() { } }
true
3a1405cd3efb220247231e6b586568cfc7a3dc5b
Java
divyjain40041/WebServices-Framework
/WEB-INF/classes/bobby/services/DAOConnection.java
UTF-8
398
2.515625
3
[]
no_license
package bobby.services; import java.sql.*; public class DAOConnection { private DAOConnection(){} public static Connection getConnection() { Connection connection=null; try { Class.forName("com.mysql.cj.jdbc.Driver"); connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/school","root","JAIN@divy40041"); }catch(Exception e) { System.out.println(e.getMessage()); } return connection; } }
true
f47088d6d4efbe450378543e7f792db23898bc17
Java
sofflen/rest_api_trial
/src/main/java/com/example/trial/service/UserService.java
UTF-8
1,071
2.5625
3
[]
no_license
package com.example.trial.service; import com.example.trial.dto.UserDto; import com.example.trial.dto.UserPatchDto; import com.example.trial.model.User; import java.util.List; /** * Service's interface for operating users */ public interface UserService { /** * finds user by login * @param login login of user * @return user */ User getByLogin(String login); /** * saves user to database * @param userDto dto representation of user * @return {@code true} if new user was created successfully */ boolean saveUser(UserDto userDto); /** * updates existing user * @param login login of existing user * @param userPatchDto dto for patching of user * @return updated user */ User updateUser(String login, UserPatchDto userPatchDto); /** * removes user from database if exists * @param login login of user */ void deleteUser(String login); /** * finds all users in database * @return {@code List} of users */ List<User> getAll(); }
true
c58aa046279cb69d07473b223727452b5f5e781c
Java
linolastella/CSC207H1---W2016
/A3/test/PublicationsTest.java
UTF-8
1,322
2.546875
3
[]
no_license
package test; import static org.junit.Assert.*; import java.util.ArrayList; import org.junit.Test; import driver.Publications; public class PublicationsTest { @Test public void testSetPublicationsList() { String url = "rs.html"; Publications publ = new Publications(url); ArrayList<String> actual = publ.publicationsList; ArrayList<String> expected = new ArrayList<String>(); expected.add("On fast exploration in 2D and 3D terrains with multiple " + "robots"); expected.add("Sonic Grid: an auditory interface for the visually impaired " + "to navigate GUI-based environments"); expected.add("Multi robotic exploration with communication requirement to" + " a fixed base station"); expected.add("Covering hostile terrains with partial and complete " + "visibilities: On minimum distance paths"); expected.add("On reduced time fault tolerant paths for multiple UAVs " + "covering a hostile terrain"); assertArrayEquals(expected.toArray(), actual.toArray()); } @Test public void testGetTotalPublications(){ String url = "rs.html"; Publications publ = new Publications(url); int totalNumberOfPublications = 5; int actual = publ.totalPublications; assertEquals(actual, totalNumberOfPublications); } }
true
baa4ee5fbda6f01214b7d4b5d90d153f825813f4
Java
nameishari/Portfolio-Java-Legacy
/src/com/hari/myprofile/vo/SuccessMessageVO.java
UTF-8
715
1.960938
2
[]
no_license
package com.hari.myprofile.vo; public class SuccessMessageVO { String statusString; String statusClass; String commonClass; String status; public String getStatusString() { return statusString; } public void setStatusString(String statusString) { this.statusString = statusString; } public String getStatusClass() { return statusClass; } public void setStatusClass(String statusClass) { this.statusClass = statusClass; } public String getCommonClass() { return commonClass; } public void setCommonClass(String commonClass) { this.commonClass = commonClass; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } }
true
e2cb0b88ec96b2a5cdeea09ab89d628d557baebe
Java
ricardo17coelho/Bar-System
/bar/src/model/Snack.java
UTF-8
480
2.765625
3
[]
no_license
package model; import java.io.Serializable; ; /** * @author morga * */ public abstract class Snack extends Produkt{ protected String groesse; /** * Konstruktor von Snack */ public Snack(String name, double preis, String iconPath, String groesse) { super(name, preis, iconPath); this.groesse = groesse; } /* * toString Methode */ public String toString() { String result = super.toString(); return getClass().getSimpleName() + ":: " + result; } }
true
d065938a0bcdf549518f143d899dc75d683c5c4d
Java
cocktail-office/Feve
/src/org/cocktail/feve/eos/modele/mangue/EOVCandidatEvaluation.java
UTF-8
7,862
1.710938
2
[]
no_license
package org.cocktail.feve.eos.modele.mangue; import org.cocktail.feve.eos.modele.grhum.EOIndividu; import org.cocktail.fwkcktlwebapp.common.CktlLog; import org.cocktail.fwkcktlwebapp.common.util.DateCtrl; import org.cocktail.fwkcktlwebapp.server.database.CktlDataBus; import com.webobjects.eocontrol.EOEditingContext; import com.webobjects.eocontrol.EOQualifier; import com.webobjects.foundation.NSArray; import com.webobjects.foundation.NSMutableArray; import com.webobjects.foundation.NSTimestamp; import com.webobjects.foundation.NSValidation; public class EOVCandidatEvaluation extends _EOVCandidatEvaluation { public EOVCandidatEvaluation() { super(); } public void validateForInsert() throws NSValidation.ValidationException { this.validateObjectMetier(); validateBeforeTransactionSave(); super.validateForInsert(); } public void validateForUpdate() throws NSValidation.ValidationException { this.validateObjectMetier(); validateBeforeTransactionSave(); super.validateForUpdate(); } public void validateForDelete() throws NSValidation.ValidationException { super.validateForDelete(); } /** * Apparemment cette methode n'est pas appelee. * * @see com.webobjects.eocontrol.EOValidation#validateForUpdate() */ public void validateForSave() throws NSValidation.ValidationException { validateObjectMetier(); validateBeforeTransactionSave(); super.validateForSave(); } /** * Peut etre appele a partir des factories. * * @throws NSValidation.ValidationException */ public void validateObjectMetier() throws NSValidation.ValidationException { } /** * A appeler par les validateforsave, forinsert, forupdate. * */ private final void validateBeforeTransactionSave() throws NSValidation.ValidationException { } // ajouts public final static String D_TENUE_ENTRETIEN_KEY = "dTenueEntretien"; public final static String D_VISA_RESPONSABLE_RH_KEY = "dVisaResponsableRh"; // les classements possibles public final static String SORT_EVALUATEUR = TO_EVALUATEUR_KEY + "." + EOIndividu.NOM_PRENOM_KEY; public final static String SORT_AGENT = TO_INDIVIDU_KEY + "." + EOIndividu.NOM_PRENOM_KEY; public final static String SORT_DATE_ENTRETIEN = D_TENUE_ENTRETIEN_KEY; public final static String SORT_DATE_VISA_RH = D_VISA_RESPONSABLE_RH_KEY; /** * Indique si l'enregistrement EOEvaluation existe */ private boolean isEOEvaluationCreee() { return toEvaluation() != null; } /** * */ public boolean isViseParResponsableRh() { boolean result = false; if (isEOEvaluationCreee()) { result = toEvaluation().isViseParResponsableRh(); } return result; } /** * */ public NSTimestamp dTenueEntretien() { NSTimestamp result = null; if (isEOEvaluationCreee()) { result = toEvaluation().dTenueEntretien(); } return result; } /** * */ public NSTimestamp dVisaResponsableRh() { NSTimestamp result = null; if (isViseParResponsableRh()) { result = toEvaluation().dVisaResponsableRh(); } return result; } /** * La fenetre volante sur la case à cocher visa RH */ public String tipChkDVisaResponsableRh() { String str = ""; if (isEOEvaluationCreee() && toEvaluation().isViseParResponsableRh()) { str = "Visé RH le " + DateCtrl.dateToString(toEvaluation().dVisaResponsableRh()); } else { str = "Pas encore visé"; } return str; } /** * Methode interne permettant de liste un ensemble d'objets * <code>VCandidatEvaluation</code>. * * @param ec * @param individu * : l'individu responsable * @param periode * @param ignoreNm1 * : faut-il ne pas tenir compte des N-1 directs * @param onlyNm1 * : faut ne traiter que les N-1 directs * @return */ public static NSArray getVCandidatEvaluationForIndividuAndPeriodeInContext( EOIndividu individu, EOEvaluationPeriode periode, boolean ignoreNm1, boolean onlyNm1) { NSArray records = new NSArray(); EOEditingContext ec = individu.editingContext(); // cas particulier du grand chef (de la hierachie) : on retourne tous les // individus de la hierarchie EOHierarchie eoHierarchieBigBoss = EOHierarchie.getEoHierarchieRacineForPeriodeInContext(ec, periode); if (eoHierarchieBigBoss != null) { EOIndividu theBigBoss = eoHierarchieBigBoss.toIndividu(); if (!onlyNm1 && theBigBoss.noIndividu().intValue() == individu.noIndividu().intValue()) { records = fetchVCandidatEvaluations( ec, CktlDataBus.newCondition(TO_EVALUATION_PERIODE_KEY + "=%@", new NSArray(periode)), null); } else { // la liste des individu N-p d'apres la hierarchie dont on soustrait les // N-1 NSMutableArray individusNmp = new NSMutableArray( onlyNm1 ? (NSArray) EOHierarchie.findHierarchieForIndividuRespNmpInContext(ec, individu, periode).valueForKey(EOHierarchie.TO_INDIVIDU_KEY) : (NSArray) EOHierarchie.findHierarchieForIndividuRespInContext(ec, individu, periode).valueForKey(EOHierarchie.TO_INDIVIDU_KEY)); // on retire tous les N-1 si besoin if (ignoreNm1) { // la liste des individu N-1 d'apres la hierarchie NSArray individusNm1 = (NSArray) EOHierarchie.findHierarchieForIndividuRespInContext( ec, individu, periode).valueForKey(EOHierarchie.TO_INDIVIDU_KEY); individusNmp.removeObjectsInArray(individusNm1); } /* * String strQual = ""; NSArray args = new NSArray(); if * (individusNmp.count() > 0) { strQual += "("; for (int i = 0; i < * individusNmp.count(); i++) { EOIndividu unIndividu = (EOIndividu) * individusNmp.objectAtIndex(i); strQual += TO_INDIVIDU_KEY + "=%@"; * args = args.arrayByAddingObject(unIndividu); if (i != * individusNmp.count() -1) strQual += " OR "; } strQual += * ") AND "+TO_EVALUATION_PERIODE_KEY+"=%@"; args = * args.arrayByAddingObject(periode); long start = * System.currentTimeMillis(); records = fetchVCandidatEvaluations(ec, * CktlDataBus.newCondition(strQual, args), null); CktlLog.log( * "getVCandidatEvaluationForIndividuAndPeriodeInContext() fetchVCandidatEvaluations duration : " * + (System.currentTimeMillis()-start) + "ms"); } */ if (individusNmp.count() > 0) { long start = System.currentTimeMillis(); for (int i = 0; i < individusNmp.count(); i++) { EOIndividu unIndividu = (EOIndividu) individusNmp.objectAtIndex(i); EOQualifier qual = CktlDataBus.newCondition( TO_INDIVIDU_KEY + "=%@ and " + TO_EVALUATION_PERIODE_KEY + "=%@", new NSArray(new Object[] { unIndividu, periode })); records = records.arrayByAddingObjectsFromArray( fetchVCandidatEvaluations(ec, qual, null)); } CktlLog.log("getVCandidatEvaluationForIndividuAndPeriodeInContext() fetchVCandidatEvaluations duration : " + (System.currentTimeMillis() - start) + "ms"); } } } return records; } public String display() { return toIndividu().display() + " du " + DateCtrl.dateToString(toEvaluationPeriode().epeDDebut()) + " au " + DateCtrl.dateToString(toEvaluationPeriode().epeDFin()); } /** * Retourne l'enregistrement associ� � un individu et une periode * * @param individu * @param periode * @return */ public static EOVCandidatEvaluation findRecordForIndividuAndPeriode(EOIndividu individu, EOEvaluationPeriode periode) { EOEditingContext ec = individu.editingContext(); return fetchRequiredVCandidatEvaluation(ec, CktlDataBus.newCondition(TO_INDIVIDU_KEY + "=%@ and " + TO_EVALUATION_PERIODE_KEY + " =%@", new NSArray(new Object[] { individu, periode }))); } @Override public EOVCandidatEvaluation toVCandidatEvaluation() { return this; } public void setIsViseParResponsableRh(boolean value) { if (toEvaluation() != null) { toEvaluation().setIsViseParResponsableRh(value); } } }
true
d29e6ee9b1cb4a5f042637031c69a2dd86a7a639
Java
nabinmillias/EmployeeRetrofit2
/app/src/main/java/com/example/employeeretrofit/MainActivity.java
UTF-8
2,311
2.15625
2
[]
no_license
package com.example.employeeretrofit; import android.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.widget.Toast; import com.example.employeeretrofit.Mofdels.EmployeeList; import java.util.ArrayList; import java.util.List; import dmax.dialog.SpotsDialog; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class MainActivity extends AppCompatActivity { // SpotsDialog.Builder alertDialog; AlertDialog dialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); dialog=new SpotsDialog(this); // alertDialog=new SpotsDialog(this); dialog.show(); final RecyclerView recyclerview = findViewById(R.id.rvxml); recyclerview.setHasFixedSize(true); RecyclerView.LayoutManager layoutmanager = new LinearLayoutManager(getApplicationContext()); recyclerview.setLayoutManager(layoutmanager); Utils Utilss = new Utils(); Call<List<EmployeeList>> employeeListCall = Utilss.getApi().empcall(); employeeListCall.enqueue(new Callback<List<EmployeeList>>() { @Override public void onResponse(Call<List<EmployeeList>> call, Response<List<EmployeeList>> response) { Toast.makeText(MainActivity.this, "success", Toast.LENGTH_SHORT).show(); LinearLayoutManager verticalLayoutmanager = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.VERTICAL, false); recyclerview.setLayoutManager(verticalLayoutmanager); DataAdapter adpt=new DataAdapter((ArrayList<EmployeeList>) response.body(),MainActivity.this); recyclerview.setAdapter(adpt); dialog.dismiss(); } @Override public void onFailure(Call<List<EmployeeList>> call, Throwable t) { dialog.dismiss(); Toast.makeText(MainActivity.this, "failure", Toast.LENGTH_SHORT).show(); } }); } }
true