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
6f1106878cb64fa727d9cb1a4e05b67a677a65bc
Java
namndd00325/D00325-example
/EnterpriseApplication/EnterpriseApplication-ejb/src/java/session/TblUserFacadeLocal.java
UTF-8
677
1.945313
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package session; import entity.TblUser; import java.util.List; import javax.ejb.Local; /** * * @author Nam Nguyen */ @Local public interface TblUserFacadeLocal { void create(TblUser tblUser); void edit(TblUser tblUser); void remove(TblUser tblUser); TblUser find(Object id); List<TblUser> findAll(); List<TblUser> findRange(int[] range); int count(); boolean checkLogin(String username, String password); }
true
308a2fb6103fda9fe91b50a13826ef1d0b073725
Java
hairlun/radix-android
/src/com/patr/radix/LockSetupActivity.java
UTF-8
5,988
2.140625
2
[ "Apache-2.0" ]
permissive
package com.patr.radix; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.xutils.common.util.LogUtil; import com.patr.radix.ui.view.LockPatternView; import com.patr.radix.ui.view.TitleBarView; import com.patr.radix.ui.view.LockPatternView.Cell; import com.patr.radix.ui.view.LockPatternView.DisplayMode; import com.patr.radix.ui.view.LockPatternView.OnPatternListener; import com.patr.radix.utils.Constants; import com.patr.radix.utils.PrefUtil; import com.patr.radix.utils.ToastUtil; import com.patr.radix.utils.lock.LockPatternUtils; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.widget.TextView; public class LockSetupActivity extends Activity implements OnPatternListener { Context context; private TitleBarView titleBarView; /** 手势密码界面 */ private LockPatternView lockPatternView; /** 标题 */ private TextView title; /** 步骤开始 */ private static final int STEP_1 = 1; /** 步骤第一次设置手势完成 */ private static final int STEP_2 = 2; /** 步骤按下继续按钮 */ private static final int STEP_3 = 3; /** 步骤第二次设置手势完成 */ private static final int STEP_4 = 4; // /** 步骤按确认按钮 */ // private static final int SETP_5 = 4; /** 当前步骤 */ private int step; /** 手势密码数据 */ private List<Cell> choosePattern; private boolean confirm = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_lock_setup); context = this; initView(); } private void initView() { titleBarView = (TitleBarView) findViewById(R.id.lock_settings_titlebar); titleBarView.setTitle(R.string.titlebar_lock_setup); lockPatternView = (LockPatternView) findViewById(R.id.lock_pattern); lockPatternView.setOnPatternListener(this); title = (TextView) findViewById(R.id.text_lock_hint); step = STEP_1; updateView(); } private void updateView() { switch (step) { case STEP_1: choosePattern = null; confirm = false; lockPatternView.clearPattern(); lockPatternView.enableInput(); break; case STEP_2: title.setTextColor(getResources().getColor(R.color.right_text)); title.setText(R.string.lockpattern_reenter_new_lockpattern); lockPatternView.clearPattern(); lockPatternView.enableInput(); break; case STEP_3: title.setTextColor(getResources().getColor(R.color.right_text)); title.setText(R.string.lockpattern_reenter_new_lockpattern); lockPatternView.clearPattern(); lockPatternView.enableInput(); break; case STEP_4: if (confirm) { title.setTextColor(getResources().getColor(R.color.right_text)); title.setText(R.string.lockpattern_ok); lockPatternView.disableInput(); PrefUtil.save(context, Constants.PREF_LOCK_KEY, LockPatternUtils.patternToString(choosePattern)); finish(); } else { title.setTextColor(getResources().getColor(R.color.error_text)); title.setText(R.string.lock_confirm_error); lockPatternView.setDisplayMode(DisplayMode.Wrong); lockPatternView.enableInput(); } break; default: break; } } @Override public void onPatternStart() { LogUtil.d("onPatternStart"); } @Override public void onPatternCleared() { LogUtil.d("onPatternCleared"); } @Override public void onPatternCellAdded(List<Cell> pattern) { LogUtil.d("onPatternCellAdded"); } @Override public void onPatternDetected(List<Cell> pattern) { LogUtil.d("onPatternDetected"); if (pattern.size() < LockPatternUtils.MIN_LOCK_PATTERN_SIZE) { ToastUtil.showShort(this, R.string.lockpattern_recording_incorrect_too_short); lockPatternView.setDisplayMode(DisplayMode.Wrong); return; } if (choosePattern == null) { choosePattern = new ArrayList<Cell>(pattern); // LogUtil.d( "choosePattern = "+choosePattern.toString()); // LogUtil.d( "choosePattern.size() = "+choosePattern.size()); LogUtil.d("choosePattern = " + Arrays.toString(choosePattern.toArray())); step = STEP_2; updateView(); return; } // [(row=1,clmn=0), (row=2,clmn=0), (row=1,clmn=1), (row=0,clmn=2)] // [(row=1,clmn=0), (row=2,clmn=0), (row=1,clmn=1), (row=0,clmn=2)] LogUtil.d("choosePattern = " + Arrays.toString(choosePattern.toArray())); LogUtil.d("pattern = " + Arrays.toString(pattern.toArray())); if (choosePattern.equals(pattern)) { // LogUtil.d( "pattern = "+pattern.toString()); // LogUtil.d( "pattern.size() = "+pattern.size()); LogUtil.d("pattern = " + Arrays.toString(pattern.toArray())); confirm = true; } else { confirm = false; } step = STEP_4; updateView(); } /** * * @param context */ public static void start(Context context) { Intent intent = new Intent(context, LockSetupActivity.class); context.startActivity(intent); } }
true
4064cfcdcfe227a029e146460f91c847cf38a7ba
Java
anukat2015/perconik
/sk.stuba.fiit.perconik.activity/src/sk/stuba/fiit/perconik/activity/listeners/ui/text/TextMarkListener.java
UTF-8
5,668
1.867188
2
[ "MIT" ]
permissive
package sk.stuba.fiit.perconik.activity.listeners.ui.text; import java.util.LinkedList; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IMarkSelection; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchPartReference; import sk.stuba.fiit.perconik.activity.listeners.ActivityListener; import sk.stuba.fiit.perconik.activity.serializers.ui.selection.MarkSelectionSerializer; import sk.stuba.fiit.perconik.core.annotations.Version; import sk.stuba.fiit.perconik.core.listeners.MarkSelectionListener; import sk.stuba.fiit.perconik.core.listeners.PartListener; import sk.stuba.fiit.perconik.data.events.Event; import sk.stuba.fiit.perconik.eclipse.jface.text.LineRegion; import sk.stuba.fiit.perconik.utilities.concurrent.TimeValue; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import static sk.stuba.fiit.perconik.activity.listeners.ui.text.TextMarkListener.Action.MARK; import static sk.stuba.fiit.perconik.activity.serializers.ConfigurableSerializer.StandardOption.TREE; import static sk.stuba.fiit.perconik.data.content.StructuredContents.key; import static sk.stuba.fiit.perconik.utilities.concurrent.TimeValue.of; /** * TODO * * @author Pavol Zbell * @since 1.0 */ @Version("0.1.0.alpha") public final class TextMarkListener extends AbstractTextListener implements MarkSelectionListener, PartListener { // TODO note that mark selection is generated only on incremental search (ctrl + j) // or for marked regions used in Emacs style editing static final TimeValue selectionEventPause = of(500L, MILLISECONDS); static final TimeValue selectionEventWindow = of(10L, SECONDS); private final TextMarkEvents events; public TextMarkListener() { this.events = new TextMarkEvents(this); } enum Action implements ActivityListener.Action { MARK; private final String name; private final String path; private Action() { this.name = actionName("eclipse", "text", this); this.path = actionPath(this.name); } public String getName() { return this.name; } public String getPath() { return this.path; } } Event build(final long time, final Action action, final LinkedList<TextMarkEvent> sequence, final IWorkbenchPart part, final IMarkSelection selection, final LineRegion region) { assert sequence.getLast().selection.equals(selection); Event data = this.build(time, action, part, region); data.put(key("sequence", "first", "timestamp"), sequence.getFirst().time); data.put(key("sequence", "first", "raw"), new MarkSelectionSerializer(TREE).serialize(sequence.getFirst().selection)); data.put(key("sequence", "last", "timestamp"), sequence.getLast().time); data.put(key("sequence", "last", "raw"), new MarkSelectionSerializer(TREE).serialize(sequence.getLast().selection)); data.put(key("sequence", "count"), sequence.size()); return data; } void process(final long time, final Action action, final LinkedList<TextMarkEvent> sequence, final IWorkbenchPart part, final IMarkSelection selection) { IDocument document = selection.getDocument(); LineRegion region = LineRegion.compute(document, selection.getOffset(), selection.getLength()).normalize(); this.send(action.getPath(), this.intern(this.build(time, action, sequence, part, selection, region))); } static final class TextMarkEvents extends ContinuousEvent<TextMarkListener, TextMarkEvent> { TextMarkEvents(final TextMarkListener listener) { super(listener, "text-mark", selectionEventPause, selectionEventWindow); } @Override protected boolean accept(final LinkedList<TextMarkEvent> sequence, final TextMarkEvent event) { return true; } @Override protected boolean continuous(final LinkedList<TextMarkEvent> sequence, final TextMarkEvent event) { return sequence.getLast().isContinuousWith(event); } @Override protected void process(final LinkedList<TextMarkEvent> sequence) { this.listener.handleSelectionEvents(sequence); } } void handleSelectionEvents(final LinkedList<TextMarkEvent> sequence) { this.execute(new Runnable() { public void run() { TextMarkEvent event = sequence.getLast(); process(event.time, MARK, sequence, event.part, event.selection); } }); } public void partOpened(final IWorkbenchPartReference reference) { // ignore } public void partClosed(final IWorkbenchPartReference reference) { // ignore } public void partActivated(final IWorkbenchPartReference reference) { // ignore } public void partDeactivated(final IWorkbenchPartReference reference) { // ensures that pending events are flushed on part deactivation, // this primarily handles proper selection termination on shutdown, // as a side effect it breaks event continuation this.events.flush(); } public void partVisible(final IWorkbenchPartReference reference) { // ignore } public void partHidden(final IWorkbenchPartReference reference) { // ignore } public void partBroughtToTop(final IWorkbenchPartReference reference) { // ignore } public void partInputChanged(final IWorkbenchPartReference reference) { // ignore } private void push(final long time, final IWorkbenchPart part, final IMarkSelection selection) { this.events.push(new TextMarkEvent(time, part, selection)); } public void selectionChanged(final IWorkbenchPart part, final IMarkSelection selection) { final long time = this.currentTime(); this.push(time, part, selection); } }
true
c83d49a0deedfc117b3ab875b6838cb6f0b7d32c
Java
AdoucheAli/advancedjava
/1-concurrency-deepdive/src/com/joshcummings/badvisibility/NoVisibility.java
UTF-8
626
3.109375
3
[]
no_license
package com.joshcummings.badvisibility; public class NoVisibility { private volatile static boolean ready; private static int number; private static class ReaderThread extends Thread { public void run() { while (!ready) { } if ( number == 0 ) { System.out.println("WHAT?"); } } } public static void main(String[] args) throws InterruptedException { //for ( int i = 0; i < 100000; i++ ) { number = 0; ready = false; Thread t = new ReaderThread(); t.start(); //Thread.sleep(1000); number = 42; ready = true; t.join(); //System.out.println(i + " completed"); //} } }
true
831194cc32c1d24961ea4c8db753ff2087b760a3
Java
xiaoshuaishuai/rpc
/qrpc-mode/src/main/java/org/rpc/qrpc/mode/proxy/stati/RealSubject.java
UTF-8
282
1.90625
2
[]
no_license
package org.rpc.qrpc.mode.proxy.stati; /** * 真实对象 * @author shuaishuaixiao * */ public class RealSubject extends AbstractSubject{ @Override public void request() { // TODO Auto-generated method stub System.out.println("真实对象request"); } }
true
5d766f6051f9d0e43e0bdc0541035f584a649956
Java
ek169/princeton-algorithms-part1
/RandomizedQueue.java
UTF-8
2,907
3.375
3
[]
no_license
import java.util.Iterator; import java.util.Random; import java.util.NoSuchElementException; public class RandomizedQueue<Item> implements Iterable<Item> { private int numberItems = 0; private Item[] itemArray = (Item[]) new Object[1]; private Random random; public RandomizedQueue() { random = new Random(); } public boolean isEmpty() { return numberItems == 0; } public int size() { return numberItems; } public void enqueue(Item item) { if (item == null) { throw new IllegalArgumentException(); } push(item); } public Item dequeue() { int location = random.nextInt(numberItems); return pop(location); } public Item sample() { if (numberItems == 0) { throw new NoSuchElementException(); } int location = random.nextInt(numberItems); return itemArray[location]; } private void shuffle() { for (int i = 0; i < numberItems; i++) { int intA = random.nextInt(numberItems); int intB = random.nextInt(numberItems); if (intA != intB) { Item temp = itemArray[intA]; itemArray[intA] = itemArray[intB]; itemArray[intB] = temp; } } } public Iterator<Item> iterator() { shuffle(); return new ListIterator(); } private class ListIterator implements Iterator<Item> { private int current = 0; public boolean hasNext() { return itemArray[current] != null; } public void remove() { throw new UnsupportedOperationException(); } public Item next() { if (!hasNext()) { throw new NoSuchElementException(); } Item item = itemArray[current]; current++; return item; } } private void push(Item item) { if (numberItems == itemArray.length) { resize(2 * itemArray.length); } itemArray[numberItems] = item; numberItems++; } private void resize(int capacity) { Item[] newArray = (Item[]) new Object[capacity]; for (int i = 0; i < numberItems; i++) { newArray[i] = itemArray[i]; } itemArray = newArray; } private Item pop(int location) { Item item = itemArray[location]; if (numberItems > 0 && numberItems == itemArray.length/4) { resize(itemArray.length/2); } if (location == numberItems-1) { itemArray[location] = null; } else { itemArray[location] = itemArray[numberItems-1]; itemArray[numberItems-1] = null; } numberItems--; return item; } public static void main(String[] args) { // For testing } }
true
0e23d2b02418a46be8af47e54d4ce57673217b7f
Java
Andrefgr/SkydiverAttack
/src/core/src/com/mygdx/game/HelpScreen.java
UTF-8
3,351
2.265625
2
[]
no_license
package com.mygdx.game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.InputListener; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.utils.Align; import com.badlogic.gdx.utils.viewport.ExtendViewport; import com.badlogic.gdx.utils.viewport.FillViewport; import com.badlogic.gdx.utils.viewport.StretchViewport; import com.badlogic.gdx.utils.viewport.Viewport; public class HelpScreen implements Screen { Viewport viewport; private OrthographicCamera cam; Stage stage; Label label; Texture buttonMenu; MyActor actorButtonMenu; MyGame myGame; float auxX, auxY; Texture background; SpriteBatch batch; public HelpScreen(MyGame myGame) { this.myGame = myGame; batch = new SpriteBatch(); viewport = new ExtendViewport(myGame.getScreenWidth(), myGame.getScreenHeight()); stage = new Stage(viewport); Gdx.input.setInputProcessor(stage); background = new Texture("helpscreen.png"); buttonMenu = new Texture("ButtonMenu.png"); actorButtonMenu = new MyActor(buttonMenu, "buttonMenu"); actorButtonMenu.setSize(350,200); } @Override public void show() { actorButtonMenu.addListener(new InputListener() { @Override public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) { Sprite sprite = new Sprite(new Texture("ButtonMenu2.png")); sprite.setPosition(actorButtonMenu.getX(), actorButtonMenu.getY()); sprite.setSize(350,200); actorButtonMenu.sprite = sprite; return true; } @Override public void touchUp(InputEvent event, float x, float y, int pointer, int button) { // myGame.setScreen(new GameScreen(myGame, level)); // myGame.setScreen(new LoadingScreen(myGame, numOfLevel)); AssetLoader.gameOverSound.pause(); dispose(); myGame.setScreen(new MainMenu(myGame)); } }); auxX = myGame.getScreenWidth() / 2 - actorButtonMenu.sprite.getWidth() / 2; actorButtonMenu.spritePos(auxX, 0); stage.addActor(actorButtonMenu); } @Override public void render(float delta) { Gdx.gl.glClearColor(0, 0, 0, 0); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); stage.act(Gdx.graphics.getDeltaTime()); stage.getBatch().begin(); stage.getBatch().draw(background, 0, 0, myGame.getScreenWidth(), myGame.getScreenHeight()); stage.getBatch().end(); stage.draw(); } @Override public void resize(int width, int height) { stage.getViewport().update(width, height); } @Override public void pause() { } @Override public void resume() { } @Override public void hide() { } @Override public void dispose() { } }
true
fa35befd0b295a935f44c5deb6afc9e3750db432
Java
lijie909224307/javaBase
/SocketTestIdea/src/com/inet/PortUsedCheck.java
UTF-8
793
3.1875
3
[]
no_license
package com.inet; import java.io.IOException; import java.net.Socket; /** * @author lijie * @version 1.00 * @Description: 查询端口占用情况, 实质就是挨个连接,哪个端口打开了就会连接上. * http://www.manongjc.com/java_example/net_port.html * @date 2020/3/15 17:58 */ public class PortUsedCheck { public static void main(String[] args) throws IOException { Socket socket = null; String host = "localhost"; for (int i = 0; i < 1000; i++) { try { socket = new Socket(host,i); System.out.println("端口"+i+"已经被占用"); } catch (IOException e) { System.out.println("Exception has occured " + e); continue; } } } }
true
0e8ce4f340837f1b096811a4dc586d68cfb6b0f5
Java
evnurm/LunchList
/src/backend/JSONDecoder.java
UTF-8
513
2.609375
3
[]
no_license
package backend; import java.util.Calendar; import java.util.Date; /** * Serves as a supertype for the decoders used for * different service providers, ie. Amica and Sodexo. * * @author evnurm */ abstract class JSONDecoder{ Calendar cal = Calendar.getInstance(); /** Returns the date object that represents Monday of the current week. */ Date getMonday(){ int today = cal.get(Calendar.DAY_OF_WEEK); cal.roll(Calendar.DAY_OF_WEEK, 2-today); return cal.getTime(); } }
true
337e58defa2ce203d53a35d3e389dff908ad3932
Java
onurmumcu/Cucumber-TestNG-Automation
/src/test/java/com/app/tests/Log4jDemo.java
UTF-8
382
2.171875
2
[]
no_license
package com.app.tests; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class Log4jDemo { public static final Logger logger=LogManager.getLogger(); public static void main(String[] args) { logger.info("this is info log step"); logger.warn("a warning"); logger.debug("debug"); logger.error("error logging"); } }
true
19acdc243869030600774d9af4ff99651b0e32bb
Java
cuixuyang/MicroCommunity
/service-front/src/main/java/com/java110/front/smo/wxLogin/impl/WxLoginSMOImpl.java
UTF-8
7,749
1.976563
2
[ "Apache-2.0" ]
permissive
package com.java110.front.smo.wxLogin.impl; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.java110.front.properties.WechatAuthProperties; import com.java110.front.smo.AppAbstractComponentSMO; import com.java110.front.smo.wxLogin.IWxLoginSMO; import com.java110.core.context.IPageData; import com.java110.core.factory.AuthenticationFactory; import com.java110.utils.cache.MappingCache; import com.java110.utils.constant.*; import com.java110.utils.exception.SMOException; import com.java110.utils.util.Assert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import java.util.HashMap; import java.util.Map; /** * wx登录 */ @Service("wxLoginSMOImpl") public class WxLoginSMOImpl extends AppAbstractComponentSMO implements IWxLoginSMO { private final static Logger logger = LoggerFactory.getLogger(WxLoginSMOImpl.class); @Autowired private RestTemplate outRestTemplate; @Autowired private RestTemplate restTemplate; @Autowired private WechatAuthProperties wechatAuthProperties; @Override public ResponseEntity<String> doLogin(IPageData pd) throws SMOException { return businessProcess(pd); } @Override protected void validate(IPageData pd, JSONObject paramIn) { //super.validatePageInfo(pd); Assert.hasKeyAndValue(paramIn, "code", "请求报文中未包含code信息"); //super.checkUserHasPrivilege(pd, restTemplate, PrivilegeCodeConstant.LIST_ORG); } @Override protected ResponseEntity<String> doBusinessProcess(IPageData pd, JSONObject paramIn) { logger.debug("doLogin入参:" + paramIn.toJSONString()); ResponseEntity<String> responseEntity; String code = paramIn.getString("code"); String urlString = "?appid={appId}&secret={secret}&js_code={code}&grant_type={grantType}"; String response = outRestTemplate.getForObject( wechatAuthProperties.getSessionHost() + urlString, String.class, wechatAuthProperties.getAppId(), wechatAuthProperties.getSecret(), code, wechatAuthProperties.getGrantType()); logger.debug("wechatAuthProperties:" + JSONObject.toJSONString(wechatAuthProperties)); logger.debug("微信返回报文:" + response); //Assert.jsonObjectHaveKey(response, "errcode", "返回报文中未包含 错误编码,接口出错"); JSONObject responseObj = JSONObject.parseObject(response); if (responseObj.containsKey("errcode") && !"0".equals(responseObj.getString("errcode"))) { throw new IllegalArgumentException("微信验证失败,可能是code失效" + responseObj); } String openId = responseObj.getString("openid"); String sessionKey = responseObj.getString("session_key"); responseEntity = super.getUserInfoByOpenId(pd, restTemplate, openId); logger.debug("查询用户信息返回报文:" + responseEntity); if (responseEntity.getStatusCode() != HttpStatus.OK) { throw new IllegalArgumentException("根绝openId 查询用户信息异常" + openId + ", " + responseEntity.getBody()); } JSONObject userResult = JSONObject.parseObject(responseEntity.getBody()); int total = userResult.getIntValue("total"); JSONObject paramOut = new JSONObject(); JSONObject userInfo = paramIn.getJSONObject("userInfo"); if (total == 0) { //保存用户信息 /*JSONObject registerInfo = new JSONObject(); //设置默认密码 String userDefaultPassword = MappingCache.getValue(MappingConstant.KEY_STAFF_DEFAULT_PASSWORD); Assert.hasLength(userDefaultPassword, "映射表中未设置员工默认密码,请检查" + MappingConstant.KEY_STAFF_DEFAULT_PASSWORD); userDefaultPassword = AuthenticationFactory.passwdMd5(userDefaultPassword); registerInfo.put("userId", "-1"); registerInfo.put("email", ""); registerInfo.put("address", userInfo.getString("country") + userInfo.getString("province") + userInfo.getString("city")); registerInfo.put("locationCd", "001"); registerInfo.put("age", "1"); registerInfo.put("sex", "2".equals(userInfo.getString("gender")) ? "1" : "0"); registerInfo.put("tel", "-1"); registerInfo.put("level_cd", "1"); registerInfo.put("name", userInfo.getString("nickName")); registerInfo.put("password", userDefaultPassword); JSONArray userAttr = new JSONArray(); JSONObject userAttrObj = new JSONObject(); userAttrObj.put("attrId", "-1"); userAttrObj.put("specCd", "100201911001"); userAttrObj.put("value", openId); userAttr.add(userAttrObj); registerInfo.put("businessUserAttr", userAttr); responseEntity = this.callCenterService(restTemplate, pd, registerInfo.toJSONString(), ServiceConstant.SERVICE_API_URL + "/api/user.service.register", HttpMethod.POST); if (responseEntity.getStatusCode() != HttpStatus.OK) { throw new IllegalArgumentException("保存用户信息失败"); } responseEntity = super.getUserInfoByOpenId(pd, restTemplate, openId); logger.debug("查询用户信息返回报文:" + responseEntity); if (responseEntity.getStatusCode() != HttpStatus.OK) { throw new IllegalArgumentException("根绝openId 查询用户信息异常" + openId); } userResult = JSONObject.parseObject(responseEntity.getBody());*/ paramOut.put("openId", openId); paramOut.put("msg", "还没有注册请先注册"); responseEntity = new ResponseEntity<String>(paramOut.toJSONString(), HttpStatus.UNAUTHORIZED); return responseEntity; } JSONObject realUserInfo = userResult.getJSONArray("users").getJSONObject(0); userInfo.putAll(realUserInfo); userInfo.put("password", ""); try { Map userMap = new HashMap(); userMap.put(CommonConstant.LOGIN_USER_ID, userInfo.getString("userId")); userMap.put(CommonConstant.LOGIN_USER_NAME, userInfo.getString("name")); String token = AuthenticationFactory.createAndSaveToken(userMap); paramOut.put("result", 0); paramOut.put("userInfo", userInfo); paramOut.put("token", token); paramOut.put("sessionKey", sessionKey); pd.setToken(token); responseEntity = new ResponseEntity<String>(paramOut.toJSONString(), HttpStatus.OK); } catch (Exception e) { logger.error("登录异常:", e); throw new IllegalArgumentException("鉴权失败"); } //根据openId 查询用户信息,是否存在用户 return responseEntity; } public RestTemplate getRestTemplate() { return restTemplate; } public void setRestTemplate(RestTemplate restTemplate) { this.restTemplate = restTemplate; } public WechatAuthProperties getWechatAuthProperties() { return wechatAuthProperties; } public void setWechatAuthProperties(WechatAuthProperties wechatAuthProperties) { this.wechatAuthProperties = wechatAuthProperties; } }
true
61a23277c7ea3ee4d2c8530e0d8349fc838b34d8
Java
clanout/android-app-old-v2
/app/src/main/java/reaper/android/app/api/notification/NotificationApi.java
UTF-8
387
1.8125
2
[]
no_license
package reaper.android.app.api.notification; import reaper.android.app.api.notification.request.GCmRegisterUserApiRequest; import retrofit.client.Response; import retrofit.http.Body; import retrofit.http.POST; import rx.Observable; public interface NotificationApi { @POST("/notification/register") Observable<Response> registerUser(@Body GCmRegisterUserApiRequest request); }
true
9ebb4b5016027c4c96c753d16fd3dca07a1be67c
Java
BestOfTheBeast/SEP
/src/main/java/student/enterprise/project/entity/LessonEntity.java
UTF-8
1,007
2.46875
2
[]
no_license
package student.enterprise.project.entity; import java.time.LocalTime; import javax.persistence.Column; import javax.persistence.Convert; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import student.enterprise.project.converter.jpa.LocalDateAttributeConverter; /* Enum entity that defines lesson order number and it's time */ @Data @Builder @NoArgsConstructor @AllArgsConstructor @Entity @Table(name = "lessons") public class LessonEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; //Lesson time of day @Convert(converter = LocalDateAttributeConverter.class) @Column(name = "time", columnDefinition = "TIME") private LocalTime time; //Lesson order number @Column(name = "number") private Integer number; }
true
8d90ea8eb9f039e320642945bf14fb92ee727578
Java
luisfelipesv/Tetris
/Tetris/src/tetris/SidePanel.java
UTF-8
8,623
3.203125
3
[]
no_license
package tetris; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import javax.swing.JPanel; /** * SidePanel Class * * @authors Brendan Jones, arrangements by: luisfelipesv y melytc * * Luis Felipe Salazar A00817158 Melissa Janet Treviño A00816715 * * 1/MAR/16 * @version 2.0 * * The {@code SidePanel} class is responsible for displaying various information * on the game such as the next piece, the score and current level, and * controls. * */ public class SidePanel extends JPanel { //Serial Version UID. private static final long lSerialVersionUID = 2181495598854992747L; // The dimensions of each tile on the next piece preview. private static final int iTileSize = BoardPanel.iTileSize >> 1; // The width of the shading on each tile on the next piece preview. private static final int iShadeWidth = BoardPanel.iShadeWidth >> 1; // The number of rows and columns in the preview window. // Set to 5 because we can show any piece with some sort of padding. private static final int iTiles = 5; // The center x of the next piece preview box. private static final int iSquareCenterX = 130; // The center y of the next piece preview box. private static final int iSquareCenterY = 65; // The size of the next piece preview box. private static final int iSquareSize = (iTileSize * iTiles >> 1); // The number of pixels used on a small insets. private static final int iSmallInset = 20; // The number of pixels used on a large insets. private static final int iLargeInset = 40; // The y coordinate of the stats category. private static final int iStatsInset = 125; // The y coordinate of the controls category. private static final int iControlsInset = 220; // The number of pixels to offset between each string. private static final int iTextStride = 25; // The small font. private static final Font fSmallFont = new Font("Tahoma", Font.BOLD, 11); // The large font. private static final Font fLargeFont = new Font("Tahoma", Font.BOLD, 13); // The color to draw the text and preview box in. private static final Color cDrawColor = new Color(128, 192, 128); // The Tetris instance. private Tetris tetris; /** * SidePanel * * Creates a new SidePanel and sets it's display properties. * * @param tetris The Tetris instance to use. */ public SidePanel(Tetris tetris) { this.tetris = tetris; setPreferredSize(new Dimension(200, BoardPanel.iPanelHeight)); setBackground(new Color(245, 245, 245)); } @Override public void paintComponent(Graphics graGraphic) { super.paintComponent(graGraphic); //Set the color for drawing. graGraphic.setColor(cDrawColor); //This variable stores the current y coordinate of the string. // This way we can re-order, add, or remove new strings if necessary // without needing to change the other strings. int iOffset; // Draw the "Stats" category. graGraphic.setFont(fLargeFont); graGraphic.drawString("Stats", iSmallInset, iOffset = iStatsInset); graGraphic.setFont(fSmallFont); graGraphic.drawString("Level: " + tetris.getLevel(), iLargeInset, iOffset += iTextStride); graGraphic.drawString("Score: " + tetris.getScore(), iLargeInset, iOffset += iTextStride); drawControls(graGraphic, iOffset); // Draw the "Controls" category. graGraphic.setFont(fSmallFont); // Draw music theme playing. graGraphic.drawString("Music: " + tetris.getMusic(), iLargeInset * 2, 15); // Draw the next piece preview box. graGraphic.setFont(fLargeFont); graGraphic.drawString("Next Piece", iSmallInset, 70); graGraphic.drawRect(iSquareCenterX - iSquareSize, iSquareCenterY - iSquareSize, iSquareSize * 2, iSquareSize * 2); drawPreview(graGraphic); } /** * drawControls * * Method that draws the controls instructions in the SidePanel. * * @param graGraphic is the <code>Graphic</code> of the game. * @param iOffset is the <code>integer</code> value with the offset. */ public void drawControls(Graphics graGraphic, int iOffset) { graGraphic.setFont(fLargeFont); graGraphic.drawString("Controls", iSmallInset, iOffset = iControlsInset); graGraphic.setFont(fSmallFont); graGraphic.drawString("← Move Left", iLargeInset, iOffset += iTextStride); graGraphic.drawString("→ Move Right", iLargeInset, iOffset += iTextStride); graGraphic.drawString("↑ Rotate Clockwise", iLargeInset, iOffset += iTextStride); graGraphic.drawString("X Rotate Clockwise", iLargeInset, iOffset += iTextStride); graGraphic.drawString("Z Rotate Anticlockwise", iLargeInset, iOffset += iTextStride); graGraphic.drawString("— Total Drop (Space Bar)", iLargeInset, iOffset += iTextStride); graGraphic.drawString("P Pause Game", iLargeInset, iOffset += iTextStride); graGraphic.drawString("S Save Game", iLargeInset, iOffset += iTextStride); graGraphic.drawString("L Load Game", iLargeInset, iOffset += iTextStride); graGraphic.drawString("0 Mute (Zero)", iLargeInset, iOffset += iTextStride); } /** * drawPreview * * Method that draws preview tile in the SidePanel. * Draw a preview of the next piece that will be spawned. The code is * pretty much identical to the drawing code on the board, just smaller * and centered, rather than constrained to a grid. * * @param graGraphic is the <code>Graphic</code> of the game. */ public void drawPreview(Graphics graGraphic) { TileType type = tetris.getNextPieceType(); if (!tetris.isGameOver() && type != null) { //Get the size properties of the current piece. int cols = type.getCols(); int rows = type.getRows(); int dimension = type.getDimension(); // Calculate the top left corner (origin) of the piece. int startX = (iSquareCenterX - (cols * iTileSize / 2)); int startY = (iSquareCenterY - (rows * iTileSize / 2)); // Get the insets for the preview. The default // rotation is used for the preview, so we just use 0. int top = type.getTopInset(0); int left = type.getLeftInset(0); //Loop through the piece and draw it's tiles onto the preview. for (int row = 0; row < dimension; row++) { for (int col = 0; col < dimension; col++) { if (type.isTile(col, row, 0)) { drawTile(type, startX + ((col - left) * iTileSize), startY + ((row - top) * iTileSize), graGraphic); } } } } } /** * Draws a tile onto the preview window. * * @param ttType is the <code>TileType</code> of the piece to draw. * @param iX is the <code>integer</code> with the column. * @param iY is the <code>integer</code> with the row. * @param graGraphic is the <code>Graphic</code> of the game. */ private void drawTile(TileType ttType, int iX, int iY, Graphics graGraphic) { // Fill the entire tile with the light color. graGraphic.setColor(ttType.getLightColor()); graGraphic.fillRect(iX, iY, iTileSize, iTileSize); graGraphic.fillRect(iX, iY, iTileSize, iTileSize); // Fill the bottom and right edges of the tile with the dark shading color. graGraphic.setColor(ttType.getBaseColor()); int xPoints[] = {iX, iX, iX + (iTileSize / 2)}; int yPoints[] = {iY + iTileSize, iY, iY + (iTileSize / 2)}; int xPoints2[] = {iX + (iTileSize / 2), iX + iTileSize, iX + iTileSize}; int yPoints2[] = {iY + (iTileSize / 2), iY + iTileSize, iY}; graGraphic.fillPolygon(xPoints, yPoints, 3); graGraphic.fillPolygon(xPoints2, yPoints2, 3); graGraphic.setColor(ttType.getDarkColor()); int xPoints3[] = {iX, iX + iTileSize, iX + (iTileSize / 2)}; int yPoints3[] = {iY + iTileSize, iY + iTileSize, iY + (iTileSize / 2)}; graGraphic.fillPolygon(xPoints3, yPoints3, 3); } }
true
52cc3ba8cce328910a5850497332b9ae9a944c8a
Java
sanjeevkrai1/Java8Feature
/LambdaExpressionDemo/src/com/test/lambda/demo1/ClientDemo1.java
UTF-8
212
2.359375
2
[]
no_license
package com.test.lambda.demo1; public class ClientDemo1 { public static void main(String args[]) { MyInterface myInterface = (x , y) -> x>y; System.out.println(myInterface.test(10 , 15)); } }
true
5590ec6a21d0bc12d393cc8acc15b854cd474928
Java
sachinmorejava123/online_food_order
/src/com/nacre/ofo/services/PaymentServiceI.java
UTF-8
198
1.84375
2
[]
no_license
package com.nacre.ofo.services; import java.sql.SQLException; import com.nacre.ofo.dto.OrderDto; public interface PaymentServiceI { public int paymentService(OrderDto dto) throws SQLException; }
true
3bee0ed39059019c233dd344499ceb5c2c2d73e2
Java
dedel009/Java_Project
/Java_Project/src/project1207/Calculator_ex1.java
UTF-8
1,815
4.375
4
[]
no_license
package project1207; import java.util.*; public class Calculator_ex1 { public static void main(String[] args) { /* 연산자를 숫자로 입력받기*/ // boolean operation = true; // Scanner sc = new Scanner(System.in); // // System.out.println("연산자를 입력하시오. [1]+ [2] - [3] * [4] / "); // int operator = sc.nextInt(); // System.out.println("숫자 두개를 입력하시오."); // int num1 = sc.nextInt(), num2 = sc.nextInt(); // int sum =0; // // oper:while(operation) { // switch(operator) { // case 1: // sum = num1 + num2; // System.out.println("두 수의 합은: "+sum); // break oper; // case 2: // sum = num1 - num2; // System.out.println("두 수의 뺄셈은 "+sum); // break oper; // case 3: // sum = num1 * num2; // System.out.println("두 수의 곱은:"+sum); // break oper; // case 4: // sum = num1 / num2; // System.out.println("두 수의 나눗셈은:"+sum); // break oper; // } // // } /*연산자를 문자로 입력받기*/ boolean operation = true; Scanner sc = new Scanner(System.in); System.out.println("연산자를 입력하시오. +, -, *, / "); String operator = sc.next(); System.out.println("숫자 두개를 입력하시오."); int num1 = sc.nextInt(), num2 = sc.nextInt(); int sum =0; oper:while(operation) { switch(operator) { case "+": sum = num1 + num2; System.out.println("두 수의 합은: "+sum); break oper; case "-": sum = num1 - num2; System.out.println("두 수의 뺄셈은 "+sum); break oper; case "*": sum = num1 * num2; System.out.println("두 수의 곱은:"+sum); break oper; case "/": sum = num1 / num2; System.out.println("두 수의 나눗셈은:"+sum); break oper; } } } }
true
66a13e188fa205fbdbff199de646b8440de56da8
Java
codehaus/drools
/drools/drools-ide/src/main/org/drools/ide/debug/DroolsDebugViewEventHandler.java
UTF-8
3,025
2.171875
2
[]
no_license
package org.drools.ide.debug; import org.eclipse.debug.core.DebugEvent; import org.eclipse.debug.core.model.IExpression; import org.eclipse.debug.core.model.ISuspendResume; import org.eclipse.debug.core.model.IVariable; import org.eclipse.debug.internal.ui.views.AbstractDebugEventHandler; import org.eclipse.debug.ui.AbstractDebugView; import org.eclipse.jface.viewers.StructuredSelection; /** * A generic Drools debug view event handler. * * @author <a href="mailto:kris_verlaenen@hotmail.com">kris verlaenen </a> */ public class DroolsDebugViewEventHandler extends AbstractDebugEventHandler { public DroolsDebugViewEventHandler(AbstractDebugView view) { super(view); } protected void doHandleDebugEvents(DebugEvent[] events, Object data) { for (int i = 0; i < events.length; i++) { DebugEvent event = events[i]; switch (event.getKind()) { case DebugEvent.SUSPEND: doHandleSuspendEvent(event); break; case DebugEvent.CHANGE: doHandleChangeEvent(event); break; case DebugEvent.RESUME: doHandleResumeEvent(event); break; } } } protected void updateForDebugEvents(DebugEvent[] events) { for (int i = 0; i < events.length; i++) { DebugEvent event = events[i]; switch (event.getKind()) { case DebugEvent.TERMINATE: doHandleTerminateEvent(event); break; } } } protected void doHandleResumeEvent(DebugEvent event) { if (!event.isStepStart() && !event.isEvaluation()) { getDebugView().psetViewerInput(StructuredSelection.EMPTY); } } protected void doHandleTerminateEvent(DebugEvent event) { getDebugView().pclearExpandedVariables(event.getSource()); } protected void doHandleSuspendEvent(DebugEvent event) { if (event.getDetail() != DebugEvent.EVALUATION_IMPLICIT) { if (event.getSource() instanceof ISuspendResume) { if (!((ISuspendResume)event.getSource()).isSuspended()) { return; } } refresh(); getDebugView().populateDetailPane(); } } protected void doHandleChangeEvent(DebugEvent event) { if (event.getDetail() == DebugEvent.STATE) { if (event.getSource() instanceof IVariable) { refresh(event.getSource()); } } else { if (!(event.getSource() instanceof IExpression)) { refresh(); } } } protected DroolsDebugEventHandlerView getDebugView() { return (DroolsDebugEventHandlerView) getView(); } protected void viewBecomesVisible() { super.viewBecomesVisible(); getDebugView().populateDetailPane(); } }
true
3fea721499d352f53e640612999331644209cc9c
Java
bida2/comices-backend
/src/main/java/com/vuetify/utils/JWTDecoder.java
UTF-8
661
2.5
2
[]
no_license
package com.vuetify.utils; import java.util.Arrays; import com.auth0.jwt.JWT; import com.auth0.jwt.exceptions.JWTDecodeException; import com.auth0.jwt.interfaces.DecodedJWT; public class JWTDecoder { // Possible values for group are -> "admins" and "users" public boolean decodeJwt(String token, String group) { try { DecodedJWT jwt = JWT.decode(token); String[] groups = jwt.getClaim("groups").asArray(String.class); if(Arrays.stream(groups).anyMatch(group::equals)) { return true; } else { return false; } } catch(JWTDecodeException exception) { // Signifies token is invalid or missing return false; } } }
true
797211e19df19f37b2ee4ffd9e5b272efd6b2710
Java
lettuce-io/lettuce-core
/src/main/java/io/lettuce/core/GeoAddArgs.java
UTF-8
3,340
2.5
2
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
/* * Copyright 2011-2022 the original author or authors. * * 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 * * https://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 io.lettuce.core; import static io.lettuce.core.protocol.CommandKeyword.*; import io.lettuce.core.protocol.CommandArgs; /** * Argument list builder for the Redis <a href="https://redis.io/commands/geoadd">GEOADD</a> command starting from Redis 6.2. * Static import the methods from {@link Builder} and call the methods: {@code xx()} or {@code nx()} . * <p> * {@link GeoAddArgs} is a mutable object and instances should be used only once to avoid shared mutable state. * * @author Mark Paluch * @since 6.1 */ public class GeoAddArgs implements CompositeArgument { private boolean nx = false; private boolean xx = false; private boolean ch = false; /** * Builder entry points for {@link ScanArgs}. */ public static class Builder { /** * Utility constructor. */ private Builder() { } /** * Creates new {@link GeoAddArgs} and enabling {@literal NX}. * * @return new {@link GeoAddArgs} with {@literal NX} enabled. * @see GeoAddArgs#nx() */ public static GeoAddArgs nx() { return new GeoAddArgs().nx(); } /** * Creates new {@link GeoAddArgs} and enabling {@literal XX}. * * @return new {@link GeoAddArgs} with {@literal XX} enabled. * @see GeoAddArgs#xx() */ public static GeoAddArgs xx() { return new GeoAddArgs().xx(); } /** * Creates new {@link GeoAddArgs} and enabling {@literal CH}. * * @return new {@link GeoAddArgs} with {@literal CH} enabled. * @see GeoAddArgs#ch() */ public static GeoAddArgs ch() { return new GeoAddArgs().ch(); } } /** * Don't update already existing elements. Always add new elements. * * @return {@code this} {@link GeoAddArgs}. */ public GeoAddArgs nx() { this.nx = true; return this; } /** * Only update elements that already exist. Never add elements. * * @return {@code this} {@link GeoAddArgs}. */ public GeoAddArgs xx() { this.xx = true; return this; } /** * Modify the return value from the number of new elements added, to the total number of elements changed. * * @return {@code this} {@link GeoAddArgs}. */ public GeoAddArgs ch() { this.ch = true; return this; } public <K, V> void build(CommandArgs<K, V> args) { if (nx) { args.add(NX); } if (xx) { args.add(XX); } if (ch) { args.add(CH); } } }
true
570909994dda3dce2b35bc9278ededf961452f59
Java
Zi-nat/public
/bugOptional2.java
UTF-8
461
2.5
2
[]
no_license
package javaSamples.bug_Optional; public class bugOptional2 { public static final bugOptional2 EMPTY_bugOptional2 = new bugOptional2("",""); private final String l; private final String c; public bugOptional2(String l, String c) { this.l = l; this.c = c; } public String l(){ return l; } public String c(){ return c; } public String toString() { return "bugOptional2{" + "l=" + l+ ", c=" + c + "}"; } }
true
523b336c9a9493129b19928f199a640f4c2e77d4
Java
zzctt/Class
/StuInfoManage/src/com/courseDao/CourseDao.java
UTF-8
201
1.703125
2
[]
no_license
package com.courseDao; import java.util.List; import com.PO.Course; public interface CourseDao { void saveOrUpdateCo(Course co); List<Course> findCo(String hql); void deleteCo(Course co); }
true
f68cd86aadd07383cb12957acc1d370e4c0c80ee
Java
jiji87432/TDATC
/tdatcAndroid/AmWell/app/src/main/java/com/skoruz/amwell/patient/MyProviderFragment.java
UTF-8
18,404
1.585938
2
[]
no_license
package com.skoruz.amwell.patient; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Parcelable; import android.support.annotation.Nullable; import android.support.v4.app.FragmentActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.afollestad.materialdialogs.DialogAction; import com.afollestad.materialdialogs.MaterialDialog; import com.android.volley.DefaultRetryPolicy; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyLog; import com.android.volley.error.AuthFailureError; import com.android.volley.error.VolleyError; import com.android.volley.request.JsonArrayRequest; import com.android.volley.request.JsonObjectRequest; import com.google.gson.Gson; import com.skoruz.amwell.R; import com.skoruz.amwell.common.ActionBarListFragment; import com.skoruz.amwell.constants.BaseURL; import com.skoruz.amwell.physicianEntity.Clinic; import com.skoruz.amwell.physicianEntity.PhysicianDetails; import com.skoruz.amwell.utils.AppController; import com.skoruz.amwell.utils.Utils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MyProviderFragment extends ActionBarListFragment implements AbsListView.OnScrollListener{ private static final String TAG = UploadValue.class.getSimpleName(); private ListView recentProvider_list; private PhysicianListAdapter adapter; private ArrayList<PhysicianDetails> allPhysicianDetailsList; private Gson gson=new Gson(); private View.OnClickListener onClickListener; private SharedPreferences sharedPreferences; private int patientId; private ProgressDialog pDialog; private String doctorSpecialization; public MyProviderFragment(){ onClickListener=new View.OnClickListener() { @Override public void onClick(View v) { int n=MyProviderFragment.this.getListView().getPositionForView(v); if (n==-1 || MyProviderFragment.this.adapter==null) return; { final PhysicianDetails physicianDetails=MyProviderFragment.this.getDoctorBundle(n).getParcelable("bundle_doctor"); switch (v.getId()){ case R.id.book_appointment: Toast.makeText(MyProviderFragment.this.getActionBarActivity(),"Appointment Button",Toast.LENGTH_SHORT).show(); break; case R.id.doctor_layout: Toast.makeText(MyProviderFragment.this.getActionBarActivity(),"Layout",Toast.LENGTH_SHORT).show(); break; case R.id.add_preference: Toast.makeText(MyProviderFragment.this.getActionBarActivity(), "Preference Button", Toast.LENGTH_SHORT).show(); new MaterialDialog.Builder(MyProviderFragment.this.getActionBarActivity()) .title(R.string.preferred_doctor) .content(R.string.preferred_doctor_msg) .positiveText(R.string.string_ok) .negativeText(R.string.string_cancel) .onPositive(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(MaterialDialog materialDialog, DialogAction dialogAction) { Toast.makeText(MyProviderFragment.this.getActionBarActivity(), "Positive Button", Toast.LENGTH_SHORT).show(); addToPreferredList(BaseURL.addPreferredDoctor,physicianDetails.getPhysician_id()); } }) .onNegative(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(MaterialDialog materialDialog, DialogAction dialogAction) { Toast.makeText(MyProviderFragment.this.getActionBarActivity(), "Negative Button", Toast.LENGTH_SHORT).show(); } }) .show(); default: break; } } } }; } private void addToPreferredList(String url,int physicianId){ JsonObjectRequest addPatientPhysician=new JsonObjectRequest(Request.Method.POST, url +patientId + "/" + physicianId,null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { if (response.getString("status").equalsIgnoreCase("success")){ getPhysicianList(BaseURL.getAllPhysicians,patientId); }else if (response.getString("status").equalsIgnoreCase("failure")){ Toast.makeText(MyProviderFragment.this.getActionBarActivity(), "Some", Toast.LENGTH_SHORT).show(); } }catch (JSONException e){ e.printStackTrace(); }catch (Exception e){ e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); } }){ /** * Passing some request headers * */ @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<>(); headers.put("Content-Type", "application/json"); return headers; } }; addPatientPhysician.setRetryPolicy(new DefaultRetryPolicy(5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); AppController.getInstance().addToRequestQueue(addPatientPhysician,TAG); } private Bundle getDoctorBundle(int n) { FragmentActivity fragmentActivity; PhysicianDetails cursor = (PhysicianDetails) this.getListView().getAdapter().getItem(n); PhysicianDetails doctor = new PhysicianDetails(); doctor.setPhysician_id(cursor.getPhysician_id()); doctor.setUser(cursor.getUser()); doctor.setSpecializations(cursor.getSpecializations()); doctor.setClinic(cursor.getClinic()); doctor.setLocation(cursor.getLocation()); Bundle bundle = new Bundle(); bundle.putParcelable("bundle_doctor", (Parcelable)doctor); //bundle.putParcelable("bundle_clinic",cursor.getClinic().get(n)); /*String string3 = cursor.getString(cursor.getColumnIndex("practice_city")); if (Utils.isEmptyString(string3)) { string3 = this.mSharedPreferences.getString("selected_city_name", "bangalore"); } if (Utils.isActivityAlive((Activity)(fragmentActivity = this.getActivity()))) { bundle.putString("bundle_currency", new GeoLocation((Context)fragmentActivity).getCurrencyForCity(string3)); }*/ return bundle; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (Utils.isActivityAlive(this.getActivity())) { this.getListView().setOnScrollListener((AbsListView.OnScrollListener)this); this.adapter=new PhysicianListAdapter(this.getActivity(),allPhysicianDetailsList); this.setListAdapter(this.adapter); } } public static MyProviderFragment newInstance(Bundle paramBundle) { MyProviderFragment myProviderFragment = new MyProviderFragment(); myProviderFragment.setArguments(paramBundle); return myProviderFragment; } public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments()!=null){ doctorSpecialization=getArguments().getString("specialization"); } } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view= inflater.inflate(R.layout.fragment_my_provider,container,false); sharedPreferences=getActivity().getSharedPreferences(getString(R.string.amWellPreference), Context.MODE_PRIVATE); patientId=sharedPreferences.getInt("user_id", 0); //recentProvider_list= (ListView) view.findViewById(R.id.allProvider); allPhysicianDetailsList=new ArrayList<PhysicianDetails>(); //getPhysicianList(BaseURL.getAllPhysicians,patientId); getPhysicianBySpecialization(BaseURL.getPhysicianBySpeciality,patientId,doctorSpecialization); //physicianDetailsList=new ArrayList<PhysicianDetails>(); //adapter=new PhysicianListAdapter(getActivity(),allPhysicianDetailsList); //recentProvider_list.setAdapter(adapter); return view; } public void getPhysicianBySpecialization(String url,int patientId,String speciality){ pDialog = new ProgressDialog(MyProviderFragment.this.getActionBarActivity()); pDialog.setMessage("Loading..."); pDialog.setCanceledOnTouchOutside(false); pDialog.show(); allPhysicianDetailsList.clear(); JsonArrayRequest getAllPhysicians=new JsonArrayRequest(url+patientId+"/"+speciality, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray jsonArray) { if (jsonArray.length() > 0){ for (int i = 0; i < jsonArray.length(); i++) { try { JSONObject jsonObject = jsonArray.getJSONObject(i); PhysicianDetails physicianDetails = gson.fromJson(jsonObject.toString(), PhysicianDetails.class); allPhysicianDetailsList.add(physicianDetails); pDialog.dismiss(); } catch (Exception e) { e.printStackTrace(); } } adapter.notifyDataSetChanged(); } pDialog.dismiss(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { pDialog.dismiss(); VolleyLog.d(TAG, "Error: " + volleyError.getMessage()); } }); getAllPhysicians.setRetryPolicy(new DefaultRetryPolicy(5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); AppController.getInstance().addToRequestQueue(getAllPhysicians, TAG); } public void getPhysicianList(String url,int patientId){ pDialog = new ProgressDialog(MyProviderFragment.this.getActionBarActivity()); pDialog.setMessage("Loading..."); pDialog.setCanceledOnTouchOutside(false); pDialog.show(); allPhysicianDetailsList.clear(); JsonArrayRequest getAllPhysicians=new JsonArrayRequest(url+patientId, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray jsonArray) { for (int i=0;i<jsonArray.length();i++){ try { JSONObject jsonObject=jsonArray.getJSONObject(i); PhysicianDetails physicianDetails=gson.fromJson(jsonObject.toString(), PhysicianDetails.class); allPhysicianDetailsList.add(physicianDetails); pDialog.dismiss(); }catch (Exception e){ e.printStackTrace(); } } adapter.notifyDataSetChanged(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { pDialog.dismiss(); VolleyLog.d(TAG, "Error: " + volleyError.getMessage()); } }); getAllPhysicians.setRetryPolicy(new DefaultRetryPolicy(5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); AppController.getInstance().addToRequestQueue(getAllPhysicians, TAG); } @Override public void onStop() { super.onStop(); AppController.getInstance().cancelPendingRequests(TAG); } @Override public void onResume() { super.onResume(); } @Override public void onStart() { super.onStart(); } @Override public void onPause() { super.onPause(); } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { } public class PhysicianListAdapter extends BaseAdapter{ private Activity activity; private LayoutInflater inflater; ArrayList<PhysicianDetails> physicianDetailsList; public PhysicianListAdapter(Activity activity,ArrayList<PhysicianDetails> physicianDetailsList){ this.physicianDetailsList=physicianDetailsList; this.activity=activity; } @Override public int getCount() { return physicianDetailsList.size(); } @Override public Object getItem(int position) { return physicianDetailsList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; if (convertView==null){ inflater= (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView=inflater.inflate(R.layout.item_search_result_list,parent,false); viewHolder=new ViewHolder(); viewHolder.doctorLayout= (LinearLayout) convertView.findViewById(R.id.doctor_layout); viewHolder.docName= (TextView) convertView.findViewById(R.id.doctor_name); viewHolder.availability= (TextView) convertView.findViewById(R.id.available_today); viewHolder.doc_spec= (TextView) convertView.findViewById(R.id.doctor_speciality); viewHolder.clinic_name= (TextView) convertView.findViewById(R.id.clinic_name); viewHolder.clinic_locality= (TextView) convertView.findViewById(R.id.clinic_locality); viewHolder.doc_exp= (TextView) convertView.findViewById(R.id.doctor_experience); viewHolder.doc_fees= (TextView) convertView.findViewById(R.id.doctor_fees); viewHolder.book_appoint= (Button) convertView.findViewById(R.id.book_appointment); viewHolder.add_prefer= (Button) convertView.findViewById(R.id.add_preference); viewHolder.doctorLayout.setOnClickListener(MyProviderFragment.this.onClickListener); viewHolder.book_appoint.setOnClickListener(MyProviderFragment.this.onClickListener); viewHolder.add_prefer.setOnClickListener(MyProviderFragment.this.onClickListener); convertView.setTag(viewHolder); }else{ viewHolder= (ViewHolder) convertView.getTag(); } if(physicianDetailsList.size()>0) { PhysicianDetails physicianDetails = physicianDetailsList.get(position); if (physicianDetails != null) { viewHolder.docName.setText("Dr " + physicianDetails.getUser().getFirstName() + " " + physicianDetails.getUser().getLastName()); if(physicianDetails.getSpecializations()!=null) { viewHolder.doc_spec.setText(physicianDetails.getSpecializations().getSpecializations()); } if(physicianDetails.getClinic().size()>0) { if (physicianDetails.getClinic() != null) { List<Clinic> clinics = new ArrayList<>(physicianDetails.getClinic()); viewHolder.clinic_name.setText(clinics.get(0).getClinicName()); viewHolder.doc_fees.setText(this.activity.getResources().getString(R.string.Rs) + String.valueOf(clinics.get(0).getConsultationFees())); viewHolder.clinic_locality.setText(clinics.get(0).getCity()); } } viewHolder.doc_exp.setText(String.valueOf(physicianDetails.getExperienceInYear()) + " yrs exp."); } } return convertView; } } private static class ViewHolder{ LinearLayout doctorLayout; TextView docName,availability,doc_spec,clinic_name,clinic_locality,doc_exp,doc_fees; Button book_appoint,add_prefer; } }
true
32dd4a4b5b90f5cf8f3579bfdbda93c20a4f8bb7
Java
fwhite95/ugh
/FinalProject/src/finalProject02/DBTest.java
UTF-8
958
3.03125
3
[]
no_license
package finalProject02; import java.io.BufferedReader; import java.io.InputStreamReader; import java.sql.*; public class DBTest { public static void main(String[] args)throws SQLException, ClassNotFoundException { // TODO Auto-generated method stub System.out.println("Driver loaded"); //Connect to a database Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/javabook", "scott", "tiger"); System.out.println("Database connected"); //Create a statement Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery("select address " + "from Facility"); while(rs.next()){ System.out.println(rs.getString(1)); } //close connection connection.close(); System.out.println("Database disconnected"); } }
true
8bcc05721bfed3eea9d13eb3f95e933ef55aa839
Java
407570165/Hello
/src/sample/Practice2.java
UTF-8
699
3.0625
3
[]
no_license
package sample; //02-6 import java.util.Random; import java.util.Scanner; import java.util.StringTokenizer; public class Practice2 { public static void main(String[] args) { Scanner scanner =new Scanner(System.in); int number =scanner.nextInt(); int answer =1; while (number%10!=0){ answer=answer*(number%10); number=number/10; } System.out.println(answer); /* Scanner scanner=new Scanner(System.in); int target =scanner.nextInt(); int answer=1; while (target!=0){ answer =answer*(target%10); target=target/10; } System.out.println(answer);*/ } }
true
b0f4e19f6ac2a01e15902eee1c7f80ffcb9836fd
Java
huangzehai/spring-cloud-example
/src/main/java/cloud/integration/StoreIntegration.java
UTF-8
527
1.789063
2
[ "Apache-2.0" ]
permissive
package cloud.integration; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import org.springframework.stereotype.Component; import java.util.Map; @Component public class StoreIntegration { @HystrixCommand(fallbackMethod = "defaultStores") public Object getStores(Map<String, Object> parameters) { throw new NullPointerException("Error"); // return "store successfully"; } public Object defaultStores(Map<String, Object> parameters) { return "fallback"; } }
true
972b72b53c1627064a5b8003d45ceff95d0c9e43
Java
shaz312/address-components
/src/test/Address.java
UTF-8
1,422
2.515625
3
[]
no_license
package test; public class Address { private String addressString; private String number; private String section; private String street; private String city; private String state; private String postcode; public Address(String addressString) { this.addressString = addressString; } public String getAddressString() { return addressString; } public void setAddressString(String addressString) { this.addressString = addressString; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public String getSection() { return section; } public void setSection(String section) { this.section = section; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getPostCode() { return postcode; } public void setPostCode(String postcode) { this.postcode = postcode; } }
true
ff3f9252567d944171981e5160afe2c77ae2f053
Java
clairtonluz/imex
/src/main/java/negocio/Produto.java
UTF-8
729
2.75
3
[ "MIT" ]
permissive
package negocio; import java.util.Date; public class Produto { private String nome; private double preco; private double desconto; private Date validade; public Date getValidade() { return validade; } public void setValidade(Date validade) { this.validade = validade; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public double getPreco() { return preco; } public void setPreco(double preco) { this.preco = preco; } public double getDesconto() { return desconto; } public void setDesconto(double desconto) { this.desconto = desconto; } public boolean isDescontoValido() { return getDesconto() >= 0 && getDesconto() < 1; } }
true
e0b6b689491a1ebaa7f3b35ab78f523d1fe8e6e6
Java
guxinghuahuo/BankTransferSystem
/src/main/java/com/gxhh/mysql/bank/service/TransferService.java
UTF-8
204
1.648438
2
[]
no_license
package com.gxhh.mysql.bank.service; import org.springframework.stereotype.Service; import java.util.Map; @Service public interface TransferService { void callTransfer(Map<String, Object> map); }
true
964678bbbab3924d60cc03940aee299aac43bbb9
Java
gvpm/inferenceEngine
/src/inferenceengine/Rule.java
UTF-8
4,313
3.484375
3
[]
no_license
package inferenceengine; import java.util.ArrayList; /** * Structure that represents a Rule * Contains a list of If tuples, Add tuples and Delete tuples * @author gvpm */ public class Rule { ArrayList<Tuple> ifTuples; ArrayList<Tuple> addTuples; ArrayList<Tuple> deleteTuples; int ruleNumber; /** * Constructor * @param n number of the rule */ public Rule(int n) { this.ifTuples = new ArrayList<>(); this.addTuples = new ArrayList<>(); this.deleteTuples = new ArrayList<>(); this.ruleNumber=n; } /** * Returns the rule number * @return rule number */ public int getRuleNumber() { return ruleNumber; } /** * Checks if rule is applicable in a given working memory * @param wm working memory to check * @return true= applicable false= not applicable */ public boolean isApplicableOn(WorkingMemory wm){ for (int i = 0; i < getIfTuplesSize(); i++) { if(wm.searchTuple(getIfTuple(i))==-1) return false; } return true; } /** *Check if the rule can provide the goal * @param g tuple * @return true if provides, false if not */ public boolean providesGoal(Tuple g){ for (int i = 0; i < addTuples.size(); i++) { if(this.getAddTuple(i).compareTuple(g)){ return true; } } return false; } /** * Apply the rule to a given working memory * @param wm working memory to apply on */ public void applyOn(WorkingMemory wm){ if(this.isApplicableOn(wm)){ System.out.println(this.toString()); for (int i = 0; i < this.getDeleteTuplesSize(); i++) { int toRemove = wm.searchTuple(this.getDeleteTuple(i)); if(toRemove!=-1){ wm.removeTuple(toRemove); } } for (int i = 0; i < this.getAddTuplesSize(); i++) { if(wm.searchTuple(this.getAddTuple(i))==-1){ wm.addTuple(this.getAddTuple(i)); } } System.out.println("Updated "+wm.toString()+"\n"); }else{ System.out.println("RULE"+ruleNumber+ " Failed"); } } /** * Adds a If tuple * @param t Tuple to add */ public void addIfTuple(Tuple t){ this.ifTuples.add(t); } /** * Adds ADD tuple * @param t Tuple to add */ public void addAddTuple(Tuple t){ this.addTuples.add(t); } /** * Adds Delete tuple * @param t Tuple to add */ public void addDeleteTuple(Tuple t){ this.deleteTuples.add(t); } /** * Returns the size of the IF tuples list * @return size */ public int getIfTuplesSize(){ return this.ifTuples.size(); } /** * Returns the size of the Add tuples list * @return size */ public int getAddTuplesSize(){ return this.addTuples.size(); } /** * Returns the size of the Delete tuples list * @return size */ public int getDeleteTuplesSize(){ return this.deleteTuples.size(); } /** * Returns one if tuple from the list * @param i index of the tuple * @return the tuple */ public Tuple getIfTuple(int i){ return this.ifTuples.get(i); } /** * Returns one Add tuple from the list * @param i index of the tuple * @return the tuple */ public Tuple getAddTuple(int i){ return this.addTuples.get(i); } /** * Returns one Delete tuple from the list * @param i index of the tuple * @return the tuple */ public Tuple getDeleteTuple(int i){ return this.deleteTuples.get(i); } @Override public String toString() { return "RULE"+ruleNumber+": \n"+ "IF: " + ifTuples + "\nTHEN: " + "Add: " + addTuples+ " Delete: " +deleteTuples; } }
true
6a75b55ee89a2ad4c73a83fe69e98ea4b65b402a
Java
mr-spod/repo
/cs2231/JUnitTestingRevisited/src/Homework.java
UTF-8
4,117
4.3125
4
[]
no_license
public class Homework { /** * Evaluates an expression and returns its value. * * @param source * the {@code StringBuilder} that starts with an expr string * @return value of the expression * @updates source * @requires <pre> * [an expr string is a proper prefix of source, and the longest * such, s, concatenated with the character following s, is not a prefix * of any expr string] * </pre> * @ensures <pre> * valueOfExpr = * [value of longest expr string at start of #source] and * #source = [longest expr string at start of #source] * source * </pre> */ public static int valueOfExpr(StringBuilder source) { int answer = valueOfTerm(source); while (source.charAt(0) == '+' || source.charAt(0) == '-') { StringBuilder operator = source.deleteCharAt(0); int nextTerm = valueOfTerm(source); if (operator.charAt(0) == '-') { nextTerm *= -1; } answer += nextTerm; } return answer; } /** * Evaluates a term and returns its value. * * @param source * the {@code StringBuilder} that starts with a term string * @return value of the term * @updates source * @requires <pre> * [a term string is a proper prefix of source, and the longest * such, s, concatenated with the character following s, is not a prefix * of any term string] * </pre> * @ensures <pre> * valueOfTerm = * [value of longest term string at start of #source] and * #source = [longest term string at start of #source] * source * </pre> */ private static int valueOfTerm(StringBuilder source) { int answer = valueOfFactor(source); while (source.charAt(0) == '*' || source.charAt(0) == '/') { StringBuilder operator = source.deleteCharAt(0); int nextFactor = valueOfFactor(source); if (operator.charAt(0) == '*') { answer *= nextFactor; } else { answer /= nextFactor; } } return answer; } /** * Evaluates a factor and returns its value. * * @param source * the {@code StringBuilder} that starts with a factor string * @return value of the factor * @updates source * @requires <pre> * [a factor string is a proper prefix of source, and the longest * such, s, concatenated with the character following s, is not a prefix * of any factor string] * </pre> * @ensures <pre> * valueOfFactor = * [value of longest factor string at start of #source] and * #source = [longest factor string at start of #source] * source * </pre> */ private static int valueOfFactor(StringBuilder source) { int answer; if (source.charAt(0) == '(') { source.deleteCharAt(0); answer = valueOfExpr(source); } else { answer = valueOfDigitSeq(source); } return answer; } /** * Evaluates a digit sequence and returns its value. * * @param source * the {@code StringBuilder} that starts with a digit-seq string * @return value of the digit sequence * @updates source * @requires <pre> * [a digit-seq string is a proper prefix of source, which * contains a character that is not a digit] * </pre> * @ensures <pre> * valueOfDigitSeq = * [value of longest digit-seq string at start of #source] and * #source = [longest digit-seq string at start of #source] * source * </pre> */ private static int valueOfDigitSeq(StringBuilder source) { int answer = valueOfDigit(source); while (Character.isDigit(source.charAt(0))) { answer *= 10; answer += valueOfDigit(source); } return answer; } /** * Evaluates a digit and returns its value. * * @param source * the {@code StringBuilder} that starts with a digit * @return value of the digit * @updates source * @requires 1 < |source| and [the first character of source is a digit] * @ensures <pre> * valueOfDigit = [value of the digit at the start of #source] and * #source = [digit string at start of #source] * source * </pre> */ private static int valueOfDigit(StringBuilder source) { StringBuilder digit = source.deleteCharAt(0); int dig = Character.digit(digit.charAt(0), 10); return dig; } }
true
d64b66bb53160b33c81886518fad0624803799b7
Java
JArmunia/ProcesadoresDeLenguajes
/EntregaFinalPL/CodigoEntrega/ExcepcionTablaSimbolos.java
WINDOWS-1250
1,477
2.953125
3
[]
no_license
import clasesJava.Simbolo; public class ExcepcionTablaSimbolos extends SemanticException { /** * */ private static final long serialVersionUID = 1L; public ExcepcionTablaSimbolos(Token currentToken, int nivel, Simbolo conflicto) { super(inicializar(currentToken, nivel, conflicto)); } public ExcepcionTablaSimbolos(String identificador, int linea, int nivel, Simbolo conflicto) { super(inicializar(identificador, linea, nivel, conflicto)); } private static String inicializar(Token currentToken, int nivel, Simbolo conflicto) { StringBuilder sb = new StringBuilder(); sb.append( "ERROR SEMNTICO: Se ha producido un error al intentar declarar " + currentToken.image + " en el nivel " + nivel + " en la lnea: " + currentToken.beginLine + ", columna: " + currentToken.beginColumn + ".\nPero ya hay un/a " + conflicto.getTipoSimbolo().toString().toLowerCase() + " con ese nombre en el nivel " + conflicto.getNivel()); return sb.toString(); } private static String inicializar(String identificador, int linea, int nivel, Simbolo conflicto) { StringBuilder sb = new StringBuilder(); sb.append("ERROR SEMNTICO: Se ha producido un error al intentar declarar " + identificador + " en el nivel " + nivel + " en la lnea: " + linea + ".\nPero ya hay un/a " + conflicto.getTipoSimbolo().toString().toLowerCase() + " con ese nombre en el nivel " + conflicto.getNivel()); return sb.toString(); } }
true
47a09af0d778525b3f900e1483d15fff9bbeda1b
Java
AntonyBaasan/godzula
/api/src/main/java/com/godzula/web/rest/PublicCourseResource.java
UTF-8
2,928
2.4375
2
[]
no_license
package com.godzula.web.rest; import com.codahale.metrics.annotation.Timed; import com.godzula.service.CourseService; import com.godzula.service.SectionService; import com.godzula.service.TaskService; import com.godzula.service.dto.CourseDTO; import com.godzula.service.dto.FullCourseDTO; import com.godzula.service.dto.SectionDTO; import com.godzula.service.dto.TaskDTO; import io.github.jhipster.web.util.ResponseUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; /** * REST controller for managing Course. */ @RestController @RequestMapping("/api/public") public class PublicCourseResource { private final Logger log = LoggerFactory.getLogger(PublicCourseResource.class); private static final String ENTITY_NAME = "course"; private final CourseService courseService; private final SectionService sectionService; private final TaskService taskService; public PublicCourseResource( CourseService courseService, SectionService sectionService, TaskService taskService ) { this.courseService = courseService; this.sectionService = sectionService; this.taskService = taskService; } @GetMapping("/courses") @Timed public List<CourseDTO> getAllCoursesMetadata() { log.debug("REST request to get all Courses metadata"); return courseService.findAllPublished(); } /** * GET /courses/:id : get the "id" course. * * @param id the id of the courseDTO to retrieve * @return the ResponseEntity with status 200 (OK) and with body the courseDTO, or with status 404 (Not Found) */ @GetMapping("/courses/{id}") @Timed public ResponseEntity<FullCourseDTO> getCourse(@PathVariable String id) { log.debug("REST request to get Course : {}", id); Optional<CourseDTO> courseDTO = courseService.findOne(id); if(courseDTO.isPresent()){ return ResponseEntity.ok(getFullCourse(courseDTO.get())); }else{ return new ResponseEntity(HttpStatus.NOT_FOUND); } } /** * Creates section and task about a course */ private FullCourseDTO getFullCourse(CourseDTO course){ FullCourseDTO fullCourse = new FullCourseDTO(); fullCourse.setCourse(course); List<SectionDTO> sections = sectionService.findByCourseId(course.getId()); fullCourse.setSections(sections); List<String> sectionIds = sections.stream().map(SectionDTO::getId).collect(Collectors.toList()); List<TaskDTO> tasks = taskService.findBySectionIds(sectionIds); fullCourse.setTasks(tasks); return fullCourse; } }
true
3fad2273c1ba340149ef868f1fb3cc39c67ebb91
Java
Dbejan21/Batch10
/src/String/Task1.java
UTF-8
1,389
4.15625
4
[]
no_license
package String; import java.util.Scanner; public class Task1 { public static void main(String[] args) { /* TASK: Ask user to enter a String value which should have space at the beginning or end - Replace all letter 'a's with single '*' and letter 'e's with double '**', - change all string value to UPPERCASE - Find index of First '*' - Multiply that value by 10 and - Print out the result */ Scanner scanner = new Scanner(System.in); System.out.println("please enter a string value may have some space in the beginning or at the end"); String text = scanner.nextLine(); System.out.println(text); text = text.trim(); System.out.println(text); text = text.replace('a', '*'); System.out.println(text); text = text.replace("e", "**"); System.out.println(text); text = text.toUpperCase(); System.out.println(text); int indexOfStar = text.indexOf('*'); System.out.println(indexOfStar); System.out.println(indexOfStar * 10); // find and print out middle char's index number // Chicago text.charAt(4); text.charAt((text.length() - 1) / 2); text.indexOf("a"); int index = text.indexOf(text.charAt((text.length() - 1) / 2)); System.out.println(index); } }
true
d92578ddde17de83e84a14759f8162bd3b102f61
Java
zzz999/code
/src/main/java/com/htsec/service/impl/UserAccountOverviewServiceImpl.java
UTF-8
11,314
2.078125
2
[]
no_license
package com.htsec.service.impl; import com.htsec.commons.utils.CommonKeys; import com.htsec.commons.utils.TimeUtil; import com.htsec.mysql.service.UserDataBaseService; import com.htsec.service.UserAccountOverviewService; import com.htsec.service.dto.*; import net.sf.json.JSONObject; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.math.BigDecimal; import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; /** * Created by bernard on 2017/9/19. */ @Service public class UserAccountOverviewServiceImpl implements UserAccountOverviewService { private static final Logger logger = Logger.getLogger(UserAccountOverviewServiceImpl.class); @Autowired private UserDataBaseService userDataBaseService; @Override public void getOverview(JSONObject input, HttpServletResponse response) { String account=input.getString(CommonKeys.ACCOUNT); String range =input.getString(CommonKeys.RANGE); switch (range){ case "week": getOverviewByWeek( account,response); break; case "month": getOverviewByMonth(account,response); break; case "year": getOverviewByYear(account,response); break; default: logger.error("fail to match range:"+range); } } private void getOverviewByWeek(String account, HttpServletResponse response) { JSONObject weekOverview = new JSONObject(); List<String> week = null; try { week = TimeUtil.getThisWeekBeginEnd(); } catch (ParseException e) { logger.error(e); } List<UserOverview> list = userDataBaseService.getUserOverviewByAccout(Integer.parseInt(account),Integer.parseInt(week.get(0)),Integer.parseInt(week.get(1))); BigDecimal totoalPro =new BigDecimal(1); BigDecimal totalMoney = new BigDecimal(0); for(UserOverview overview:list){ BigDecimal todayPro = overview.getPorfitToday(); totoalPro =(todayPro.add(new BigDecimal(1))).multiply(totoalPro); BigDecimal todayMoney =overview.getProfitMoney(); totalMoney = totalMoney.add(todayMoney); overview.setTotalProfitMoney(totalMoney); overview.setTotalProfit(totoalPro.setScale(5,BigDecimal.ROUND_HALF_UP)); } List<MasterOverview> masterList = userDataBaseService.getMasterOverview(Integer.parseInt(week.get(0)),Integer.parseInt(week.get(1))); BigDecimal masterTotoalPro =new BigDecimal(1); for(MasterOverview masterOverview:masterList){ BigDecimal todayPro = masterOverview.getPorfitToday(); masterTotoalPro =(todayPro.add(new BigDecimal(1)).multiply(masterTotoalPro)); masterOverview.setTotalProfit(masterTotoalPro.setScale(5,BigDecimal.ROUND_HALF_UP)); } weekOverview.put("userOverview",list); weekOverview.put("masterOverview",masterList); //moneychange JSONObject moneyChange = new JSONObject(); moneyChange.put("moneyBegin",1000.10); moneyChange.put("moneyEnd",5000.10); moneyChange.put("moneyInput",1000.00); moneyChange.put("moneyOutput",2000.01); weekOverview.put("moneyChange",moneyChange); try { response.getWriter().write(weekOverview.toString()); } catch (IOException e) { logger.error(e); } } private void getOverviewByMonth(String account, HttpServletResponse response){ List<SwfundAssetmonth> swfundAssetmonthList=userDataBaseService.getSwfundAssetMonthInfo(account,Integer.parseInt(TimeUtil.getMonth()),Integer.parseInt(TimeUtil.getMonth())); if(swfundAssetmonthList==null||swfundAssetmonthList.isEmpty()){ try { response.getWriter().write(new JSONObject().toString()); } catch (IOException e) { e.printStackTrace(); } return; } SwfundAssetmonth monthInfo =swfundAssetmonthList.get(0); String profitRateInfo=monthInfo.getProfitRateByday().trim();//当日收益率 String profitHoderInfo= monthInfo.getHolderRateByday().trim();//当日仓位 String profitInfo =monthInfo.getProfitByday().trim();//当日收益 HashMap<String,OverViewInfo> overViewInfoHashMap = new HashMap<>(); String[] prfitRateInfoList = profitRateInfo.split(","); for(String profitRate:prfitRateInfoList){ String[] datas =profitRate.split(":"); if(overViewInfoHashMap.containsKey(datas[0])){ overViewInfoHashMap.get(datas[0]).setTodayRate(datas[1]); }else { overViewInfoHashMap.put(datas[0],new OverViewInfo()); overViewInfoHashMap.get(datas[0]).setTodayRate(datas[1]); overViewInfoHashMap.get(datas[0]).setTime(datas[0]); } } String[] prfitHoldInfoList = profitHoderInfo.split(","); for(String profitHold:prfitHoldInfoList){ String[] datas =profitHold.split(":"); if(overViewInfoHashMap.containsKey(datas[0])){ overViewInfoHashMap.get(datas[0]).setTodayHold(datas[1]); }else { overViewInfoHashMap.put(datas[0],new OverViewInfo()); overViewInfoHashMap.get(datas[0]).setTodayHold(datas[1]); overViewInfoHashMap.get(datas[0]).setTime(datas[0]); } } String[] profitInfoList = profitInfo.split(","); for(String profit:profitInfoList){ String[] datas =profit.split(":"); if(overViewInfoHashMap.containsKey(datas[0])){ overViewInfoHashMap.get(datas[0]).setTodayProfit(datas[1]); }else { overViewInfoHashMap.put(datas[0],new OverViewInfo()); overViewInfoHashMap.get(datas[0]).setTodayProfit(datas[1]); overViewInfoHashMap.get(datas[0]).setTime(datas[0]); } } ArrayList<OverViewInfo> overViewInfos = new ArrayList<>(); for(String key : overViewInfoHashMap.keySet()){ overViewInfos.add(overViewInfoHashMap.get(key)); } Collections.sort(overViewInfos); float totalrate =1; float totalProfit =0; for(OverViewInfo info: overViewInfos){ totalrate =totalrate*(1+Float.parseFloat(info.getTodayRate())); totalProfit =totalProfit+Float.parseFloat(info.getTodayProfit()); info.setTotalProfit(totalProfit+""); info.setTotalRate((totalrate-1)+""); } AssertChange assertChange = new AssertChange(); assertChange.setAssertIncome(monthInfo.getPeriodInBalance().toString()); assertChange.setAssertOutcome(monthInfo.getPeriodOutBalance().toString()); assertChange.setBeginAssert(monthInfo.getBeginTotalAsset().toString()); assertChange.setEndAssert(monthInfo.getEndTotalAsset().toString()); String factorprofit=monthInfo.getFactorProfit(); String riskExp =monthInfo.getRiskExp(); List<ReasonAnalysis> reasonAnalysisList = new ArrayList<>(); String[] factors =factorprofit.trim().split(","); for(String factor:factors){ String[] dat = factor.split(":"); ReasonAnalysis reasonAnalysis = new ReasonAnalysis(); reasonAnalysis.setKey(dat[0]); reasonAnalysis.setValue(dat[1]); reasonAnalysisList.add(reasonAnalysis); } List<ReasonAnalysis> riskAnalysisList = new ArrayList<>(); String[] risks =riskExp.trim().split(","); for(String risk:risks){ String[] dat = risk.split(":"); ReasonAnalysis riskA = new ReasonAnalysis(); riskA.setKey(dat[0]); riskA.setValue(dat[1]); riskAnalysisList.add(riskA); } OperationAnalysis operationAnalysis =new OperationAnalysis(); operationAnalysis.setStockSelection(monthInfo.getStockSelection().toString()); operationAnalysis.setProfitSecCount(monthInfo.getProfitSecCount()+""); operationAnalysis.setTimeSelection(monthInfo.getMarketTiming().toString()); operationAnalysis.setTradeSuccessRate(monthInfo.getTradeSuccessRate().toString()); operationAnalysis.setTradeTime(monthInfo.getTradingTimes().toString()); List<ShootIndustry> shootIndustries = new ArrayList<>(); String industryProfit = monthInfo.getIndustryProfit().trim(); String [] industrys = industryProfit.split(","); for(String industry:industrys){ String[] data = industry.split(":"); ShootIndustry shootIndustry = new ShootIndustry(); shootIndustry.setName(data[0]); shootIndustry.setRate(data[1]); shootIndustries.add(shootIndustry); } List<InvestStyle> investStyles = new ArrayList<>(); String investStyleInfo = monthInfo.getInvestStyle(); for(String style: investStyleInfo.trim().split(",")){ String[] data = style.split(":"); InvestStyle investStyle = new InvestStyle(); investStyle.setNum(data[0]); investStyle.setStyle(data[1]); investStyles.add(investStyle); } RiskControl riskControl = new RiskControl(); riskControl.setCalmarRatio(monthInfo.getCalmarRatio().toString()); riskControl.setSharpeRatio(monthInfo.getSharpeRatio().toString()); riskControl.setSortinoRatio(monthInfo.getSortinoRatio().toString()); ComprehensivePerformance comprehensivePerformance = new ComprehensivePerformance(); comprehensivePerformance.setAssetAllocation(monthInfo.getAssetAllocation().toString()); comprehensivePerformance.setMarketTiming(monthInfo.getMarketTiming().toString()); comprehensivePerformance.setOperate(monthInfo.getOperate().toString()); comprehensivePerformance.setRiskControl(monthInfo.getRiskControl().toString()); comprehensivePerformance.setStability(monthInfo.getStability().toString()); comprehensivePerformance.setStockSelection(monthInfo.getStockSelection().toString()); JSONObject result = new JSONObject(); result.put("overviewInfos",overViewInfos); result.put("assertchanges",assertChange); result.put("reasonAnalysis",reasonAnalysisList); result.put("riskAnalysis",riskAnalysisList); result.put("operateAnalysis",operationAnalysis); result.put("shootIndustry",shootIndustries); result.put("investStyle",investStyles); result.put("riskControl",riskControl); result.put("comprehensivePerformance",comprehensivePerformance); try { response.getWriter().write(result.toString()); } catch (IOException e) { e.printStackTrace(); } } private void getOverviewByYear(String account, HttpServletResponse response){ } }
true
9ef55c0a13e9c9da007589306a28682397477460
Java
MohitJain11/SwachAndroidProject
/app/src/main/java/com/android/swach/Handlers/CenterListHandler.java
UTF-8
4,483
2.34375
2
[]
no_license
package com.android.swach.Handlers; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import com.android.swach.extra.db_class; import com.android.swach.models.CenterListModel; public class CenterListHandler extends SQLiteOpenHelper { //Field Name public static final String CentreID = "CentreID"; public static final String PSID = "PSID"; public static final String GPID = "GPID"; public static final String VillageID = "VillageID"; public static final String CentreName = "CentreName"; public static final String DocNo = "DocNo"; public static final String FirstTeacher = "FirstTeacher"; public static final String FTQualification = "FTQualification"; public static final String SecondTeacher = "SecondTeacher"; public static final String STQualification = "STQualification"; public static final String TypeID = "TypeID"; public static final String MobileNo = "MobileNo"; public static final String Latitude = "Latitude"; public static final String Longitude = "Longitude"; public static final String CordID = "CordID"; //Table Name public static final String TABLE_NAME = "Center_List_Handler"; //create query public static final String CREATE_QUERY = "CREATE TABLE if not exists " + TABLE_NAME + "(id INTEGER PRIMARY KEY AUTOINCREMENT, " + CentreID + " TEXT, " + PSID + " TEXT, " + VillageID + " TEXT, " + CentreName + " TEXT, " + DocNo + " TEXT, " + FirstTeacher + " TEXT, " + FTQualification + " TEXT, " + SecondTeacher + " TEXT, " + STQualification + " TEXT, " + TypeID + " TEXT, " + MobileNo + " TEXT, " + Latitude + " TEXT, " + Longitude + " TEXT, " + CordID + " TEXT, " + GPID + " TEXT );"; private static final int DATABASE_VERSION = 8; //Delete query private static final String Delete_QUERY = "DELETE FROM " + TABLE_NAME + ""; //Constructor public CenterListHandler(Context context) { super(context, db_class.DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_QUERY); } //To insert values public int addinnformation(CenterListModel tecm, SQLiteDatabase db) { ContentValues contentValue = new ContentValues(); contentValue.put(CentreID, tecm.CentreID); contentValue.put(PSID, tecm.PSID); contentValue.put(GPID, tecm.GPID); contentValue.put(VillageID, tecm.VillageID); contentValue.put(CentreName, tecm.CentreName); contentValue.put(DocNo, tecm.DocNo); contentValue.put(FirstTeacher, tecm.FirstTeacher); contentValue.put(FTQualification, tecm.FTQualification); contentValue.put(SecondTeacher, tecm.SecondTeacher); contentValue.put(STQualification, tecm.STQualification); contentValue.put(TypeID, tecm.TypeID); contentValue.put(MobileNo, tecm.MobileNo); contentValue.put(Latitude, tecm.Latitude); contentValue.put(Longitude, tecm.Longitude); contentValue.put(CordID, tecm.CordID); int status = Integer.parseInt(db.insert(TABLE_NAME, null, contentValue) + ""); return status; } public Cursor getinformation(SQLiteDatabase db) { Cursor cursor; String[] projections = { CentreID, PSID, GPID, VillageID, CentreName, DocNo, FirstTeacher, FTQualification, SecondTeacher, STQualification, TypeID, MobileNo, Latitude, Longitude, CordID, }; cursor = db.query(TABLE_NAME, projections, null, null, null, null, null); return cursor; } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } //delete public void deletequery(SQLiteDatabase db) { db.execSQL(Delete_QUERY); } public int countExistCustomer(SQLiteDatabase db) { Cursor cursor = db.rawQuery("Select * FROM " + TABLE_NAME, null); return cursor.getCount(); } }
true
63b70fce10ac349b4a92101d7a8d9a1ab294f066
Java
beigua2github/im
/im-service/im-service-aggregation/src/main/java/com/starsea/im/aggregation/dto/UserDto.java
UTF-8
370
1.726563
2
[]
no_license
package com.starsea.im.aggregation.dto; import lombok.*; import lombok.experimental.Builder; /** * Created by beigua on 2015/8/5. */ @Getter @Setter @NoArgsConstructor @AllArgsConstructor @Builder @ToString public class UserDto { private String name; private int age; private String account; private String password; private String email; }
true
f183da9216f46f3a705659fdca52a1367a25db91
Java
nipafx/demo-java9-jsr305
/src/org/codefx/demo/java9/jsr305/MixedJsr305AndJavaxAnnotation.java
UTF-8
358
2.34375
2
[ "CC0-1.0" ]
permissive
package org.codefx.demo.java9.jsr305; import javax.annotation.Generated; import javax.annotation.Nonnull; @Generated("NIPA-TYPING") public class MixedJsr305AndJavaxAnnotation { public static void main(String[] args) { System.out.println(message()); } @Nonnull public static String message() { return "Hello, JSR 305 and javax.annotations"; } }
true
7a854369a2570ce1aa36421b8e13d0780b385177
Java
artjimlop/droidchan
/DroidChan/src/domain/ReplyScore.java
UTF-8
985
2.234375
2
[]
no_license
package domain; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class ReplyScore extends Score { private Integer replyScoreID; private Integer replyID; public ReplyScore(){ super(); } public ReplyScore(String userCreator, Integer score, String scoreCreationDate ,Integer replyScoreID, Integer scoreID, Integer replyID) { super(userCreator, score, scoreCreationDate,scoreID); this.replyScoreID = replyScoreID; this.replyID = replyID; } public ReplyScore(String userCreator, Integer score, String scoreCreationDate , Integer scoreID, Integer replyID) { super(userCreator, score, scoreCreationDate,scoreID); this.replyID = replyID; } public Integer getReplyScoreID() { return replyScoreID; } public void setReplyScoreID(Integer replyScoreID) { this.replyScoreID = replyScoreID; } public Integer getReplyID() { return replyID; } public void setReplyID(Integer replyID) { this.replyID = replyID; } }
true
e88efec4d2ab0f0bd37c3119092d3e7c3f98b5d3
Java
varungontla/Collection-Management-App
/java/Gsoft/project/InternetConnection.java
UTF-8
2,057
2.546875
3
[]
no_license
package Gsoft.project; import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.provider.Settings; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; public class InternetConnection extends AppCompatActivity { static boolean isConnected(Activity activity) { ConnectivityManager cm = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE); /*NetworkInfo wifiCon = cm.getActiveNetworkInfo(ConnectivityManager.TYPE_WIFI); NetworkInfo mobCon = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if ((wifiCon !=null && wifiCon.isConnected() || (mobCon !=null && mobCon.isConnected()) )){ return true; } else { return false; }*/ NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); if (activeNetwork !=null){ return true; } else { return false; } } static void showCustomDailog(final Context context, final Activity activity) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setMessage("You are not connected to the internet") .setCancelable(false) .setPositiveButton("Connect", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { context.startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS)); } }) .setNegativeButton("Exit", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { activity.finish(); } }); AlertDialog alert = builder.create(); alert.show(); } }
true
66ee63aef34a9445bdd903831a8fe2f667bde808
Java
XBCJWen/XPProject
/app/src/main/java/com/jm/xpproject/utils/PhotoUtil.java
UTF-8
15,646
1.9375
2
[]
no_license
package com.jm.xpproject.utils; import android.Manifest; import android.annotation.TargetApi; import android.app.Activity; import android.content.ContentUris; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Build.VERSION; import android.provider.DocumentsContract; import android.provider.MediaStore; import android.provider.MediaStore.Images.Media; import android.support.annotation.NonNull; import android.support.v4.content.FileProvider; import android.widget.Toast; import com.jm.api.util.PermissionTools; import com.jm.core.common.tools.image.BitmapUtil; import com.jm.xpproject.ui.common.act.ClipImageActivity; import com.yanzhenjie.permission.PermissionListener; import java.io.File; import java.util.List; import static android.app.Activity.RESULT_OK; import static com.jm.core.common.tools.base.FileUtil.getRealFilePathFromUri; /** * 图片处理工具类 * * @author jinXiong.Xie */ public class PhotoUtil { /** * 拍照 */ public static final int TAKE_CAMERA = 1; /** * 拍照后截取 */ public static final int CUT_CAMERA = 2; /** * 选择图片后截取 */ public static final int CUT_PHOTO = 3; /** * 选择图片 */ public static final int CHOOSE_PHOTO = 4; /** * 判断是否剪切 */ private boolean isCut = false; /** * 选择图片所需要的权限 */ static final String[] PERMISSIONS_SELECT_PHOTO = new String[]{ Manifest.permission.WRITE_EXTERNAL_STORAGE, }; /** * 拍照所需要的权限 */ static final String[] PERMISSIONS_TAKE_CAMERA = new String[]{ Manifest.permission.CAMERA, }; private Activity activity; private PermissionTools permissionTools; private Uri imageUri; private File outputImage; private OnShowDialogListener dialogListener; /** * 记录用户所操作的方式 */ private int type = TAKE_CAMERA; public PhotoUtil(Context context) { this(context, null); } public PhotoUtil(Context context, OnShowDialogListener dialogListener) { this.activity = (Activity) context; permissionTools = new PermissionTools(context); this.dialogListener = dialogListener; } public Uri getImageUri() { return imageUri; } public File getOutputImage() { return outputImage; } /** * 选择本地图片 */ public void choosePhoto(boolean isCut) { this.isCut = isCut; if (isCut) { type = CUT_PHOTO; } else { type = CHOOSE_PHOTO; } requestPermission(PERMISSIONS_SELECT_PHOTO, new RequestPermissionCallBack() { @Override public void success() { openAlbum(); } }); } /** * 拍照 */ public void takeCamera(boolean isCut) { this.isCut = isCut; if (isCut) { type = CUT_CAMERA; } else { type = TAKE_CAMERA; } requestPermission(PERMISSIONS_TAKE_CAMERA, new RequestPermissionCallBack() { @Override public void success() { openCamera(); } }); } /** * 获取权限 * * @param permission * @param callBack */ private void requestPermission(String[] permission, final RequestPermissionCallBack callBack) { if (dialogListener == null) { permissionTools.requestPermissionDefault(new PermissionTools.PermissionCallBack() { @Override public void onSuccess() { if (callBack != null) { callBack.success(); } } @Override public void onCancel() { } }, permission); } else { permissionTools.requestPermission(new PermissionListener() { @Override public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) { if (callBack != null) { callBack.success(); } } @Override public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) { dialogListener.showDialog(); } }, permission); } } /** * 获取权限回调 */ interface RequestPermissionCallBack { void success(); } private void openCamera() { //创建File对象,用于存储拍照后的图片 outputImage = new File(activity.getExternalCacheDir(), "output_image" + System.currentTimeMillis() + ".jpg"); try { if (outputImage.exists()) { outputImage.delete(); } } catch (Exception e) { e.printStackTrace(); } if (VERSION.SDK_INT >= 24) { imageUri = FileProvider .getUriForFile(activity, activity.getPackageName() + ".FileProvider", outputImage); } else { imageUri = Uri.fromFile(outputImage); } //启动照相机程序 Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); activity.startActivityForResult(intent, TAKE_CAMERA); } private void openAlbum() { // //启动选择图片 // Intent intent = new Intent("android.intent.action.GET_CONTENT"); // intent.setType("image/*"); // activity.startActivityForResult(intent, CHOOSE_PHOTO); //跳转到调用系统图库 Intent intent = new Intent(Intent.ACTION_PICK, Media.EXTERNAL_CONTENT_URI); activity.startActivityForResult(Intent.createChooser(intent, "请选择图片"), CHOOSE_PHOTO); } private void handleImage(Intent data, OnPhotoBackListener listener) { if (VERSION.SDK_INT >= 19) { handleImageOnKitKat(data, listener); } else { handleImageBeforeKitKat(data, listener); } } @TargetApi(19) private void handleImageOnKitKat(Intent data, OnPhotoBackListener listener) { String imagePath = null; Uri uri = data.getData(); if (DocumentsContract.isDocumentUri(activity, uri)) { //如果是document类型的uri,则通过document id 处理 String docId = DocumentsContract.getDocumentId(uri); if ("com.android.providers.media.documents".equals(uri.getAuthority())) { //解析出数字格式的id String id = docId.split(":")[1]; String selection = Media._ID + "=" + id; imagePath = getImagePath(Media.EXTERNAL_CONTENT_URI, selection); } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) { Uri contentUri = ContentUris .withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId)); imagePath = getImagePath(contentUri, null); } } else if ("content".equalsIgnoreCase(uri.getScheme())) { //如果content类型的uri,则使用普通方式处理 imagePath = getImagePath(uri, null); } else if ("file".equalsIgnoreCase(uri.getScheme())) { //如果是file类型的uri,直接获取图片路径即可 imagePath = uri.getPath(); } displayImage(imagePath, listener); } private String getImagePath(Uri uri, String selection) { String path = null; //通过Uri和selection来获取真实的图片路径 Cursor cursor = activity.getContentResolver().query(uri, null, selection, null, null); if (cursor != null) { if (cursor.moveToFirst()) { path = cursor.getString(cursor.getColumnIndex(Media.DATA)); } cursor.close(); } return path; } private void handleImageBeforeKitKat(Intent data, OnPhotoBackListener listener) { Uri uri = data.getData(); String imagePath = getImagePath(uri, null); displayImage(imagePath, listener); } private void displayImage(String imagePath, OnPhotoBackListener listener) { if (imagePath == null || !new File(imagePath).exists()) { Toast.makeText(activity, "找不到该图片", Toast.LENGTH_SHORT).show(); return; } if (imagePath != null) { if (isCut) { cutPhoto(imagePath); } else { int degree = BitmapUtil.readPictureDegree(imagePath); if (degree != 0) { BitmapUtil.saveBitmapFile(BitmapUtil.toTurn(BitmapUtil.getBitmap(imagePath), degree), new File(imagePath)); } // if (listener != null) { // listener.onSuccess(getBitmap(), new File(imagePath)); // } if (listener != null) { listener.onSuccess(BitmapFactory.decodeFile(imagePath), new File(imagePath)); } } } else { Toast.makeText(activity, "failed to get image", Toast.LENGTH_SHORT).show(); } } private void cutPhoto(String imagePath) { // Bitmap bitmap = BitmapFactory.decodeFile(imagePath); // imgPhoto.setImageBitmap(bitmap); File inputImage = new File(imagePath); if (!inputImage.exists()) { Toast.makeText(activity, "找不到该图片", Toast.LENGTH_SHORT).show(); return; } // Bitmap bm = BitmapUtil.compressionBitmap(outputImage); // BitmapUtil.saveBitmapFile(BitmapUtil.martixBitmap(bm), outputImage); //创建File对象,用于存储拍照后的图片 outputImage = new File(activity.getExternalCacheDir(), "output_image" + System.currentTimeMillis() + ".jpg"); try { if (outputImage.exists()) { outputImage.delete(); } } catch (Exception e) { e.printStackTrace(); } // Uri inImageUri; if (VERSION.SDK_INT >= 24) { // inImageUri = FileProvider // .getUriForFile(activity, activity.getPackageName() + ".FileProvider", // inputImage); imageUri = FileProvider .getUriForFile(activity, activity.getPackageName() + ".FileProvider", outputImage); } else { // inImageUri = Uri.fromFile(inputImage); imageUri = Uri.fromFile(outputImage); } turnClipAct(imagePath); // Crop.of(inImageUri, imageUri).asSquare().start(activity, CUT_PHOTO); // Toast.makeText(activity, "请长按蓝框直角移动进行缩放", Toast.LENGTH_SHORT).show(); } /** * 跳转至剪切图片页面 */ private void turnClipAct(String imagePath) { Intent intent = new Intent(); intent.setClass(activity, ClipImageActivity.class); intent.putExtra("FilePath", imagePath); activity.startActivityForResult(intent, CUT_PHOTO); } /** * 压缩图片(只能压缩得到拍照和剪切后的Bitmap) */ private Bitmap compressionBitMap(int size) { Bitmap bm = BitmapUtil.compressionBitmap(outputImage); BitmapUtil.saveBitmapFile(BitmapUtil.martixBitmap(bm, size), outputImage); return BitmapFactory.decodeFile(outputImage.getPath()); } /** * 获取权限失败的监听 */ public interface OnShowDialogListener { void showDialog(); } /** * 图片处理结果 */ public void onActivityResult(int requestCode, int resultCode, Intent data, OnPhotoBackListener listener) { switch (requestCode) { case TAKE_CAMERA: if (resultCode == RESULT_OK) { if (outputImage == null) { return; } if (isCut) { // Crop.of(imageUri, imageUri).asSquare().start(activity, CUT_CAMERA); turnClipAct(outputImage.getPath()); // Toast.makeText(activity, "请长按蓝框直角移动进行缩放", Toast.LENGTH_SHORT).show(); } else { int degree = BitmapUtil.readPictureDegree(outputImage.getPath()); if (degree != 0) { BitmapUtil.saveBitmapFile(BitmapUtil.toTurn(BitmapUtil.getBitmap(outputImage), degree), outputImage); } if (listener != null) { listener.onSuccess(getBitmap(), outputImage); } } } break; case CUT_CAMERA: case CUT_PHOTO: if (resultCode == RESULT_OK) { final Uri uri = data.getData(); if (uri == null) { //重新选择 switch (type) { case TAKE_CAMERA: case CUT_CAMERA: takeCamera(isCut); break; case CHOOSE_PHOTO: case CUT_PHOTO: choosePhoto(isCut); break; default: } return; } String cropImagePath = getRealFilePathFromUri(activity.getApplicationContext(), uri); Bitmap bitMap = BitmapFactory.decodeFile(cropImagePath); if (listener != null) { listener.onSuccess(bitMap, new File(cropImagePath)); } } // if (resultCode == RESULT_OK) { // //将拍摄的照片显示出来 //// Bitmap bitmap = BitmapFactory //// .decodeStream(getContentResolver().openInputStream(imageUri)); // int degree = BitmapUtil.readPictureDegree(outputImage.getPath()); // if (degree != 0) { // BitmapUtil.saveBitmapFile(BitmapUtil.toTurn(BitmapUtil.getBitmap(outputImage), degree), outputImage); // } // if (listener != null) { // listener.onSuccess(getBitmap(), outputImage); // } // } break; case CHOOSE_PHOTO: if (resultCode == RESULT_OK) { handleImage(data, listener); } break; default: break; } } /** * 获取图片(只能获取得到拍照和剪切后的Bitmap) */ private Bitmap getBitmap() { if (outputImage != null) { return BitmapFactory.decodeFile(outputImage.getPath()); } return null; } /** * 图片返回数据 */ public interface OnPhotoBackListener { void onSuccess(Bitmap bitmap, File file); } }
true
947499d9258d7a69b4821db8566936801a84293f
Java
pltchuong/PsdParser
/src/com/psdparser/model/common/descriptor/ReferenceStructure.java
UTF-8
224
2.03125
2
[]
no_license
package com.psdparser.model.common.descriptor; public abstract class ReferenceStructure { private String type; public String getType() { return type; } public void setType(String type) { this.type = type; } }
true
b1282836784e368250e2765a53d90b8ff440bfee
Java
adeloaleman/JavaDesktopApp-ZooManagementSystem
/src/cctzoo/view/animals/ViewAnimalsFrame.java
UTF-8
5,322
3.125
3
[]
no_license
/** * ViewAnimalsFrame * * Purpose: * * To create a frame that displays/search for Animals * * This class creates objects with the following characteristics: * * Header header * ImageLabel viewAnimalImage; * RefineByPanel refiningTextPanel; * ViewAnimalsPanel animalsPanel; * ViewAnimalCard animalView; * ViewOffspringsPanel offspringsPanel; * final ArrayList<String> refiningFields; * GenericButton updateAnimalButton; * ImageLabel viewAnimalsOnFrame; * * This Class Extends MainFrame, that is a class that creates Frames given a input */ package cctzoo.view.animals; import cctzoo.model.animals.Animal; import cctzoo.view.generic.GenericButton; import cctzoo.view.generic.Header; import cctzoo.view.generic.ImageLabel; import cctzoo.view.generic.MainFrame; import cctzoo.view.generic.RefineByPanel; import java.util.ArrayList; /** * * @author Adelo Vieira (2017276), Asmer Bracho (2016328) and Miguelantonio Guerra (2016324) * */ public class ViewAnimalsFrame extends MainFrame { private Header header; private ImageLabel viewAnimalImage; public RefineByPanel refiningTextPanel; private ViewAnimalsPanel animalsPanel; private ViewAnimalCard animalView; private ViewOffspringsPanel offspringsPanel; private final ArrayList<String> refiningFields; private GenericButton updateAnimalButton; private ImageLabel viewAnimalsOnFrame; private final ImageLabel placeHolderImage; private ArrayList<Animal> animals; /** * Constructor of the Class ViewAnimalsFrame to create ViewAnimalsFrame objects. * * This constructor takes the parameters: * * @param frameTitle String that sets the title of the frame * @param frameWidth int that sets the width of the frame * @param frameHeight int that sets the height of the frame * @param iconName String that points to the location of the icon of the frame */ public ViewAnimalsFrame(ArrayList<Animal> animals, String frameTitle, int frameWidth, int frameHeight, String iconName) { super(frameTitle, frameWidth, frameHeight, iconName); this.animals = animals; // Header panel this.header = new Header(frameWidth, 260, "View/Search/Update Animals", "src/cctzoo/view/images/addanimal.png", "src/cctzoo/view/images/back.png", "Go Back to dashboard"); this.add(header); // Animals Image this.viewAnimalImage = new ImageLabel(10, 40, 270, 180, "src/cctzoo/view/images/animali.png"); this.add(viewAnimalImage.getImageLabel()); // Refining By Panel this.refiningFields = new ArrayList<String>(); this.refiningFields.add("Type"); this.refiningFields.add("Specie"); this.refiningFields.add("Name"); this.refiningFields.add("Keeper"); this.refiningTextPanel = new RefineByPanel("Refine Animal view by filtering data stored", refiningFields); this.add(this.refiningTextPanel); // Animals' list Panel this.animalsPanel = new ViewAnimalsPanel(15, 205, 500, 360, "Animals", "Searched Animals", 330); this.add(this.animalsPanel); // Initializing the table with all the data this.animalsPanel.dataToString(animals); this.animalsPanel.setData(); // Another Animals Image this.placeHolderImage = new ImageLabel(525, 205, 430, 360, "src/cctzoo/view/images/placeholder.jpg"); this.add(this.placeHolderImage.getImageLabel()); this.placeHolderImage.getImageLabel(); // Animal's Description Card this.animalView = new ViewAnimalCard(525, 205, 220, 360, "Animal Details", "Details of Clicked Animal"); this.add(this.animalView); // Animal's Offprings Table this.offspringsPanel = new ViewOffspringsPanel(755, 205, 200, 300, "Offsprings", "Offsprings of selected animal", 270); this.add(this.offspringsPanel); // Update Animal Selected Button this.updateAnimalButton = new GenericButton(800, 520, 120, "src/cctzoo/view/images/updateanimal.png", "Update Animal", "Update Selected Animal"); this.add(this.updateAnimalButton); // Another Animals Image this.viewAnimalsOnFrame = new ImageLabel(590, 60, 355, 142, "src/cctzoo/view/images/zoo.png"); this.add(this.viewAnimalsOnFrame.getImageLabel()); } public ViewAnimalCard getAnimalView() { return animalView; } public RefineByPanel getRefiningTextPanel() { return refiningTextPanel; } public Header getHeader() { return header; } public ViewOffspringsPanel getOffspringsPanel() { return offspringsPanel; } public ImageLabel getPlaceHolderImage() { return placeHolderImage; } public ViewAnimalsPanel getAnimalsPanel() { return animalsPanel; } public ArrayList<Animal> getAnimals() { return animals; } public GenericButton getUpdateAnimalButton() { return updateAnimalButton; } }
true
4109316171e1df0ffb5c39e99fa37ef569c266df
Java
Naddaamahmoud/Logic-Design-Lab
/LogicDesignLab-master/src/logic/design/lab/XnorGui.java
UTF-8
1,003
2.5625
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 logic.design.lab; import java.awt.*; import java.awt.event.MouseListener; import java.awt.image.ImageObserver; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; /** * * @author abade */ public class XnorGui extends Component { String id; int x; int y; public XnorGui(String id, int x, int y) { this.id = id; this.x = x; this.y = y; this.setBounds(x, y, 92, 55); this.setSize(180,155); } @Override public void paint(Graphics g) { Toolkit t=Toolkit.getDefaultToolkit(); Image img = t.getImage("xnorgate.png"); g.drawImage(img,0,0,this); g.drawString(id, 20, 20); } }
true
4a170a857da360cd713c0bbc5a569f42b5025c39
Java
olibye/aeftools
/src/java/com/appenginefan/toolkit/persistence/ObjectPersistence.java
UTF-8
2,147
2.34375
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2009 Jens Scheffler (appenginefan.com) * * Licensed under the Apache License, Version 2.0 (the * "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the * License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in * writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing * permissions and limitations under the License. */ package com.appenginefan.toolkit.persistence; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; /** * A persistence that uses serialization to put objects into * a store. Use with caution! */ public class ObjectPersistence<T extends Serializable> extends MarshallingPersistence<T> { public ObjectPersistence(Persistence<byte[]> backend) { super(backend); } @Override protected byte[] makeArray(T nonNullValue) { try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer); out.writeObject(nonNullValue); out.close(); return buffer.toByteArray(); } catch (IOException e) { throw new StoreException( "Object serialization failed", e); } } @SuppressWarnings("unchecked") @Override protected T makeType(byte[] nonNullValue) { try { return (T) new ObjectInputStream( new ByteArrayInputStream(nonNullValue)) .readObject(); } catch (ClassCastException e) { throw new StoreException( "Object deserialization failed", e); } catch (IOException e) { throw new StoreException( "Object deserialization failed", e); } catch (ClassNotFoundException e) { throw new StoreException( "Object deserialization failed", e); } } }
true
888579bc5f5154d735d9e0ee2d3c3ed4a96bcba2
Java
dalittl/TaskMessenger
/src/com/acnc/mm/controller/LoginBean.java
UTF-8
2,679
2.078125
2
[]
no_license
package com.acnc.mm.controller; import java.io.Serializable; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.SessionScoped; import javax.faces.context.FacesContext; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import com.acnc.mm.application.AuthenticationService; import com.acnc.mm.domain.messenger.ContractRecord; @ManagedBean(name = "loginBean") @SessionScoped public class LoginBean implements Serializable { /** * */ private static final long serialVersionUID = 8257630497025659422L; private String username; private String password; public String nameuser; boolean isUser = false; boolean isAdmin = false; @ManagedProperty(value = "#{authenticationService}") private AuthenticationService authenticationService; public String login() { boolean success = authenticationService.login(username, password); System.out.println("Username at LoginBean:" + username); if (success){ Authentication auth = SecurityContextHolder.getContext().getAuthentication(); //auth.getAuthorities().equals("ROLE_USER"); nameuser = auth.getName(); System.out.println(nameuser); if (auth.getAuthorities().toString().equals("[ROLE_ADMIN]")){ // System.out.println(auth.getAuthorities().toString().equals("[ROLE_ADMIN]")); // System.out.println(auth.getAuthorities().toString()); return "main.xhtml"; } else if(auth.getAuthorities().toString().equals("[ROLE_USER]")) { return "tasks.xhtml"; } } FacesContext.getCurrentInstance().addMessage( null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error:", "Login or password incorrect.")); return "login.xhtml"; } public String logout(){ authenticationService.logout(); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Info:", "You have been successfully logged out.")); return "login.xhtml"; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getNameuser() { return nameuser; } public void setNameuser(String nameuser) { this.nameuser = nameuser; } public void setAuthenticationService(AuthenticationService authenticationService) { this.authenticationService = authenticationService; } }
true
7c38f208be055e70cb4e683581e378a27b76c0da
Java
ahmadmuflih/smartsurveillance
/app/src/main/java/info/edutech/smartsurveillance/model/Capture.java
UTF-8
1,335
2.296875
2
[]
no_license
package info.edutech.smartsurveillance.model; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.Date; import io.realm.RealmObject; import io.realm.annotations.PrimaryKey; /** * Created by Baso on 2/21/2017. */ public class Capture extends RealmObject { @SerializedName("id") @Expose @PrimaryKey private int id; @SerializedName("url") @Expose private String url; @SerializedName("image_name") @Expose private String imageName; @SerializedName("date") @Expose private Date date; public Capture() { } public Capture(int id, String url, String imageName, Date date) { this.id = id; this.url = url; this.imageName = imageName; this.date = date; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getImageName() { return imageName; } public void setImageName(String imageName) { this.imageName = imageName; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } }
true
9c5a9bffd53c79f71604f01bd31b11084252449b
Java
adreeana/spring-batch-samples
/src/main/java/com/adreeana/batch/integration/launch_on_event/FileToJobLaunchRequestTransformer.java
UTF-8
1,244
2.203125
2
[]
no_license
package com.adreeana.batch.integration.launch_on_event; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobParametersBuilder; import org.springframework.batch.integration.launch.JobLaunchRequest; import org.springframework.integration.annotation.Transformer; import java.io.File; import java.time.LocalDateTime; import java.time.temporal.ChronoField; public class FileToJobLaunchRequestTransformer { private static final Logger log = LoggerFactory.getLogger(FileToJobLaunchRequestTransformer.class); private final String fileParameter; private final Job job; public FileToJobLaunchRequestTransformer(String fileParameter, Job job) { this.fileParameter = fileParameter; this.job = job; } @Transformer public JobLaunchRequest transform(File file) { final JobLaunchRequest result = new JobLaunchRequest(job, new JobParametersBuilder() .addLong("lot", LocalDateTime.now().getLong(ChronoField.MILLI_OF_DAY)) .addString(fileParameter, file.getAbsolutePath()) .toJobParameters()); log.info("[TRANSFORMER] Transformed file {} in job launch request {}.", file, result); return result; } }
true
4e37068d2fa67db27b2221e7539e6fd3e95a05b9
Java
mmarkie2/toDo2021MVP
/app/src/main/java/com/example/todo2/viewDagger/MainScreenActivityModule.java
UTF-8
765
2.125
2
[]
no_license
package com.example.todo2.viewDagger; import android.content.Context; import com.example.todo2.Contract; import com.example.todo2.view.MainScreenActivity; import dagger.Module; import dagger.Provides; @Module public class MainScreenActivityModule { private final MainScreenActivity mainScreenActivity; private final Context context; public MainScreenActivityModule(MainScreenActivity mainScreenActivity) { this.mainScreenActivity = mainScreenActivity; this.context = mainScreenActivity.getApplicationContext(); } @Provides Contract.presenterToMainScreenView providePresenterToMainScreenView() { return this.mainScreenActivity; } @Provides public Context context() { return context; } }
true
efc6e481dadb340c2e2108a7a7f5cef7c330c48a
Java
oneacik/foodfront-application
/app/src/main/java/pl/foodfront/views/ActivityLogin.java
UTF-8
3,389
2.40625
2
[]
no_license
package pl.foodfront.views; import android.app.Activity; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.Toast; import pl.foodfront.R; import pl.foodfront.communication.Bridge; /** * Created by Michał Stobiński on 2016-02-04. */ @SuppressWarnings("deprecation") public class ActivityLogin extends Activity implements ILoginCallback { private ILoginCallback callback; private EditText etUser; private EditText etPass; private Bridge bridge; private Intent intent; @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.login_activity); this.callback = this; recallInterruptedConenction(); // w przypadku zmiany konfiguracji próbujemy uzyskać wcześniejszą instancję klasy Bridge etUser = (EditText) findViewById(R.id.loginEtUser); etPass = (EditText) findViewById(R.id.loginEtPass); intent = new Intent(this, Main.class); findViewById(R.id.loginButConfirm).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String username = etUser.getText().toString(); String password = etPass.getText().toString(); boolean userCondition = !(username.equals(null) || username.equals("")); boolean passCondition = !(password.equals(null) || password.toString().equals("")); if (userCondition && passCondition) { bridge.connectActivity(callback); bridge.login(username, password); } else if (!(userCondition && passCondition)) { etUser.setHintTextColor(Color.RED); etPass.setHintTextColor(Color.RED); return; } else if (userCondition) { etUser.setHintTextColor(Color.RED); etPass.setHintTextColor(Color.LTGRAY); } else if (passCondition) { etUser.setHintTextColor(Color.LTGRAY); etPass.setHintTextColor(Color.RED); } } }); findViewById(R.id.loginButCancel).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(intent); } }); } private void recallInterruptedConenction() { bridge = (Bridge) this.getLastNonConfigurationInstance(); if(bridge != null) { bridge.connectActivity(callback); } else { bridge = new Bridge(); } } @Override protected void onDestroy() { super.onDestroy(); if(bridge != null) { bridge.disconnectActivity(); } } @Override public Object onRetainNonConfigurationInstance() { return bridge; } @Override public void loginInfo(Boolean logged, String msg) { if(logged) { startActivity(intent); Toast.makeText(this, "Logowanie zakończone sukcesem", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "Logowanie nieudane", Toast.LENGTH_SHORT).show(); } } }
true
d87d2f94248c06e045eca02ace8a55acb557ef17
Java
wjbtt/java-demo-collection
/dubbo-demo/dubbo-api/src/main/java/pers/husen/demo/dubbo/TestService.java
UTF-8
252
1.820313
2
[]
no_license
package pers.husen.demo.dubbo; /** * @Desc dubbo接口 * * @Author 何明胜 * * @Created at 2018年3月20日 上午8:59:04 * * @Version 1.0.0 */ public interface TestService { void test(); String testString(String str); }
true
720e6c82db71aab42151571a5f78f46a1e96382b
Java
Bojo38/bbtour
/Teamedit/src/bojo/teamedit/shared/SkillType.java
WINDOWS-1250
1,186
2.25
2
[]
no_license
package bojo.teamedit.shared; import java.io.Serializable; public class SkillType implements Serializable{ public String _name; public String _accronym; static final long serialVersionUID = 1L; public SkillType() { _name="Undefined"; _accronym="U"; } public SkillType(String Name, String Accronym) { _name=Name; _accronym=Accronym; } public void set_name(String name) { _name=name; } public String get_name() { return _name; } public void set_accronym(String accronym) { _accronym=accronym; } public String get_accronym() { return _accronym; } public static final SkillType GeneralSkill=new SkillType("General","G"); public static final SkillType StrengthSkill=new SkillType("Force","F"); public static final SkillType AgilitySkill=new SkillType("Agilit","A"); public static final SkillType PassSkill=new SkillType("Passe","P"); public static final SkillType Mutation=new SkillType("Mutation","M"); public static final SkillType ExtraoridnarySkill=new SkillType("Extraordinaire","E"); public static final SkillType Ehancements=new SkillType("Augmentations","C"); }
true
812badda257c351bdb08e1aa6df469e60ef206a2
Java
JaneChelle/agro-achievement
/src/main/java/org/wlgzs/agro_achievement/controller/ExampleController.java
UTF-8
3,703
2.234375
2
[]
no_license
package org.wlgzs.agro_achievement.controller; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import org.wlgzs.agro_achievement.base.BaseController; import org.wlgzs.agro_achievement.entity.Example; import org.wlgzs.agro_achievement.entity.User; import org.wlgzs.agro_achievement.util.Result; import javax.servlet.http.HttpSession; import java.util.List; /** * <p> * 前端控制器 * </p> * 案例 * * @author 胡亚星 * @since 2019-01-19 */ @RestController @RequestMapping("/example") public class ExampleController extends BaseController { //去添加案例 @RequestMapping(value = "/toAddExample") public ModelAndView toAddExample() { return new ModelAndView("information/addExample"); } //添加案例 @RequestMapping(value = "/addExample") public Result addExample(Example example) { return iCaseService.addExample(example); } //去修改案例 @RequestMapping(value = "/toModifyExample") public ModelAndView toModifyExample(Model model, Integer exampleId) { Example example = iCaseService.exampleDetails(exampleId); model.addAttribute("example", example); return new ModelAndView("information/modifyExample"); } //修改案例 @RequestMapping(value = "/modifyExample") public Result modifyExample(Model model, Example example) { System.out.println(example); Result result = iCaseService.modifyExample(example); return result; } //删除案例 @RequestMapping(value = "/deleteExample", method = RequestMethod.DELETE) public Result deleteExample(Model model, Integer exampleId) { Result result = iCaseService.deleteExample(exampleId); return result; } //按照用户查询所有成功案例(状态码)(用户自身操作) @GetMapping("/selectExampleByUser")//分页 public ModelAndView selectExampleByUser(Model model, String statusCode, HttpSession session, @RequestParam(value = "current", defaultValue = "1") Integer current, @RequestParam(value = "limit", defaultValue = "8") Integer limit) { User user = (User) session.getAttribute("user"); int userId = user.getUserId(); Result result = iCaseService.selectExampleByUser(userId, statusCode, current, limit); List<Example> exampleList = (List<Example>) result.getData(); model.addAttribute("exampleList", exampleList); model.addAttribute("statusCode", statusCode); model.addAttribute("TotalPages", result.getPages());//总页数 model.addAttribute("Number", result.getCurrent());//当前页数 return new ModelAndView("information/userExampleList"); } //查看案列详情 @RequestMapping(value = "/exampleDetails") public ModelAndView exampleDetails(Model model, Integer exampleId) { Example example = iCaseService.exampleDetails(exampleId); model.addAttribute("example", example); return new ModelAndView("example/exampleDetails"); } //查询所有案例 @RequestMapping(value = "/selectAllExample") public ModelAndView selectAllExample(Model model) { QueryWrapper<Example> queryWrapper = new QueryWrapper<>(); List<Example> exampleList = iCaseService.list(queryWrapper); System.out.println("exampleList" + exampleList); model.addAttribute("exampleList", exampleList); return new ModelAndView("example/ExampleList"); } }
true
8b168fce2046f8b4bfd109699d8deba04d577452
Java
sengeiou/medicalcare_java
/medicalcare/.svn/pristine/ac/ac5cca21397b1addfb24ec0b188450da595a2870.svn-base
UTF-8
240
1.53125
2
[]
no_license
package com.cmcc.medicalcare.service; import com.cmcc.medicalcare.model.SystemMessageNotice; /** * * @author Administrator * */ public interface ISystemMessageNoticeService extends GenericService<SystemMessageNotice, Integer> { }
true
44e3603f5ee8a8e850db257b59054b500f12c244
Java
guoyjalihy/portal
/src/main/java/com/common/portal/socket/ClientMsgHandleThread.java
UTF-8
3,510
2.5625
3
[]
no_license
package com.common.portal.socket; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.StringUtils; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; /** * @description:处理客户端请求消息并做出响应 * @author: guoyanjun * @date: 2018/11/17 18:27 */ public class ClientMsgHandleThread extends Thread { private final Logger logger = LoggerFactory.getLogger(this.getClass()); private short startSign = (short)0xFFFF; private int timeStamp = (int)System.currentTimeMillis()/1000; private byte alarmType = 0; private SyncSwitch syncSwitch = new SyncSwitch(); Socket socket ; DataOutputStream dos ; BufferedInputStream bis ; /** * 构造方法 */ public ClientMsgHandleThread(Socket socket){ this.socket = socket; } /** * 启动线程 */ @Override public void run() { init(); String inputStr; String outputStr; DataInputStream dis; Thread loopThread = null; try { while (true) { byte[] bytes = new byte[9]; ByteArrayInputStream bais = new ByteArrayInputStream(bytes); dis = new DataInputStream(bis); dis.readFully(bytes); DataInputStream ois = new DataInputStream(bais); short s1 = ois.readShort(); byte s2 = ois.readByte(); int s3 = ois.readInt(); short length = ois.readShort(); byte[] body = new byte[length]; dis.readFully(body); inputStr = new String(body, "UTF-8"); logger.info("socket client input info:{}", inputStr); if (inputStr.contains("closeConnAlarm")) { logger.info("==============msg contains closeConnAlarm"); socket.close(); break; } //4、获取输出流,响应客户端的请求 outputStr = buildMessage(); logger.info("socket client output info:{}", outputStr); if (StringUtils.isEmpty(outputStr)) { continue; } dos.writeShort(startSign); dos.writeByte(alarmType); dos.writeInt(timeStamp); dos.writeShort(outputStr.getBytes("UTF-8").length); dos.write(outputStr.getBytes("UTF-8")); if (inputStr.contains("reqLoginAlarm") || inputStr.contains("reqSyncAlarmFile")){ continue; } if (loopThread == null){ loopThread = new LoopAlarmThread(socket); loopThread.start(); } } }catch (IOException e){ logger.error("QueryAlarmThread run error.", e); throw new RuntimeException(e); } } private String buildMessage() { return "ackLoginAlarm;result=succ;resDesc=null"; } private void init() { try { bis = new BufferedInputStream(socket.getInputStream()); dos = new DataOutputStream(socket.getOutputStream()); } catch (IOException e) { logger.error("QueryAlarmThread init error.",e); } } }
true
98107ad9bee00beffab451dc335300bd203bed9a
Java
smasiek/Population-census
/src/main/java/com/miloszmomot/census/PeopleIterator.java
UTF-8
128
1.796875
2
[]
no_license
package com.miloszmomot.census; import java.util.Iterator; public interface PeopleIterator { Iterator createIterator(); }
true
6d02ba35b6173692fe8ec7ba1c928d1458a10bce
Java
elangoram1998/Wipro_PRP
/Video_Rental_Inventry_System/VideoStore.java
UTF-8
982
2.984375
3
[]
no_license
package com.mile1.videoRental; import java.util.*; public class VideoStore { Video[] store=new Video[3]; HashMap<String,Integer>hm=new HashMap<>(); int x=0; void addVideo(String name) { if(!hm.containsKey(name)) { hm.put(name,x); x++; store[hm.get(name)]=new Video(name); } else { System.out.println("already there"); } } void doCheckout(String name) { store[hm.get(name)].doCheckout(); } void doReturn(String name) { store[hm.get(name)].doReturn(); } void receiveRating(String name,int rating) { store[hm.get(name)].receiveRating(rating); } void listInventry() { System.out.println("---------------------------------------------------------------"); for(int i=0;i<hm.size();i++) { System.out.println("Video name:"+store[i].getName()+" "+"checkout status:"+store[i].getCheckout()+" "+"rating:"+store[i].getRating()); } System.out.println("---------------------------------------------------------------"); } }
true
dc2565d0f5673dfbdac5dcca769cb9030133172a
Java
Bastue/AddonApplication
/src/java_addon_application/SERVICEUSER.java
UTF-8
3,995
2.671875
3
[]
no_license
package java_addon_application; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; /** * * @author Emrah Bastug */ public class SERVICEUSER { // the service user class SQL_CONNECTION sql_connection = new SQL_CONNECTION(); // create a function to add a service user public boolean addServiceUser(String sname, String serviceu, String four, String site) { PreparedStatement st; String addQuery = "INSERT INTO `service`(`surname`, `service_user_type`, `four_digit_ext`, `site_or_ward_location`) VALUES (?,?,?,?)"; try { st = sql_connection.createConnection().prepareStatement(addQuery); st.setString(1, sname); st.setString(2, serviceu); st.setString(3, four); st.setString(4, site); return (st.executeUpdate() > 0); } catch (SQLException ex) { Logger.getLogger(SERVICEUSER.class.getName()).log(Level.SEVERE, null, ex); return false; } } // create a function to edit the selected client public boolean editServiceUser(int id,String sname, String serviceu, String four, String site) { PreparedStatement st; String editQuery = "UPDATE `service` SET `surname`=?,`service_user_type`=?,`four_digit_ext`=?,`site_or_ward_location`=? WHERE `id`=?"; try { st = sql_connection.createConnection().prepareStatement(editQuery); st.setString(1, sname); st.setString(2, serviceu); st.setString(3, four); st.setString(4, site); st.setInt(5, id); return (st.executeUpdate() > 0); } catch (SQLException ex) { Logger.getLogger(SERVICEUSER.class.getName()).log(Level.SEVERE, null, ex); return false; } } // create a function to remove the selected client public boolean removeServiceUser(int id) { PreparedStatement st; String deleteQuery = "DELETE FROM `service` WHERE `id`=?"; try { st = sql_connection.createConnection().prepareStatement(deleteQuery); st.setInt(1, id); return (st.executeUpdate() > 0); } catch (SQLException ex) { Logger.getLogger(SERVICEUSER.class.getName()).log(Level.SEVERE, null, ex); return false; } } // create a function to populate the jtabel with all the clients in the database public void fillServiceUserJTable(JTable table) { PreparedStatement ps; ResultSet rs; String selectQuery = "SELECT * FROM `service`"; try { ps = sql_connection.createConnection().prepareStatement(selectQuery); rs = ps.executeQuery(); DefaultTableModel tableModel = (DefaultTableModel)table.getModel(); Object[] row; while(rs.next()) { row = new Object[5]; row[0] = rs.getInt(1); row[1] = rs.getString(2); row[2] = rs.getString(3); row[3] = rs.getString(4); row[4] = rs.getString(5); tableModel.addRow(row); } } catch (SQLException ex) { Logger.getLogger(SERVICEUSER.class.getName()).log(Level.SEVERE, null, ex); } } }
true
03f2bab89078a3331a3b610e1c8884897b473e70
Java
qinweiforandroid/QDownload
/app/src/main/java/com/qw/example/MyApplication.java
UTF-8
987
2.140625
2
[]
no_license
package com.qw.example; import android.app.Application; import com.qw.download.manager.DownloadConfig; import com.qw.download.manager.DownloadManager; /** * Created by qinwei on 2021/6/7 18:41 */ public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); DownloadConfig.init(new DownloadConfig.Builder() .setConnectTimeout(10000)//连接超时时间 .setReadTimeout(10000)//读取超时时间 .setMaxTask(3)//最多3个任务同时下载 .setMaxThread(3)//1个任务分3个线程分段下载 .setAutoResume(true)//启动自动恢复下载 .setRetryCount(3)//单个任务异常T下载失败重试次数 .setDownloadDir(getExternalCacheDir().getAbsolutePath())//设置文件存储目录 .setDebug(BuildConfig.DEBUG) .builder()); DownloadManager.init(this); } }
true
8b8a7def0f7b387c8fdf45e4c2e524bdee1fcefa
Java
Hebut-Messay-relation-student/1592512019Assignment1
/159251assignment1/src/test/java/nz/ac/massey/assignment1/SaveTest.java
UTF-8
1,055
2.734375
3
[]
no_license
package nz.ac.massey.assignment1; import java.awt.FileDialog; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.List; import junit.framework.TestCase; public class SaveTest extends TestCase { @SuppressWarnings("resource") public void testSave() throws Exception{ GUI gui = new GUI(); gui.jta.setText("This is the testing string"); FileDialog saveDia = new FileDialog(gui.frmte, "Save", FileDialog.SAVE); Save save = new Save(); save.save(gui.jta, saveDia); FileReader fr=null; char[] chars = new char[1024]; String test = ""; int ch = 0; try { fr=new FileReader(saveDia.getDirectory()+saveDia.getFile()); while((ch=fr.read())!=-1) { test = test+(char)ch; } } catch(IOException e) { System.out.println(e.toString()); } finally { try { if(fr!=null) { fr.close(); } } catch(IOException e) { System.out.println(e.toString()); } } assertEquals(test,"This is the testing string"); } }
true
2bbf77116367d52cb81654ace8698b1c5de5941d
Java
vijoz/common-camera
/common-base/src/main/java/lib/android/timingbar/com/base/imageloader/ImageLoader.java
UTF-8
1,744
2.59375
3
[]
no_license
package lib.android.timingbar.com.base.imageloader; import android.content.Context; import lib.android.timingbar.com.base.imageloader.glide.GlideImageLoaderStrategy; /** * ImageLoader * ----------------------------------------------------------------------------------------------------------------------------------- * 实现策略接口(图片的相关操作实现) * * @author rqmei on 2018/1/25 * @singleton 表示单例模式 * @inject 标识需要依赖注入的构造函数和字段(注意:接口不能够创建;第三方库的类不能够创建;*配置对象必须配置!) * 注解构造函数:通过标记构造函数,告诉Dagger 2可以创建该类的实例(Dagger2通过Inject标记可以在需要这个类实例的时候来找到这个构造函数并把相关实例new出来)从而提供依赖关系。 * 注解依赖变量:通过标记依赖变量,Dagger2提供依赖关系,注入变量 */ public final class ImageLoader { private IBaseImageLoaderStrategy strategy; public ImageLoader() { if (strategy == null) { strategy = new GlideImageLoaderStrategy (); } } /** * 加载图片 * * @param context 上下文 * @param config (ImageConfig)图片相关配置 * @param <T> 通配泛型 */ public <T extends ImageConfig> void loadImage(Context context, T config) { strategy.loadImage (context, config); } /** * 清空图片 * * @param context 上下文 * @param config (ImageConfig)图片相关配置 * @param <T> 通配泛型 */ public <T extends ImageConfig> void clear(Context context, T config) { strategy.clear (context, config); } }
true
b6e0611ac1b99129a295afe1fd1bedb9a94ef7ab
Java
mdelacalle/glob3mobile
/Glob3Demo/g3m/src/main/java/org/glob3/mobile/generated/DEMGridUtils.java
UTF-8
4,673
2.203125
2
[ "BSD-2-Clause" ]
permissive
package org.glob3.mobile.generated; // // DEMGridUtils.cpp // G3MiOSSDK // // Created by Diego Gomez Deck on 11/7/16. // // // // DEMGridUtils.hpp // G3MiOSSDK // // Created by Diego Gomez Deck on 11/7/16. // // //class Mesh; //class DEMGrid; //class Planet; //class Geodetic3D; //class Sector; //class Vector2S; //class Vector3D; public class DEMGridUtils { private DEMGridUtils() { } public static Vector3D getMinMaxAverageElevations(DEMGrid grid) { final IMathUtils mu = IMathUtils.instance(); double minElevation = mu.maxDouble(); double maxElevation = mu.minDouble(); double sumElevation = 0.0; final int width = grid.getExtent()._x; final int height = grid.getExtent()._y; for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { final double elevation = grid.getElevation(x, y); if (!(elevation != elevation)) { if (elevation < minElevation) { minElevation = elevation; } if (elevation > maxElevation) { maxElevation = elevation; } sumElevation += elevation; } } } return new Vector3D(minElevation, maxElevation, sumElevation / (width * height)); } public static Mesh createDebugMesh(DEMGrid grid, Planet planet, float verticalExaggeration, Geodetic3D offset, float pointSize) { final Vector3D minMaxAverageElevations = getMinMaxAverageElevations(grid); final double minElevation = minMaxAverageElevations._x; final double maxElevation = minMaxAverageElevations._y; return createDebugMesh(grid, planet, verticalExaggeration, offset, minElevation, maxElevation, pointSize); } public static Mesh createDebugMesh(DEMGrid grid, Planet planet, float verticalExaggeration, Geodetic3D offset, double minElevation, double maxElevation, float pointSize) { final double deltaElevation = maxElevation - minElevation; FloatBufferBuilderFromGeodetic vertices = FloatBufferBuilderFromGeodetic.builderWithFirstVertexAsCenter(planet); FloatBufferBuilderFromColor colors = new FloatBufferBuilderFromColor(); final Projection projection = grid.getProjection(); final Vector2I extent = grid.getExtent(); final Sector sector = grid.getSector(); for (int x = 0; x < extent._x; x++) { final double u = (double) x / (extent._x - 1); final Angle longitude = projection.getInnerPointLongitude(sector, u).add(offset._longitude); for (int y = 0; y < extent._y; y++) { final double elevation = grid.getElevation(x, y); if (!(elevation != elevation)) { final double v = 1.0 - ((double) y / (extent._y - 1)); final Angle latitude = projection.getInnerPointLatitude(sector, v).add(offset._latitude); final double height = (elevation + offset._height) * verticalExaggeration; vertices.add(latitude, longitude, height); final float gray = (float)((elevation - minElevation) / deltaElevation); colors.add(gray, gray, gray, 1); } } } Mesh result = new DirectMesh(GLPrimitive.points(), true, vertices.getCenter(), vertices.create(), 1, pointSize, null, colors.create(), true); // depthTest - flatColor - lineWidth if (vertices != null) vertices.dispose(); return result; } public static DEMGrid bestGridFor(DEMGrid grid, Sector sector, Vector2S extent) { if (grid == null) { return null; } final Sector gridSector = grid.getSector(); final Vector2I gridExtent = grid.getExtent(); if (gridSector.isEquals(sector) && gridExtent.isEquals(extent)) { grid._retain(); return grid; } if (!gridSector.touchesWith(sector)) { return null; } DEMGrid subsetGrid = SubsetDEMGrid.create(grid, sector); final Vector2I subsetGridExtent = subsetGrid.getExtent(); if (subsetGridExtent.isEquals(extent)) { return subsetGrid; } else if ((subsetGridExtent._x > extent._x) || (subsetGridExtent._y > extent._y)) { DEMGrid decimatedGrid = DecimatedDEMGrid.create(subsetGrid, extent); subsetGrid._release(); // moved ownership to decimatedGrid return decimatedGrid; } else { DEMGrid interpolatedGrid = InterpolatedDEMGrid.create(subsetGrid, extent); subsetGrid._release(); // moved ownership to interpolatedGrid return interpolatedGrid; } } }
true
22e9e82ec6db3190b542950ab88e7e04c5ae6106
Java
nathox/craftdenki
/src/com/internousdev/craftdenki/action/UserInfoChangeAction.java
UTF-8
1,861
2.15625
2
[]
no_license
package com.internousdev.craftdenki.action; import java.sql.SQLException; import java.util.ArrayList; import java.util.Iterator; import java.util.Map; import org.apache.struts2.interceptor.SessionAware; import com.internousdev.craftdenki.dao.UserInfoChangeDAO; import com.internousdev.craftdenki.dto.UserInfoChangeDTO; import com.opensymphony.xwork2.ActionSupport; public class UserInfoChangeAction extends ActionSupport implements SessionAware { public Map<String, Object> session; private String result; private ArrayList<UserInfoChangeDTO> list_user_info = new ArrayList<UserInfoChangeDTO>(); private UserInfoChangeDAO userInfoChangeDAO = new UserInfoChangeDAO(); public String execute() throws SQLException{ /* * ↓セッションからログインしている「ユーザーID」を格納して、DAOのメソッドの引数にしてる */ String loginid = session.get("trueID").toString(); list_user_info = userInfoChangeDAO.getUserInfo(loginid); Iterator<UserInfoChangeDTO> iterator = list_user_info.iterator(); if (!(iterator.hasNext())) { list_user_info = null; } result = SUCCESS; return result; } @Override public void setSession(Map<String, Object> session) { // TODO 自動生成されたメソッド・スタブ this.session = session; } public Map<String, Object> getSession(){ return session; } public UserInfoChangeDAO userInfoChangeDAO(){ return userInfoChangeDAO; } public void setUserInfoChangeDAO(UserInfoChangeDAO userInfoChangeDAO){ this.userInfoChangeDAO = userInfoChangeDAO; } public ArrayList<UserInfoChangeDTO> getList_user_info(){ return list_user_info; } public void setList_user_info(ArrayList<UserInfoChangeDTO> list_user_info){ this.list_user_info = list_user_info; } }
true
ad0c2c6b62f2d73fb3bc8af52dfe28edb197ad52
Java
jwweber/JaviBeans_Intelligent_Tutoring_System
/JaviBeans3.0/src/main/java/edu/asu/CSE360/recitation6/group6/ProgrammingAssignmentGUI.java
UTF-8
4,766
3.25
3
[]
no_license
package edu.asu.CSE360.recitation6.group6; import java.awt.Dimension; /* * This class provides a GUI displaying buttons that link to different programming assignment window objects. * Added parameters that enable communication with ProgrammingAssignmentWindow and Evaluator * Assignment Number: Recitation Project 3 * Completion Time: 30 additional minutes * * @author Jamison Weber * @version 2.0 */ import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; public class ProgrammingAssignmentGUI extends JPanel{ private JButton assignmentOne; private JButton assignmentTwo; private JButton assignmentThree; private JButton assignmentFour; private JButton assignmentFive; private JButton assignmentSix; private JPanel contentPane; private Evaluator ev; private ProgrammingAssignmentGUI pagui; private int userID; private JPanel emptyPanel; private JPanel emptyPanel2; //public constructor public ProgrammingAssignmentGUI(int userID, Evaluator ev){ pagui = this; this.ev = ev; this.userID = userID; this.setSize(800, 800); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); contentPane.setLayout(new GridLayout(4, 2)); assignmentOne = new JButton("Complete Introduction Assignment"); assignmentTwo = new JButton("Complete Variables Assignment"); assignmentThree = new JButton("Complete Strings Assignment"); assignmentFour = new JButton("Complete Control Statements Assignment"); assignmentFive = new JButton("Complete Loops Assignment"); assignmentSix = new JButton("Complete Arrays Assignment"); assignmentOne.setPreferredSize(new Dimension(200,100)); assignmentOne.addActionListener(new ButtonListener()); assignmentTwo.addActionListener(new ButtonListener()); assignmentThree.addActionListener(new ButtonListener()); assignmentFour.addActionListener(new ButtonListener()); assignmentFive.addActionListener(new ButtonListener()); assignmentSix.addActionListener(new ButtonListener()); emptyPanel = new JPanel(); emptyPanel.setPreferredSize(new Dimension(200,100)); emptyPanel2 = new JPanel(); emptyPanel2.setPreferredSize(new Dimension(200,100)); contentPane.add(emptyPanel); contentPane.add(emptyPanel2); contentPane.add(assignmentOne); contentPane.add(assignmentTwo); contentPane.add(assignmentThree); contentPane.add(assignmentFour); contentPane.add(assignmentFive); contentPane.add(assignmentSix); this.add(contentPane); setVisible(true); } //Method for communicating with other classes public void update(){ ev.update(); } //Event Handler public class ButtonListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if(e.getSource() == assignmentOne){ try { ProgrammingAssignmentWindow paw1 = new ProgrammingAssignmentWindow(1,userID, pagui); Thread t1 = new Thread(paw1); t1.start(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }else if(e.getSource() == assignmentTwo ){ try { ProgrammingAssignmentWindow paw2 = new ProgrammingAssignmentWindow(2,userID,pagui); Thread t2 = new Thread(paw2); t2.start(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }else if(e.getSource() == assignmentThree ){ try { ProgrammingAssignmentWindow paw3 = new ProgrammingAssignmentWindow(3,userID,pagui); Thread t3 = new Thread(paw3); t3.start(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }else if(e.getSource() == assignmentFour ){ try { ProgrammingAssignmentWindow paw4 = new ProgrammingAssignmentWindow(4,userID,pagui); Thread t4 = new Thread(paw4); t4.start(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }else if(e.getSource() == assignmentFive ){ try { ProgrammingAssignmentWindow paw5 = new ProgrammingAssignmentWindow(5,userID,pagui); Thread t5 = new Thread(paw5); t5.start(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }else if(e.getSource() == assignmentSix ){ try { ProgrammingAssignmentWindow paw6 = new ProgrammingAssignmentWindow(6,userID,pagui); Thread t6 = new Thread(paw6); t6.start(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } } }
true
29fb64021d68d058787d92d5f5df56d799f6a244
Java
moutainhigh/cnsoft
/0.1.1/src/main/java/com/ttnn/framework/ept/bean/EPTDataBean.java
UTF-8
1,279
2.296875
2
[ "BSD-3-Clause-Clear" ]
permissive
package com.ttnn.framework.ept.bean; import java.io.Serializable; import java.util.ArrayDeque; import java.util.HashMap; import com.ttnn.framework.ept.SEPTConstants; /** * Excel 读取操作,数据保存到缓存 * @since 0.1 * @version 0.1 */ public class EPTDataBean implements SEPTConstants,Serializable{ /** * */ private static final long serialVersionUID = 2542805005624834986L; /** * 操作类别(插入||更新||查询),默认插入 */ private String OperationType = OPERATION_TYPE_INSERT; /** * 操作SQLMap */ private String OperationSQLMap = ""; /** * 被操作数据(dao) */ private ArrayDeque<HashMap<String, Object>> OperationData = new ArrayDeque<HashMap<String, Object>>(20); public String getOperationType() { return OperationType; } public void setOperationType(String operationType) { OperationType = operationType; } public String getOperationSQLMap() { return OperationSQLMap; } public void setOperationSQLMap(String operationSQLMap) { OperationSQLMap = operationSQLMap; } public ArrayDeque<HashMap<String, Object>> getOperationData() { return OperationData; } public void setOperationData(ArrayDeque<HashMap<String, Object>> operationData) { OperationData = operationData; } }
true
4fe5d5b414fcab9cb26cfc96ba920e533d51a749
Java
apache/mahout
/core/src/main/java/org/apache/mahout/math/jet/stat/Gamma.java
UTF-8
16,323
2.4375
2
[ "Apache-2.0", "CPL-1.0", "GPL-2.0-or-later", "MIT", "LicenseRef-scancode-mit-old-style", "LicenseRef-scancode-public-domain", "Classpath-exception-2.0" ]
permissive
/* Copyright 1999 CERN - European Organization for Nuclear Research. Permission to use, copy, modify, distribute and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. CERN makes no representations about the suitability of this software for any purpose. It is provided "as is" without expressed or implied warranty. */ package org.apache.mahout.math.jet.stat; import org.apache.mahout.math.jet.math.Constants; import org.apache.mahout.math.jet.math.Polynomial; /** Partially deprecated until unit tests are in place. Until this time, this class/interface is unsupported. */ public final class Gamma { private static final double MAXSTIR = 143.01608; private Gamma() { } /** * Returns the beta function of the arguments. * <pre> * - - * | (a) | (b) * beta( a, b ) = -----------. * - * | (a+b) * </pre> * @param alpha * @param beta * @return The beta function for given values of alpha and beta. */ public static double beta(double alpha, double beta) { double y; if (alpha < 40 && beta < 40) { y = gamma(alpha + beta); if (y == 0.0) { return 1.0; } if (alpha > beta) { y = gamma(alpha) / y; y *= gamma(beta); } else { y = gamma(beta) / y; y *= gamma(alpha); } } else { y = Math.exp(logGamma(alpha) + logGamma(beta) - logGamma(alpha + beta)); } return y; } /** Returns the Gamma function of the argument. */ public static double gamma(double x) { double[] pCoefficient = { 1.60119522476751861407E-4, 1.19135147006586384913E-3, 1.04213797561761569935E-2, 4.76367800457137231464E-2, 2.07448227648435975150E-1, 4.94214826801497100753E-1, 9.99999999999999996796E-1 }; double[] qCoefficient = { -2.31581873324120129819E-5, 5.39605580493303397842E-4, -4.45641913851797240494E-3, 1.18139785222060435552E-2, 3.58236398605498653373E-2, -2.34591795718243348568E-1, 7.14304917030273074085E-2, 1.00000000000000000320E0 }; //double MAXGAM = 171.624376956302725; //double LOGPI = 1.14472988584940017414; double p; double z; double q = Math.abs(x); if (q > 33.0) { if (x < 0.0) { p = Math.floor(q); if (p == q) { throw new ArithmeticException("gamma: overflow"); } //int i = (int) p; z = q - p; if (z > 0.5) { p += 1.0; z = q - p; } z = q * Math.sin(Math.PI * z); if (z == 0.0) { throw new ArithmeticException("gamma: overflow"); } z = Math.abs(z); z = Math.PI / (z * stirlingFormula(q)); return -z; } else { return stirlingFormula(x); } } z = 1.0; while (x >= 3.0) { x -= 1.0; z *= x; } while (x < 0.0) { if (x == 0.0) { throw new ArithmeticException("gamma: singular"); } if (x > -1.0e-9) { return z / ((1.0 + 0.5772156649015329 * x) * x); } z /= x; x += 1.0; } while (x < 2.0) { if (x == 0.0) { throw new ArithmeticException("gamma: singular"); } if (x < 1.0e-9) { return z / ((1.0 + 0.5772156649015329 * x) * x); } z /= x; x += 1.0; } if ((x == 2.0) || (x == 3.0)) { return z; } x -= 2.0; p = Polynomial.polevl(x, pCoefficient, 6); q = Polynomial.polevl(x, qCoefficient, 7); return z * p / q; } /** * Returns the regularized Incomplete Beta Function evaluated from zero to <tt>xx</tt>; formerly named <tt>ibeta</tt>. * * See http://en.wikipedia.org/wiki/Incomplete_beta_function#Incomplete_beta_function * * @param alpha the alpha parameter of the beta distribution. * @param beta the beta parameter of the beta distribution. * @param xx the integration end point. */ public static double incompleteBeta(double alpha, double beta, double xx) { if (alpha <= 0.0) { throw new ArithmeticException("incompleteBeta: Domain error! alpha must be > 0, but was " + alpha); } if (beta <= 0.0) { throw new ArithmeticException("incompleteBeta: Domain error! beta must be > 0, but was " + beta); } if (xx <= 0.0) { return 0.0; } if (xx >= 1.0) { return 1.0; } double t; if ((beta * xx) <= 1.0 && xx <= 0.95) { t = powerSeries(alpha, beta, xx); return t; } double w = 1.0 - xx; /* Reverse a and b if x is greater than the mean. */ double xc; double x; double b; double a; boolean flag = false; if (xx > (alpha / (alpha + beta))) { flag = true; a = beta; b = alpha; xc = xx; x = w; } else { a = alpha; b = beta; xc = w; x = xx; } if (flag && (b * x) <= 1.0 && x <= 0.95) { t = powerSeries(a, b, x); t = t <= Constants.MACHEP ? 1.0 - Constants.MACHEP : 1.0 - t; return t; } /* Choose expansion for better convergence. */ double y = x * (a + b - 2.0) - (a - 1.0); w = y < 0.0 ? incompleteBetaFraction1(a, b, x) : incompleteBetaFraction2(a, b, x) / xc; /* Multiply w by the factor a b _ _ _ x (1-x) | (a+b) / ( a | (a) | (b) ) . */ y = a * Math.log(x); t = b * Math.log(xc); if ((a + b) < Constants.MAXGAM && Math.abs(y) < Constants.MAXLOG && Math.abs(t) < Constants.MAXLOG) { t = Math.pow(xc, b); t *= Math.pow(x, a); t /= a; t *= w; t *= gamma(a + b) / (gamma(a) * gamma(b)); if (flag) { t = t <= Constants.MACHEP ? 1.0 - Constants.MACHEP : 1.0 - t; } return t; } /* Resort to logarithms. */ y += t + logGamma(a + b) - logGamma(a) - logGamma(b); y += Math.log(w / a); t = y < Constants.MINLOG ? 0.0 : Math.exp(y); if (flag) { t = t <= Constants.MACHEP ? 1.0 - Constants.MACHEP : 1.0 - t; } return t; } /** Continued fraction expansion #1 for incomplete beta integral; formerly named <tt>incbcf</tt>. */ static double incompleteBetaFraction1(double a, double b, double x) { double k1 = a; double k2 = a + b; double k3 = a; double k4 = a + 1.0; double k5 = 1.0; double k6 = b - 1.0; double k7 = k4; double k8 = a + 2.0; double pkm2 = 0.0; double qkm2 = 1.0; double pkm1 = 1.0; double qkm1 = 1.0; double ans = 1.0; double r = 1.0; int n = 0; double thresh = 3.0 * Constants.MACHEP; do { double xk = -(x * k1 * k2) / (k3 * k4); double pk = pkm1 + pkm2 * xk; double qk = qkm1 + qkm2 * xk; pkm2 = pkm1; pkm1 = pk; qkm2 = qkm1; qkm1 = qk; xk = (x * k5 * k6) / (k7 * k8); pk = pkm1 + pkm2 * xk; qk = qkm1 + qkm2 * xk; pkm2 = pkm1; pkm1 = pk; qkm2 = qkm1; qkm1 = qk; if (qk != 0) { r = pk / qk; } double t; if (r != 0) { t = Math.abs((ans - r) / r); ans = r; } else { t = 1.0; } if (t < thresh) { return ans; } k1 += 1.0; k2 += 1.0; k3 += 2.0; k4 += 2.0; k5 += 1.0; k6 -= 1.0; k7 += 2.0; k8 += 2.0; if ((Math.abs(qk) + Math.abs(pk)) > Constants.BIG) { pkm2 *= Constants.BIG_INVERSE; pkm1 *= Constants.BIG_INVERSE; qkm2 *= Constants.BIG_INVERSE; qkm1 *= Constants.BIG_INVERSE; } if ((Math.abs(qk) < Constants.BIG_INVERSE) || (Math.abs(pk) < Constants.BIG_INVERSE)) { pkm2 *= Constants.BIG; pkm1 *= Constants.BIG; qkm2 *= Constants.BIG; qkm1 *= Constants.BIG; } } while (++n < 300); return ans; } /** Continued fraction expansion #2 for incomplete beta integral; formerly named <tt>incbd</tt>. */ static double incompleteBetaFraction2(double a, double b, double x) { double k1 = a; double k2 = b - 1.0; double k3 = a; double k4 = a + 1.0; double k5 = 1.0; double k6 = a + b; double k7 = a + 1.0; double k8 = a + 2.0; double pkm2 = 0.0; double qkm2 = 1.0; double pkm1 = 1.0; double qkm1 = 1.0; double z = x / (1.0 - x); double ans = 1.0; double r = 1.0; int n = 0; double thresh = 3.0 * Constants.MACHEP; do { double xk = -(z * k1 * k2) / (k3 * k4); double pk = pkm1 + pkm2 * xk; double qk = qkm1 + qkm2 * xk; pkm2 = pkm1; pkm1 = pk; qkm2 = qkm1; qkm1 = qk; xk = (z * k5 * k6) / (k7 * k8); pk = pkm1 + pkm2 * xk; qk = qkm1 + qkm2 * xk; pkm2 = pkm1; pkm1 = pk; qkm2 = qkm1; qkm1 = qk; if (qk != 0) { r = pk / qk; } double t; if (r != 0) { t = Math.abs((ans - r) / r); ans = r; } else { t = 1.0; } if (t < thresh) { return ans; } k1 += 1.0; k2 -= 1.0; k3 += 2.0; k4 += 2.0; k5 += 1.0; k6 += 1.0; k7 += 2.0; k8 += 2.0; if ((Math.abs(qk) + Math.abs(pk)) > Constants.BIG) { pkm2 *= Constants.BIG_INVERSE; pkm1 *= Constants.BIG_INVERSE; qkm2 *= Constants.BIG_INVERSE; qkm1 *= Constants.BIG_INVERSE; } if ((Math.abs(qk) < Constants.BIG_INVERSE) || (Math.abs(pk) < Constants.BIG_INVERSE)) { pkm2 *= Constants.BIG; pkm1 *= Constants.BIG; qkm2 *= Constants.BIG; qkm1 *= Constants.BIG; } } while (++n < 300); return ans; } /** * Returns the Incomplete Gamma function; formerly named <tt>igamma</tt>. * * @param alpha the shape parameter of the gamma distribution. * @param x the integration end point. * @return The value of the unnormalized incomplete gamma function. */ public static double incompleteGamma(double alpha, double x) { if (x <= 0 || alpha <= 0) { return 0.0; } if (x > 1.0 && x > alpha) { return 1.0 - incompleteGammaComplement(alpha, x); } /* Compute x**a * exp(-x) / gamma(a) */ double ax = alpha * Math.log(x) - x - logGamma(alpha); if (ax < -Constants.MAXLOG) { return 0.0; } ax = Math.exp(ax); /* power series */ double r = alpha; double c = 1.0; double ans = 1.0; do { r += 1.0; c *= x / r; ans += c; } while (c / ans > Constants.MACHEP); return ans * ax / alpha; } /** * Returns the Complemented Incomplete Gamma function; formerly named <tt>igamc</tt>. * * @param alpha the shape parameter of the gamma distribution. * @param x the integration start point. */ public static double incompleteGammaComplement(double alpha, double x) { if (x <= 0 || alpha <= 0) { return 1.0; } if (x < 1.0 || x < alpha) { return 1.0 - incompleteGamma(alpha, x); } double ax = alpha * Math.log(x) - x - logGamma(alpha); if (ax < -Constants.MAXLOG) { return 0.0; } ax = Math.exp(ax); /* continued fraction */ double y = 1.0 - alpha; double z = x + y + 1.0; double c = 0.0; double pkm2 = 1.0; double qkm2 = x; double pkm1 = x + 1.0; double qkm1 = z * x; double ans = pkm1 / qkm1; double t; do { c += 1.0; y += 1.0; z += 2.0; double yc = y * c; double pk = pkm1 * z - pkm2 * yc; double qk = qkm1 * z - qkm2 * yc; if (qk != 0) { double r = pk / qk; t = Math.abs((ans - r) / r); ans = r; } else { t = 1.0; } pkm2 = pkm1; pkm1 = pk; qkm2 = qkm1; qkm1 = qk; if (Math.abs(pk) > Constants.BIG) { pkm2 *= Constants.BIG_INVERSE; pkm1 *= Constants.BIG_INVERSE; qkm2 *= Constants.BIG_INVERSE; qkm1 *= Constants.BIG_INVERSE; } } while (t > Constants.MACHEP); return ans * ax; } /** Returns the natural logarithm of the gamma function; formerly named <tt>lgamma</tt>. */ public static double logGamma(double x) { double p; double q; double z; double[] aCoefficient = { 8.11614167470508450300E-4, -5.95061904284301438324E-4, 7.93650340457716943945E-4, -2.77777777730099687205E-3, 8.33333333333331927722E-2 }; double[] bCoefficient = { -1.37825152569120859100E3, -3.88016315134637840924E4, -3.31612992738871184744E5, -1.16237097492762307383E6, -1.72173700820839662146E6, -8.53555664245765465627E5 }; double[] cCoefficient = { /* 1.00000000000000000000E0, */ -3.51815701436523470549E2, -1.70642106651881159223E4, -2.20528590553854454839E5, -1.13933444367982507207E6, -2.53252307177582951285E6, -2.01889141433532773231E6 }; if (x < -34.0) { q = -x; double w = logGamma(q); p = Math.floor(q); if (p == q) { throw new ArithmeticException("lgam: Overflow"); } z = q - p; if (z > 0.5) { p += 1.0; z = p - q; } z = q * Math.sin(Math.PI * z); if (z == 0.0) { throw new ArithmeticException("lgamma: Overflow"); } z = Constants.LOGPI - Math.log(z) - w; return z; } if (x < 13.0) { z = 1.0; while (x >= 3.0) { x -= 1.0; z *= x; } while (x < 2.0) { if (x == 0.0) { throw new ArithmeticException("lgamma: Overflow"); } z /= x; x += 1.0; } if (z < 0.0) { z = -z; } if (x == 2.0) { return Math.log(z); } x -= 2.0; p = x * Polynomial.polevl(x, bCoefficient, 5) / Polynomial.p1evl(x, cCoefficient, 6); return Math.log(z) + p; } if (x > 2.556348e305) { throw new ArithmeticException("lgamma: Overflow"); } q = (x - 0.5) * Math.log(x) - x + 0.91893853320467274178; //if ( x > 1.0e8 ) return( q ); if (x > 1.0e8) { return q; } p = 1.0 / (x * x); if (x >= 1000.0) { q += ((7.9365079365079365079365e-4 * p - 2.7777777777777777777778e-3) * p + 0.0833333333333333333333) / x; } else { q += Polynomial.polevl(p, aCoefficient, 4) / x; } return q; } /** * Power series for incomplete beta integral; formerly named <tt>pseries</tt>. Use when b*x is small and x not too * close to 1. */ private static double powerSeries(double a, double b, double x) { double ai = 1.0 / a; double u = (1.0 - b) * x; double v = u / (a + 1.0); double t1 = v; double t = u; double n = 2.0; double s = 0.0; double z = Constants.MACHEP * ai; while (Math.abs(v) > z) { u = (n - b) * x / n; t *= u; v = t / (a + n); s += v; n += 1.0; } s += t1; s += ai; u = a * Math.log(x); if ((a + b) < Constants.MAXGAM && Math.abs(u) < Constants.MAXLOG) { t = gamma(a + b) / (gamma(a) * gamma(b)); s *= t * Math.pow(x, a); } else { t = logGamma(a + b) - logGamma(a) - logGamma(b) + u + Math.log(s); s = t < Constants.MINLOG ? 0.0 : Math.exp(t); } return s; } /** * Returns the Gamma function computed by Stirling's formula; formerly named <tt>stirf</tt>. The polynomial STIR is * valid for 33 <= x <= 172. */ static double stirlingFormula(double x) { double[] coefficients = { 7.87311395793093628397E-4, -2.29549961613378126380E-4, -2.68132617805781232825E-3, 3.47222221605458667310E-3, 8.33333333333482257126E-2, }; double w = 1.0 / x; double y = Math.exp(x); w = 1.0 + w * Polynomial.polevl(w, coefficients, 4); if (x > MAXSTIR) { /* Avoid overflow in Math.pow() */ double v = Math.pow(x, 0.5 * x - 0.25); y = v * (v / y); } else { y = Math.pow(x, x - 0.5) / y; } y = Constants.SQTPI * y * w; return y; } }
true
f8986faaba7ee135339cee073afd6b14bb25f7c0
Java
ArthurAttout/KlarHopur
/app/src/main/java/be/klarhopur/prom/DistancePathActivity.java
UTF-8
12,065
1.625
2
[ "Unlicense" ]
permissive
package be.klarhopur.prom; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.support.design.widget.BottomSheetBehavior; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.SearchView; import android.widget.TextView; import android.widget.Toast; import com.akexorcist.googledirection.model.Direction; import com.akexorcist.googledirection.model.Leg; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.PolylineOptions; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; public class DistancePathActivity extends AppCompatActivity implements OnMapReadyCallback, LocationListener { private BottomSheetBehavior mBottomSheetBehavior; private TextView textViewTime; private ImageView backArrow; private TextView textViewDistance; private EditText distanceEditText; private TextView textViewViaPOI; private GoogleMap mMap; private RecyclerView recyclerViewPOI; private Location lastKnownLocation; private LocationManager locationManager; private Direction direction; private ArrayList<PointOfInterest> pointsOfInterest; private LatLng origin; private LatLng destination; private double totalDistanceMeters; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getSupportActionBar().hide(); setContentView(R.layout.activity_distance_path); View bottomSheet = findViewById( R.id.bottom_sheet ); FloatingActionButton button = findViewById( R.id.prom_floatingActionButton ); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(direction == null || pointsOfInterest == null || origin == null || destination == null) return; Intent intent = new Intent(getBaseContext(), UserWalkMapActivity.class); Bundle b = new Bundle(); b.putParcelable("origin",origin); b.putParcelable("destination",destination); b.putString("polyline",direction.getRouteList().get(0).getOverviewPolyline().getRawPointList()); b.putParcelableArrayList("pointsOfInterest",pointsOfInterest); b.putParcelable("direction",direction); b.putDouble("length",totalDistanceMeters); intent.putExtras(b); startActivity(intent); } }); mBottomSheetBehavior = BottomSheetBehavior.from(bottomSheet); mBottomSheetBehavior.setPeekHeight(300); // 0 if you don't want to show the bottom sheet on the starting activity. mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED); textViewTime = findViewById(R.id.bottom_time_text_view); recyclerViewPOI = findViewById(R.id.recyclerViewPOI); backArrow = findViewById(R.id.back_arrow); textViewDistance = findViewById(R.id.bottom_distance_text_view); textViewViaPOI = findViewById(R.id.bottom_via_poi_text_view); textViewDistance = findViewById(R.id.bottom_distance_text_view); distanceEditText = findViewById(R.id.distance_search_bar); backArrow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this); } final boolean[] addedSuffix = {false}; final String SUFFIX = " km"; distanceEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {} @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // if the only text is the suffix if(s.toString().equals(SUFFIX)){ distanceEditText.setText(""); // clear the text return; } // If there is text append on SUFFIX as long as it is not there // move cursor back before the suffix if(s.length() > 0 && !s.toString().contains(SUFFIX) && !s.toString().equals(SUFFIX)){ String text = s.toString().concat(SUFFIX); distanceEditText.setText(text); distanceEditText.setSelection(text.length() - SUFFIX.length()); addedSuffix[0] = true; // flip the addedSuffix flag to true } } @Override public void afterTextChanged(Editable s) { if(s.length() == 0){ addedSuffix[0] = false; // reset the addedSuffix flag } } }); distanceEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @SuppressLint("MissingPermission") @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { String query = String.valueOf(distanceEditText.getText()); if(query.equals("")) return true; double value = Double.valueOf(query.substring(0,query.length()-3)); //remove suffix if(value > 30){ Toast.makeText(DistancePathActivity.this, "Cette distance n'est pas supportée", Toast.LENGTH_SHORT).show(); return true; } lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); LatLng currentLatLng = lastKnownLocation == null ? new LatLng(50.224812, 5.344703) : new LatLng(lastKnownLocation.getLatitude(),lastKnownLocation.getLongitude()); Utils.getRouteForDistance(currentLatLng,value*1000, new Utils.PathComputedCallback() { @Override public void onPathComputed(Direction direction, List<PointOfInterest> pointsOfInterests, LatLng origin, LatLng destination) { PolylineOptions options = new PolylineOptions(); options.addAll(Utils.decodePoly(direction.getRouteList().get(0).getOverviewPolyline().getRawPointList())); mMap.addPolyline(options); updateViews(direction,pointsOfInterests,origin,destination); } }); InputMethodManager inputManager = (InputMethodManager) DistancePathActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.hideSoftInputFromWindow( DistancePathActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); return true; } }); } private void updateViews(Direction direction, List<PointOfInterest> pointsOfInterests, LatLng origin, LatLng destination) { this.direction = direction; this.pointsOfInterest = new ArrayList<>(pointsOfInterests); this.origin = origin; this.destination = destination; mMap.addMarker(new MarkerOptions() .title("Départ") .position(origin)); for (PointOfInterest pointOfInterest : pointsOfInterests) { mMap.addMarker(new MarkerOptions() .title(pointsOfInterests.indexOf(pointOfInterest)+1 + " - " + pointOfInterest.getName()) .position(pointOfInterest.getLatLng())); } mMap.addMarker(new MarkerOptions() .title("Arrivée") .position(destination) .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))); int totalSeconds = 0; totalDistanceMeters = 0; for (Leg leg : direction.getRouteList().get(0).getLegList()) { totalSeconds += Integer.parseInt(leg.getDuration().getValue()); totalDistanceMeters += Integer.parseInt(leg.getDistance().getValue()); } String outTime; if(totalSeconds < 3600){ outTime = String.format("%d min", TimeUnit.SECONDS.toMinutes(totalSeconds) ); } else { outTime = String.format("%d h, %d min", TimeUnit.SECONDS.toHours(totalSeconds), TimeUnit.SECONDS.toMinutes(totalSeconds) - TimeUnit.HOURS.toMinutes(TimeUnit.SECONDS.toHours(totalSeconds)) ); } textViewTime.setText(outTime); String outDistance; if(totalDistanceMeters > 1000){ outDistance = totalDistanceMeters/1000 + "km"; } else { outDistance = totalDistanceMeters + "m"; } textViewDistance.setText(outDistance); textViewViaPOI.setText(String.format("via %d points d'intérêt", pointsOfInterests.size())); recyclerViewPOI.setLayoutManager(new LinearLayoutManager(this)); recyclerViewPOI.setAdapter(new POIAdapter(new ArrayList<>(pointsOfInterests))); } @Override public void onLocationChanged(Location location) { LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 14); if(mMap != null) mMap.animateCamera(cameraUpdate); locationManager.removeUpdates(this); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } @SuppressLint("MissingPermission") @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if(lastKnownLocation != null) onLocationChanged(lastKnownLocation); } }
true
24c1b6b87577dabf77ab0ebd277ed899e74f9de6
Java
deshani18/connect4
/src/deshani_sritharan/Board.java
UTF-8
1,608
3.15625
3
[]
no_license
package deshani_sritharan; public class Board { private Cell[][] board; private int maxRow; private int maxCol; Board (int ROWS, int COLS){ maxRow = ROWS; maxCol = COLS; board = new Cell[ROWS][COLS]; for (int i=0; i<ROWS;i++){ for(int j=0;j<COLS;j++){ board[i][j]= new Cell(); } } } public int currentPlayer(int i){ if(i%2==0){ return 1; }else{ return 2; } } public void display(){ for (int i=0; i<maxRow;i++){ for(int j=0;j<maxCol;j++){ if (board[i][j].getState()==CellState.EMPTY){ System.out.print(" - "); } else if (board[i][j].getState()==CellState.PLAYER1){ System.out.print(" X "); } else System.out.print(" O "); } System.out.println(""); } } public boolean isColumnFull(int column){ return board[0][column].getState()!=CellState.EMPTY; } public int getRowLocation(int column){ boolean found = false; int rowPosition = maxRow-1; while (!found){ if (board[rowPosition][column].getState()==CellState.EMPTY){ found=true; }else{ rowPosition--; } }return rowPosition; } public void update(CellState currentPlayer, int row, int col){ board[row][col].setState(currentPlayer); } public boolean checkWinner(CellState currentPlayer,int row, int col){ boolean winner = false; int rowPosition = row; while (!winner){ if (board[rowPosition][col].getState()==CellState.EMPTY){ winner=true; }else{ rowPosition--; } }return false; } }
true
08195989756671556ad4f1bb09617a637c81b999
Java
dkekel/demo-spring
/src/main/java/ch/cern/springcampus/demospring/bean/User.java
UTF-8
1,620
2.46875
2
[]
no_license
package ch.cern.springcampus.demospring.bean; import org.hibernate.validator.constraints.Length; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import javax.persistence.Entity; import javax.persistence.Id; import java.util.Collection; import java.util.Objects; @Entity public class User implements UserDetails { @Id @Length(min = 4, max = 16) private String username; private String password; @Override public Collection<? extends GrantedAuthority> getAuthorities() { return null; } @Override public String getPassword() { return password; } public void setPassword(final String password) { this.password = password; } @Override public String getUsername() { return username; } public void setUsername(final String username) { this.username = username; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; return username.equals(user.username); } @Override public int hashCode() { return Objects.hash(username); } }
true
e2565c994869d3d3a5f2281c4c431d783ee9bdbf
Java
Atayev89/Odevler
/Gun1Odev2/src/odev2ders8.java
UTF-8
284
2.953125
3
[]
no_license
public class odev2ders8 { public static void main(String[] args) { int sayi = 19; if(sayi<20) { System.out.println("Sayi 20 den kucukdur"); }else if(sayi>20) { System.out.println("Sayi 20 den buyukdur"); }else { System.out.println("Sayi 20 ye esitdir"); } } }
true
a2c8fb3074db565dcf5490cdeaddedbaba5daa8c
Java
intesar/MySQL-Perf1
/src/main/java/com/bia/mysqldemo1/MySQLDemo.java
UTF-8
2,578
2.734375
3
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.bia.mysqldemo1; import java.util.Date; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; /** * * @author intesar */ public class MySQLDemo { /** * @param args the command line arguments * * inserts : 50, time : 1662 inserts : 100, time : 1643 inserts : 200, time * : 1926 inserts : 500, time : 2778 inserts : 1000, time : 4611 * * gets : 50, time : 1329 gets : 100, time : 1349 gets : 200, time : 1592 * gets : 500, time : 1702 gets : 1000, time : 2197 * */ public static void main(String[] args) { // TODO code application logic here //runGet (example, bucket, 10000); runSet(50); runSet(100); runSet(200); runSet(500); runSet(1000); runGet(50); runGet(100); runGet(200); runGet(500); runGet(1000); } public static void runSet(int max) { long st = new Date().getTime(); int i = 0; for (; i < max; i++) { persist(new NewTable("apple", "apple")); } long et = new Date().getTime(); System.out.println(" inserts : " + i + ", time : " + (et - st)); } public static void runGet(int max) { long st = new Date().getTime(); int i = 0; for (; i < max; i++) { load(i); } long et = new Date().getTime(); System.out.println(" gets : " + i + ", time : " + (et - st)); } static EntityManagerFactory emf = Persistence.createEntityManagerFactory("com.bia_MysqlDemo1_jar_1.0-SNAPSHOTPU"); public static void persist(Object object) { EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); try { em.persist(object); em.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); em.getTransaction().rollback(); } finally { em.close(); } } public static void load(int i) { EntityManager em = emf.createEntityManager(); //em.getTransaction().begin(); try { em.find(NewTable.class, i); //em.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); em.getTransaction().rollback(); } finally { em.close(); } } }
true
7e8a319d853b80e7ada718bdefcad2b7d178731c
Java
MeghaGajbhiye/BudgetApp-Megha-master
/app/src/main/java/com/example/meghagajbhiye/budgetcare_megha/Earnings.java
UTF-8
5,675
2.1875
2
[]
no_license
package com.example.meghagajbhiye.budgetcare_megha; import android.app.DatePickerDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.text.Editable; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ImageButton; import android.widget.Spinner; import android.widget.Toast; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class Earnings extends FragmentActivity { Date currentDate = new Date(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); String DateToString = dateFormat.format(currentDate); EditText eDate; private EditText eAmount; //private EditText eNote; private Spinner categorySpinner; private Button saveBtn; private TransactionDA transactionDA; ImageButton addBut; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_earnings); eDate = (EditText) findViewById(R.id.date); eDate.setText(DateToString); addBut= (ImageButton) findViewById(R.id.imageButton2); categorySpinner = (Spinner) findViewById(R.id.categoryspinner); eAmount =(EditText) findViewById(R.id.amount); //eNote = (EditText) findViewById(R.id.notes); saveBtn = (Button) findViewById(R.id.savebutton); this.transactionDA=new TransactionDA(this); // fillCategorySpinner(); } //Method to show a new intent when a button is pressed public void showAddCategory(View v){ Intent i; i=new Intent(Earnings.this,AddCategory.class); startActivity(i); } @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_cash_in, 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); } public void showDatePickerDialog(View v) { DialogFragment newFragment = new DatePickerFragment(); newFragment.show(getFragmentManager(), "datePicker"); //newFragment.show(getSupportFragmentManager(), "datePicker"); //setNewDate(); } public void populateSetDate(int year, int month, int day) { eDate = (EditText) findViewById(R.id.date); eDate.setText(year + "-" + (month + 1) + "-" + day); } //Method which run when save button is pressed //Insert data to the database public void onClickSave(View v) { try { Editable date = eDate.getText(); String category = (String) categorySpinner.getSelectedItem(); //Editable amount = (Float) eAmount.getText(); float amount = Float.valueOf(eAmount.getText().toString()); //Editable note = eNote.getText(); if(amount<=0){ Toast.makeText(Earnings.this, "Please enter the amount", Toast.LENGTH_SHORT).show(); }else { // add the transaction to database Transaction createdTransaction = transactionDA.createTransaction(date.toString(), "Earnings", category, amount); Toast.makeText(Earnings.this, "Successfully Saved", Toast.LENGTH_SHORT).show(); transactionDA.close(); Intent i; i=new Intent(Earnings.this,BudgetCareHome.class); startActivity(i); } }catch(Exception ex){ Toast.makeText(Earnings.this, "Error while saving.", Toast.LENGTH_SHORT).show(); } } public void showToast(View v){ float amount=0; amount = Float.valueOf(eAmount.getText().toString()); if(amount<=0){ Toast.makeText(Earnings.this, "Please enter the amount", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(Earnings.this, "Successfully Saved", Toast.LENGTH_LONG).show(); Intent i; i=new Intent(Earnings.this,BudgetCareHome.class); startActivity(i); } } public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener { public DatePickerFragment() { } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Use the current date as the default date in the picker final Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH); int day = c.get(Calendar.DAY_OF_MONTH); // Create a new instance of DatePickerDialog and return it return new DatePickerDialog(getActivity(), this, year, month, day); } public void onDateSet(DatePicker view, int year, int month, int day) { // Do something with the date chosen by the user populateSetDate(year,month,day); } } }
true
b8d85bc9e6999693bc180d9f8879f5b0875259af
Java
IlyaFX/gammacases
/src/main/java/ru/ilyafx/gammacases/util/NBTUtil.java
UTF-8
923
2.453125
2
[]
no_license
package ru.ilyafx.gammacases.util; import lombok.experimental.UtilityClass; import net.minecraft.server.v1_13_R2.NBTTagCompound; import org.bukkit.craftbukkit.v1_13_R2.inventory.CraftItemStack; @UtilityClass public class NBTUtil { public org.bukkit.inventory.ItemStack writeNBT(org.bukkit.inventory.ItemStack item, String key, String val) { net.minecraft.server.v1_13_R2.ItemStack i = CraftItemStack.asNMSCopy(item); NBTTagCompound comp = (i.getTag() != null ? i.getTag() : new NBTTagCompound()); comp.setString(key, val); i.setTag(comp); return CraftItemStack.asBukkitCopy(i); } public String readNBT(org.bukkit.inventory.ItemStack item, String key) { net.minecraft.server.v1_13_R2.ItemStack i = CraftItemStack.asNMSCopy(item); return (i.getTag() != null && i.getTag().hasKey(key) ? i.getTag().getString(key) : null); } }
true
76b202b11b930f9a585b269423938c05a5a392cc
Java
IHTSDO/snomed-release-service
/src/main/java/org/ihtsdo/buildcloud/core/entity/helper/TestEntityGenerator.java
UTF-8
1,276
2.25
2
[ "Apache-2.0" ]
permissive
package org.ihtsdo.buildcloud.core.entity.helper; import org.ihtsdo.buildcloud.core.entity.Product; import org.ihtsdo.buildcloud.core.entity.ReleaseCenter; public class TestEntityGenerator { public static final String [] releaseCenterNames = {"International Release Center"}; public static final String [] releaseCenterShortNames = {"International"}; public static final String [] productNames = {"SNOMED CT Release", "NLM Example Refset", "Medical Devices Technical Preview", "GP/FP Refset Technical Preview", "LOINC Expressions Technical Preview", "ICPC2 Map Technical Preview", "Spanish Release"}; protected ReleaseCenter createTestReleaseCenter(String fullName, String shortName, String codeSystem) { return new ReleaseCenter(fullName, shortName, codeSystem); } protected ReleaseCenter createTestReleaseCenterWithProducts(String fullName, String shortName, String codeSystem) { ReleaseCenter releaseCenter = createTestReleaseCenter(fullName, shortName, codeSystem); addProductsToReleaseCenter(releaseCenter); return releaseCenter; } protected void addProductsToReleaseCenter(ReleaseCenter releaseCenter) { for (String productName : productNames) { releaseCenter.addProduct(new Product(productName)); } } }
true
c9080652617086fe2bb93f0775b1e7653eeaf227
Java
maxstrauch/vote-javaee
/vote-war/src/java/de/vote/web/filter/JumpToIndexFilter.java
UTF-8
3,059
2.609375
3
[ "MIT" ]
permissive
package de.vote.web.filter; import de.vote.web.ParticipateBean; import java.io.IOException; import javax.inject.Inject; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * This filter is generally responsible for the frontend and has two specific * tasks: * <ol> * <li>iff the index page is displayed and a token is submitted, this * filter is responsible for transfering the token value to the token field * of the {@link ParticipateBean}.</li> * <li>it prevents the view of the pages vote or thank-you if no poll is * set or was actually finished.</li> * </ol> * * @author Daniel Vivas Estevao * @author maximilianstrauch */ public class JumpToIndexFilter implements Filter { @Inject private ParticipateBean participateBean; @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // If there is no instance of ParticipateBean if (participateBean == null) { chain.doFilter(request, response); return; } HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; String page = getRequestedPage(req); // Inject the value of the variable input field on the index page // into the participate backing bean if ("index".equals(page)) { // Find the right key for (String key : req.getParameterMap().keySet()) { if (key.matches(".*t0kEn.*")) { participateBean.setToken(req.getParameter(key)); break; } } } // Check if there is a direct call of pages if ( // Page "vote.xhtml" ("vote".equals(page) && participateBean.getPollTO() == null) || // Page "thankyou.xhtml" ("thankyou".equals(page) && !participateBean.isHasParticipated()) ) { resp.sendRedirect(req.getContextPath() + "/index.xhtml"); return; } // Otherwise everything is fine and the next filter can be called ... chain.doFilter(request, response); } @Override public void destroy() { } public static final String getRequestedPage(HttpServletRequest request) { String uri = request.getRequestURI(); // If a XHTML page is requested, return its name if (uri.endsWith(".xhtml")) { return uri.substring(uri.lastIndexOf('/') + 1, uri.length() - 6); } // Otherwise return an empty string return ""; } }
true
18ed1b79208d774109ad283c1bff943289c9f6d4
Java
Turistforeningen/hyttebooking
/app/models/LargeCabin.java
UTF-8
3,412
2.75
3
[ "MIT" ]
permissive
package models; import java.util.ArrayList; import java.util.List; import javax.persistence.*; import org.joda.time.DateTime; import play.data.validation.Constraints; @Entity @DiscriminatorValue("LARGE_CABIN") public class LargeCabin extends Cabin { @Constraints.Required @OneToMany(mappedBy="largeCabin", cascade = CascadeType.ALL, orphanRemoval=true) public List<Bed> beds; @ManyToMany public List<Price> priceMatrix = new ArrayList<Price>(); /** TODO add Constraints.Required right here**/ /** * * @param name * @param nrOfBeds */ public LargeCabin(String name, int nrOfBeds) { super(name); for(int i= 0; i<nrOfBeds; i++) { addBed(); } } /** * Admin method */ public void addBed() { if (beds == null) { beds = new ArrayList<Bed>(); } Bed newBed = new Bed(); newBed.largeCabin = this; beds.add(newBed); newBed.save(); } /** * Book a large cabin, supply number of beds and fromDate to toDate. * @param numberOfBeds * @param fromDate * @param toDate * @return null if availBeds.size() < numberOfBeds, else availBeds */ public List<Bed> book(int numberOfBeds, DateTime fromDate, DateTime toDate) { if(numberOfBeds < 0 || !utilities.DateHelper.valid(fromDate, toDate)) return null; ArrayList<Bed> availBeds = new ArrayList<Bed>(); /** Consider using auto-sorted collection **/ for(Bed b: beds) { if(b.isAvailable(fromDate, toDate)) availBeds.add(b); } if(availBeds.size() < numberOfBeds) return null; return availBeds.subList(0, numberOfBeds); } /** * Admin method */ public void removeBed() { if (beds.size() <= 1) { return; } //add support for removing a specific bed Bed b = beds.remove(0); b.delete(); } @Override public String getcabinType() { return "large"; } @Override public String getNrOfBeds() { return this.beds.size() +""; } @Override public int getNrActiveBookings() { return Booking.find .where() .eq("beds.largeCabin", this) .gt("dateFrom", DateTime.now()) .lt("status", Booking.CANCELLED) .findRowCount(); } /** * * @param guestType CANNOT be null or empty * @param ageRange Can be null, but cannot be empty * @param nonMemberPrice Cannot be negative * @param memberPrice Cannot be negative */ public void addPrice(String guestType, String ageRange, double nonMemberPrice, double memberPrice, boolean isMinor) { if(nonMemberPrice < 0 || memberPrice < 0 || guestType == null || guestType.length() == 0) return; if(ageRange != null) if(ageRange.length() == 0) return; Price price = new Price(guestType, ageRange, nonMemberPrice, memberPrice, isMinor); price.save(); this.priceMatrix.add(price); } @Override public String getCabinUrl() { return this.id + "?type=large&beds=" + this.getNrOfBeds(); } @Override public boolean removePriceFromCabin(Long priceId) { Price p = Price.find.byId(priceId); System.out.println("before: " + this.priceMatrix.size()); boolean isRemoved = this.priceMatrix.remove(p); System.out.println("before: " + this.priceMatrix.size()); this.update(); return isRemoved; } @Override public void addPriceFromCabin(Price price) { this.priceMatrix.add(price); this.update(); } }
true
c31732fc2b3244050705cdca72fbc912e9568356
Java
hrndz24/natalie-co
/src/natalie/gui/MyMouseListener.java
UTF-8
1,210
3.03125
3
[]
no_license
package natalie.gui; import javax.swing.text.JTextComponent; import java.awt.*; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; public class MyMouseListener implements MouseListener { @Override public void mouseClicked(MouseEvent e) { // clears the field if there is default text JTextComponent component = (JTextComponent) e.getSource(); component.setFocusable(true); if (component.getName().equals(component.getText())) { component.setText(""); } component.setBackground(Color.WHITE); } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { // shows cursor on the field JTextComponent component = (JTextComponent) e.getSource(); component.setFocusable(true); } @Override public void mouseExited(MouseEvent e) { JTextComponent component = (JTextComponent) e.getSource(); if (component.getText().equals("")) { component.setText(component.getName()); } component.setFocusable(false); } }
true
eea4497ee04dd2e8b7b80b22d9b21fbfeb118971
Java
dredhorse/DeathTpPlus
/src/main/java/org/simiancage/DeathTpPlus/teleport/persistence/DeathLocationDao.java
UTF-8
3,773
2.71875
3
[]
no_license
package org.simiancage.DeathTpPlus.teleport.persistence; import org.bukkit.Bukkit; import org.simiancage.DeathTpPlus.DeathTpPlus; import org.simiancage.DeathTpPlus.commons.DefaultLogger; import org.simiancage.DeathTpPlus.death.DeathDetail; import java.io.*; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; /** * PluginName: DeathTpPlus * Class: DeathLocationDao * User: DonRedhorse * Date: 25.11.11 * Time: 19:25 */ public class DeathLocationDao implements Runnable { private static final String LOCATION_LOG_FILE = "locs.txt"; private static final DefaultLogger log = DefaultLogger.getLogger(); private static final String CHARSET = "UTF-8"; private static final long SAVE_DELAY = 2 * (60 * 20); // 2 minutes private static final long SAVE_PERIOD = 3 * (60 * 20); // 3 minutes private Map<String, DeathLocation> deathLocations; private String dataFolder; private File deathLocationLogFile; public DeathLocationDao(DeathTpPlus plugin) { deathLocations = new Hashtable<String, DeathLocation>(); dataFolder = plugin.getDataFolder() + System.getProperty("file.separator"); deathLocationLogFile = new File(dataFolder, LOCATION_LOG_FILE); if (!deathLocationLogFile.exists()) { try { deathLocationLogFile.createNewFile(); } catch (IOException e) { log.severe("Failed to create death location log: " + e.toString()); } } load(); Bukkit.getScheduler().runTaskTimerAsynchronously(plugin, this, SAVE_DELAY, SAVE_PERIOD); } private void load() { int counter = 0; try { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(deathLocationLogFile), CHARSET)); String line = null; while ((line = bufferedReader.readLine()) != null) { log.debug("DeathLocation: ",line); ++counter; DeathLocation deathLocation = new DeathLocation(line); deathLocations.put(deathLocation.getPlayerName(), deathLocation); } bufferedReader.close(); log.debug(counter + " DeathLocations loaded"); } catch (IOException e) { log.severe("Failed to read death location log: " + e.toString()); } } public synchronized void save() { try { BufferedWriter deathLocationLogWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(deathLocationLogFile), CHARSET)); for (DeathLocation deathLocation : deathLocations.values()) { log.debug("Deathlocation: ",deathLocation.toString()); deathLocationLogWriter.write(deathLocation.toString()); deathLocationLogWriter.newLine(); } deathLocationLogWriter.close(); } catch (IOException e) { log.severe("Failed to write death location log: " + e.toString()); } } public DeathLocation getRecord(String playerName) { return deathLocations.get(playerName); } public HashMap<Integer, DeathLocation> getAllRecords() { int i = 0; HashMap<Integer, DeathLocation> deathLocationRecordList = new HashMap<Integer, DeathLocation>(); for (DeathLocation record : deathLocations.values()) { deathLocationRecordList.put(i, record); } return deathLocationRecordList; } public void setRecord(DeathDetail deathDetail) { deathLocations.put(deathDetail.getPlayer().getName(), new DeathLocation(deathDetail.getPlayer())); } @Override public void run() { save(); } }
true
2767f0f641b0321a8c559d4017b67b7f85915db2
Java
RobertoKennedy/Eclipse.POO.AplicacaoBD
/src/testes/Teste.java
UTF-8
750
2.578125
3
[]
no_license
package testes; import java.sql.SQLException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import entidades.Drone; import persistencia.AutonomoSQLDAO; public class Teste { public void run() throws Exception { Drone novo = new Drone("teste", 0,0,0); AutonomoSQLDAO teste = new AutonomoSQLDAO(); teste.inserir(novo); }; public void run2() throws Exception { AutonomoSQLDAO teste1 = new AutonomoSQLDAO(); teste1.buscar(); }; public static void main(String[] args) throws Exception, SQLException, ClassNotFoundException { (new Teste()).run2(); System.out.println("Finalizando..."); } }
true
4fa7b9249824c72450de279b4b95a09c3710bc22
Java
BilgeSakal/TET_BE
/src/main/java/tetris/TetrisConstants.java
UTF-8
307
2.5625
3
[]
no_license
package tetris; import java.awt.Color; import java.awt.Dimension; public interface TetrisConstants { public Color EMPTY_TILE_COLOR = Color.WHITE; public Dimension MIN_TILE_DIMENSION = new Dimension(30, 30); public int HORIZONTAL_TILE_COUNT = 8; public int VERTICAL_TILE_COUNT = 20; }
true
dcc99e8c73c3ef20f090d860bf4ea588f207e3f9
Java
cesardanielntt/cx-academy
/spring/teilor/src/main/java/com/nttdata/spring/cxacademy/model/AddressModel.java
UTF-8
1,675
2.5
2
[]
no_license
package com.nttdata.spring.cxacademy.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity(name = "Address") public class AddressModel { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; @Column private String streetName; @Column private String streetNumber; @Column private String addressLine2; @Column private String zipCode; @Column private String city; @Column private String state; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getStreetName() { return streetName; } public void setStreetName(String streetName) { this.streetName = streetName; } public String getStreetNumber() { return streetNumber; } public void setStreetNumber(String streetNumber) { this.streetNumber = streetNumber; } public String getAddressLine2() { return addressLine2; } public void setAddressLine2(String addressLine2) { this.addressLine2 = addressLine2; } public String getZipCode() { return zipCode; } public void setZipCode(String zipCode) { this.zipCode = zipCode; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } }
true
5b40672049e6586f0b833df05a714ba4dd7a6b9f
Java
hnsylike/jatgo
/jatgo-bean/src/main/java/com/kafang/atgo/bean/fix/field/FixResendEndFlagField.java
UTF-8
551
1.828125
2
[]
no_license
package com.kafang.atgo.bean.fix.field; import com.kafang.atgo.bean.fix.base.FixField; import com.kafang.atgo.bean.fix.base.GeneralFixField; import com.kafang.atgo.bean.fix.base.GeneralFixFields; public enum FixResendEndFlagField implements FixField { MsgType(GeneralFixFields.FixField_MsgType), ; private GeneralFixField generalFixField; private FixResendEndFlagField(GeneralFixField generalFixField) { this.generalFixField = generalFixField; } @Override public GeneralFixField getGeneralFixField() { return generalFixField; } }
true
0716f523451d380c1c7f57fcdacdf37e282cba4e
Java
jeanschuchardt/library
/src/main/java/com/jb/library/entity/Book.java
UTF-8
977
2.125
2
[ "Apache-2.0" ]
permissive
package com.jb.library.entity; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; import java.util.HashSet; import java.util.Set; @Data @Builder @AllArgsConstructor @NoArgsConstructor @Entity @Table(name = "book") public class Book { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Column private int number; @Column private String title; @Column private int pageCount; @ManyToMany(targetEntity = Author.class, cascade = {CascadeType.PERSIST, CascadeType.MERGE}) private Set<Author> authorList = new HashSet<>(); @ManyToMany(targetEntity = Gender.class, cascade = {CascadeType.PERSIST, CascadeType.MERGE}) private Set<Gender> genersList = new HashSet<>(); @OneToMany(mappedBy = "books") private Set<LoanRecord> loadRecord = new HashSet<>(); }
true
2d1b0ed294204221dc0ffcbdec411f978f876695
Java
efrenrodriguezsantiago/changes-document
/src/alumno_aprobados.java
UTF-8
778
3.546875
4
[]
no_license
import javax.swing.JOptionPane; public class alumno_aprobados { public static void main(String[] args) { // dadas 6 notas escribir la cantidad de alumnos //aprobados condicionados (=4) y suspensos float nota; int aprobado=0,condicionado=0,suspenso=0; for(int i=1;i<=6;i++) { do { nota = Float.parseFloat(JOptionPane.showInputDialog("digite una nota entre 0 a 10: ")); }while(nota<0 || nota>10);//la nota esta en el intervalo de 0 a 10 if(nota==4) { condicionado++; } else if(nota>=5) { aprobado++; } else { suspenso++; } } System.out.println("cantidad de aprobados: "+aprobado); System.out.println("cantidad de condicionado: "+condicionado); System.out.println("cantidad de reprobados: "+suspenso); } }
true
9a5a4a71c93975af06142789ab5f53c9887c1c43
Java
danisilver/entregapev
/G07P1/src/view/MainView.java
WINDOWS-1250
43,611
1.75
2
[]
no_license
package view; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.Toolkit; import java.awt.event.KeyEvent; import java.io.IOException; import java.text.NumberFormat; import java.util.Arrays; import java.util.List; import javax.swing.BoxLayout; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JEditorPane; import javax.swing.JFormattedTextField; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.JSlider; import javax.swing.JSpinner; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.SpinnerNumberModel; import javax.swing.SwingConstants; import javax.swing.border.EmptyBorder; import javax.swing.border.TitledBorder; import javax.swing.text.NumberFormatter; import javax.swing.text.html.HTMLEditorKit; import javax.swing.text.html.StyleSheet; import org.math.plot.Plot2DPanel; import model.MainModel; import problem.ConcreteFactory; import utils.CustomHyperLinkListener; import utils.ModernScrollPane; import utils.Utils.TitleClickAdapter; public class MainView extends JPanel implements View{ //take the mainmodel and render view private static final long serialVersionUID = 1L; private JFrame window; private MainModel model; public JPanel panel_6;//plot2d public JPanel panel_7;//plot3d public JProgressBar progressBar; public JButton btnPaso; public JButton btnEjecutar; public JSpinner spinnerTamPoblacion; public JSpinner spinnerNGeneraciones; public JTextField tfTolerancia; public JSpinner spinnerPorcntjElitismo; public JSpinner spinnerProbCruce; public JSpinner spinnerProbMutacion; public JComboBox<Object> cbFuncionSeleccionada; public JComboBox<Object> cbTipoSeleccion; public JComboBox<Object> cbTipoCruce; public JComboBox<Object> cbTipoMutacion; public JComboBox<Object> cbTipoCromosoma; public JComboBox<Object> cbDatosOptimizar; public JComboBox<Object> cbGramaticaInit; public JCheckBox checkboxInstrIF; public JSpinner spinnerMaxDepth; public JSpinner spinnerNaddrInputs; public JSpinner spinnerNumVariables; public JTextArea jtaLog; public JSpinner spinnerMinX; public JSpinner spinnerMaxX; public JSpinner spinnerMinY; public JSpinner spinnerMaxY; public JCheckBox checkboxRandomSeed; public JFormattedTextField tfSeed; public JSpinner spinnerKindividuos; public JSpinner spinnerBeta; public JSpinner spinnerUmbral; public JSpinner spinnerTamMuestra; public JSpinner spinnerTrunc; public JSpinner spinnerAlfa; public JSpinner spinnerNumGens2Xchng; public JSpinner spinnerProbXchngGen; public JSpinner spinnerProbFlipBit; public JSpinner spinnerNumGen2Perm; public JSpinner spinnerNumGens2Ins; public JSpinner spinnerNumG2Inv; private JLabel lblMinX; private JLabel lblMaxX; private JLabel lblMinY; private JLabel lblMaxY; private JLabel lblKindividuos; private JLabel lblTamMuestra; private JLabel lblUmbral; private JLabel lblBeta; private JLabel lblTrunc; private JLabel lblProbXchngGen; private JLabel lblAlfa; private JLabel lblNumGens2Xchng; private JLabel lblProbFlipBit; private JLabel lblNumGen2Perm; private JLabel lblNumGens2Ins; private JLabel lblNumG2Inv; private JLabel lblNumVariables; private JLabel lblDatosOptimizar; private JLabel lblMaxDepth; private JLabel lblNaddrInputs; private JLabel lblcbGramaticaInit; private DefaultComboBoxModel<Object> modelCromosomas; private DefaultComboBoxModel<Object> modelSelecciones; private DefaultComboBoxModel<Object> modelCruces; private DefaultComboBoxModel<Object> modelMutaciones; private DefaultComboBoxModel<Object> modelFunciones; private JTabbedPane tabbedPane; public Plot2DPanel p2d; private JEditorPane jEditorPane; private DefaultComboBoxModel<Object> modelGramaticaInit; private JLabel lblcbBloating; private JComboBox<Object> cbBloating; private DefaultComboBoxModel<Object> modelBloating; private JLabel lblTarpeianN; private JSlider jslidderTarpeianN; private JLabel lblTFtolerancia; private JLabel lblBLXalpha; private JSpinner spinnerBLXalpha; private JSpinner spinnerOXOPn2take; private JLabel lblOXOPn2take; public JLabel labelSolucion; public MainView(MainModel model) { this.model = model; window = new JFrame(model.getTitle()); window.setVisible(true); window.setTitle("Programacin evolutiva"); window.setIconImage(Toolkit.getDefaultToolkit().getImage(MainView.class.getResource("/org/math/plot/icons/position.png"))); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setBounds(100, 100, 703, 526); setDoubleBuffered(true); setLayout(new BorderLayout(0, 0)); window.setContentPane(this); addAllComponents(); registerEvents(); updateCromosomaProps(); } public void updateView() { updateGeneralPanel(); updateCromosomaPanel(); updateSeleccionPanel(); updateCrucePanel(); updateMutacionPanel(); } public void updateGeneralPanel() { Integer tamP = (Integer) model.getPropValue("tamPoblacion"); spinnerTamPoblacion.setValue(tamP); Integer niters = (Integer) model.getPropValue("maxIteraciones"); SpinnerNumberModel sngm = (SpinnerNumberModel) spinnerNGeneraciones.getModel(); spinnerNGeneraciones.setModel( new SpinnerNumberModel(niters, sngm.getMinimum(), sngm.getMaximum(), sngm.getStepSize())); Double tol = (Double) model.getPropValue("tolerancia"); tfTolerancia.setText(String.valueOf(tol)); String self = model.getPropValue("funcion").toString(); List<Object> cblist = model.getPropValues("funcion"); modelFunciones = new DefaultComboBoxModel<>(cblist.toArray()); modelFunciones.setSelectedItem(self); cbFuncionSeleccionada.setModel(modelFunciones ); Boolean randEnabled = (Boolean)model.getPropValue("randomSeed"); checkboxRandomSeed.setSelected(randEnabled); tfSeed.setEnabled(!randEnabled); Long seed = (Long)model.getPropValue("seed"); tfSeed.setValue(seed); String selDatosFich = model.getPropValue("fichero").toString(); cbDatosOptimizar.setSelectedItem(selDatosFich); refreshFuncionFields(self); } public void updateCromosomaPanel() { List<Object> cblist = model.getPropValues("tipoCromosoma"); String selCrom = model.getPropValue("tipoCromosoma").toString(); modelCromosomas = new DefaultComboBoxModel<Object>(cblist.toArray()); if(modelCromosomas.getIndexOf(selCrom)>=0) modelCromosomas.setSelectedItem(selCrom); else selCrom = modelCromosomas.getSelectedItem().toString(); cbTipoCromosoma.setModel(modelCromosomas); String selF = model.getPropValue("funcion").toString(); if("DeJong, Easom, CrossInTray, Drop-wave, Bukin".indexOf(selF)!=-1) selCrom = ""; refreshCromosomaFields(selCrom); } public void updateSeleccionPanel() { List<Object> cblist = model.getPropValues("tipoSeleccion"); String selSel = model.getPropValue("tipoSeleccion").toString(); modelSelecciones = new DefaultComboBoxModel<>(cblist.toArray()); if(modelSelecciones.getIndexOf(selSel)>=0) modelSelecciones.setSelectedItem(selSel); else selSel = modelSelecciones.getSelectedItem().toString(); cbTipoSeleccion.setModel(modelSelecciones); refreshSelectionFields(selSel); } public void updateCrucePanel() { List<Object> cblist = model.getPropValues("tipoCruce"); String selCruce = model.getPropValue("tipoCruce").toString(); modelCruces = new DefaultComboBoxModel<>(cblist.toArray()); if(modelCruces.getIndexOf(selCruce)>=0) modelCruces.setSelectedItem(selCruce); else selCruce = modelCruces.getSelectedItem().toString(); cbTipoCruce.setModel(modelCruces); refreshCruceFields(selCruce); } public void updateMutacionPanel() { List<Object> cblist = model.getPropValues("tipoMutacion"); String selMut = model.getPropValue("tipoMutacion").toString(); modelMutaciones = new DefaultComboBoxModel<>(cblist.toArray()); if(modelMutaciones.getIndexOf(selMut)>=0) modelMutaciones.setSelectedItem(selMut); else selMut = modelMutaciones.getSelectedItem().toString(); cbTipoMutacion.setModel(modelMutaciones); refreshMutacionFields(selMut); } public void updateFuncionUI(String c) { JComponent[] comps = new JComponent[] { lblTFtolerancia, tfTolerancia, lblDatosOptimizar, cbDatosOptimizar }; Arrays.asList(comps).forEach(cmp->cmp.setVisible(false)); if(c.indexOf("datosOptimizar")!=-1) { lblDatosOptimizar.setVisible(true); cbDatosOptimizar.setVisible(true); } if(c.indexOf("tolerancia")!=-1) { lblTFtolerancia.setVisible(true); tfTolerancia.setVisible(true); } } public void updateCromosomaUI(String c) { JComponent[] comps = new JComponent[] { lblNumVariables, spinnerNumVariables, lblMinX, spinnerMinX, lblMaxX, spinnerMaxX, lblMinY, spinnerMinY, lblMaxY, spinnerMaxY, lblMaxDepth, spinnerMaxDepth, lblNaddrInputs, spinnerNaddrInputs, lblcbGramaticaInit, cbGramaticaInit, checkboxInstrIF, lblcbBloating, cbBloating }; Arrays.asList(comps).forEach(cmp->cmp.setVisible(false)); if(c.indexOf("numVariables")!=-1) { lblNumVariables.setVisible(true); spinnerNumVariables.setVisible(true); } if(c.indexOf("minX")!=-1) { lblMinX.setVisible(true); spinnerMinX.setVisible(true); } if(c.indexOf("maxX")!=-1) { lblMaxX.setVisible(true); spinnerMaxX.setVisible(true); } if(c.indexOf("minY")!=-1) { lblMinY.setVisible(true); spinnerMinY.setVisible(true); } if(c.indexOf("maxY")!=-1) { lblMaxY.setVisible(true); spinnerMaxY.setVisible(true); } if(c.indexOf("maxDepth")!=-1) { lblMaxDepth.setVisible(true); spinnerMaxDepth.setVisible(true); } if(c.indexOf("nAddrInputs")!=-1) { lblNaddrInputs.setVisible(true); spinnerNaddrInputs.setVisible(true); } if(c.indexOf("cbGramaticaInit")!=-1) { lblcbGramaticaInit.setVisible(true); cbGramaticaInit.setVisible(true); } if(c.indexOf("instrIF")!=-1){ checkboxInstrIF.setVisible(true); } if(c.indexOf("bloating")!=-1) { lblcbBloating.setVisible(true); cbBloating.setVisible(true); } } public void updateMutacionUI(String c) { JComponent[] comps = new JComponent[] {lblProbFlipBit, spinnerProbFlipBit, lblNumGens2Ins, lblNumGens2Ins, spinnerNumGens2Ins, lblNumG2Inv, spinnerNumG2Inv, lblNumGen2Perm, spinnerNumGen2Perm}; Arrays.asList(comps).forEach(cmp->cmp.setVisible(false)); if(c.indexOf("probFlipBit")!=-1) { lblProbFlipBit.setVisible(true); spinnerProbFlipBit.setVisible(true); } if(c.indexOf("numGens2Ins")!=-1) { lblNumGens2Ins.setVisible(true); spinnerNumGens2Ins.setVisible(true); } if(c.indexOf("numG2Inv")!=-1) { lblNumG2Inv.setVisible(true); spinnerNumG2Inv.setVisible(true); } if(c.indexOf("numGen2Perm")!=-1) { lblNumGen2Perm.setVisible(true); spinnerNumGen2Perm.setVisible(true); } } public void updateCruceUI(String c) { JComponent[] comps = new JComponent[] { lblProbXchngGen, spinnerProbXchngGen, lblAlfa, spinnerAlfa, lblNumGens2Xchng, spinnerNumGens2Xchng, lblBLXalpha, spinnerBLXalpha, lblOXOPn2take, spinnerOXOPn2take }; Arrays.asList(comps).forEach(cmp->cmp.setVisible(false)); if(c.indexOf("probXchngGen")!=-1) { lblProbXchngGen.setVisible(true); spinnerProbXchngGen.setVisible(true); } if(c.indexOf("alfa")!=-1) { lblAlfa.setVisible(true); spinnerAlfa.setVisible(true); } if(c.indexOf("numGens2Xchng")!=-1) { lblNumGens2Xchng.setVisible(true); spinnerNumGens2Xchng.setVisible(true); } if(c.indexOf("blxalpha")!=-1) { lblBLXalpha.setVisible(true); spinnerBLXalpha.setVisible(true); } if(c.indexOf("n2take")!=-1) { lblOXOPn2take.setVisible(true); spinnerOXOPn2take.setVisible(true); } } public void updateSeleccionUI(String c) { JComponent[] comps = new JComponent[] { lblKindividuos, spinnerKindividuos, lblTamMuestra, spinnerTamMuestra, lblUmbral, spinnerUmbral, lblBeta, spinnerBeta, lblTrunc, spinnerTrunc }; Arrays.asList(comps).forEach(cmp->cmp.setVisible(false)); if(c.indexOf("kindividuos")!=-1) { lblKindividuos.setVisible(true); spinnerKindividuos.setVisible(true); } if(c.indexOf("tamMuestra")!=-1) { lblTamMuestra.setVisible(true); spinnerTamMuestra.setVisible(true); } if(c.indexOf("umbral")!=-1) { lblUmbral.setVisible(true); spinnerUmbral.setVisible(true); } if(c.indexOf("beta")!=-1) { lblBeta.setVisible(true); spinnerBeta.setVisible(true); } if(c.indexOf("trunc")!=-1) { lblTrunc.setVisible(true); spinnerTrunc.setVisible(true); } } private void registerEvents() { checkboxRandomSeed.addActionListener(e-> model.setPropValue( "randomSeed", Boolean.valueOf(checkboxRandomSeed.isSelected()))); tfSeed.addActionListener(e-> model.setPropValue("seed", Long.valueOf(tfSeed.getValue().toString()))); btnEjecutar.addActionListener(e-> model.setPropValue("randomSeed", Boolean.valueOf(checkboxRandomSeed.isSelected()))); cbFuncionSeleccionada.addActionListener(e-> model.setPropValue("funcion", cbFuncionSeleccionada.getSelectedItem())); cbTipoCromosoma.addActionListener(e-> model.setPropValue("tipoCromosoma", cbTipoCromosoma.getSelectedItem())); cbTipoSeleccion.addActionListener(e-> model.setPropValue("tipoSeleccion", cbTipoSeleccion.getSelectedItem())); cbTipoCruce.addActionListener(e-> model.setPropValue("tipoCruce", cbTipoCruce.getSelectedItem())); cbTipoMutacion.addActionListener(e-> model.setPropValue("tipoMutacion", cbTipoMutacion.getSelectedItem())); cbDatosOptimizar.addActionListener(e-> model.setPropValue("fichero", cbDatosOptimizar.getSelectedItem())); spinnerNumVariables.addChangeListener(e-> model.setPropValue("numVariables", (Integer) spinnerNumVariables.getValue())); tfTolerancia.addActionListener(e-> model.setPropValue("tolerancia", Double.parseDouble(tfTolerancia.getText()))); spinnerTamPoblacion.addChangeListener(e-> model.setPropValue("tamPoblacion", (Integer) spinnerTamPoblacion.getValue())); spinnerNGeneraciones.addChangeListener(e-> model.setPropValue("maxIteraciones", (Integer) spinnerNGeneraciones.getValue())); spinnerPorcntjElitismo.addChangeListener(e-> model.setPropValue("%elitismo", (Double) spinnerPorcntjElitismo.getValue())); spinnerProbCruce.addChangeListener(e-> model.setPropValue("probCruce", (Double) spinnerProbCruce.getValue())); spinnerProbMutacion.addChangeListener(e-> model.setPropValue("probMutacion", (Double) spinnerProbMutacion.getValue())); spinnerMinX.addChangeListener(e-> model.setPropValue("minX", (Double) spinnerMinX.getValue())); spinnerMaxX.addChangeListener(e-> model.setPropValue("maxX", (Double) spinnerMaxX.getValue())); spinnerMinY.addChangeListener(e-> model.setPropValue("minY", (Double) spinnerMinY.getValue())); spinnerMaxY.addChangeListener(e-> model.setPropValue("maxY", (Double) spinnerMaxY.getValue())); spinnerKindividuos.addChangeListener(e-> model.setPropValue("kindividuos", (Integer) spinnerKindividuos.getValue())); spinnerBeta.addChangeListener(e-> model.setPropValue("beta", (Double) spinnerBeta.getValue())); spinnerUmbral.addChangeListener(e-> model.setPropValue("umbral", (Double) spinnerBeta.getValue())); spinnerTamMuestra.addChangeListener(e-> model.setPropValue("tamMuestra", (Integer) spinnerTamMuestra.getValue())); spinnerTrunc.addChangeListener(e-> model.setPropValue("trunc", (Integer) spinnerTrunc.getValue())); spinnerAlfa.addChangeListener(e-> model.setPropValue("alfa", (Double) spinnerAlfa.getValue())); spinnerNumGens2Xchng.addChangeListener(e-> model.setPropValue("numGens2Xchng", (Integer) spinnerNumGens2Xchng.getValue())); spinnerProbXchngGen.addChangeListener(e-> model.setPropValue("probXchngGen", (Double) spinnerProbXchngGen.getValue())); spinnerProbFlipBit.addChangeListener(e-> model.setPropValue("probFlipBit", (Double) spinnerProbFlipBit.getValue())); spinnerNumGen2Perm.addChangeListener(e-> model.setPropValue("numGen2Perm", (Integer) spinnerNumGen2Perm.getValue())); spinnerNumGens2Ins.addChangeListener(e-> model.setPropValue("numGens2Ins", (Integer) spinnerNumGens2Ins.getValue())); spinnerNumG2Inv.addChangeListener(e-> model.setPropValue("numG2Inv", (Integer) spinnerNumG2Inv.getValue())); spinnerMaxDepth.addChangeListener(e-> model.setPropValue("profundidad", spinnerMaxDepth.getValue())); spinnerNaddrInputs.addChangeListener(e-> model.setPropValue("nAddrInputs", spinnerNaddrInputs.getValue())); cbGramaticaInit.addActionListener(e-> model.setPropValue("tipoCreacion", cbGramaticaInit.getSelectedIndex())); checkboxInstrIF.addActionListener(e-> model.setPropValue("useIF", checkboxInstrIF.isSelected())); cbBloating.addActionListener(e-> model.setPropValue("bloating", cbBloating.getSelectedItem())); tabbedPane.addChangeListener(e->updateProblemView()); btnPaso.addActionListener(e-> p2d.removeAllPlots()); btnPaso.addActionListener(e-> jtaLog.setText("")); jslidderTarpeianN.addChangeListener(e-> model.setPropValue("tarpeianDeathProportion", jslidderTarpeianN.getValue())); spinnerOXOPn2take.addChangeListener(e-> model.setPropValue("blxalpha", spinnerOXOPn2take.getValue())); } public void updateProgressBar() { int searchProgress = model.getSearchProgress(); Integer maxIteraciones = (Integer) model.getPropValue("maxIteraciones"); progressBar.setMaximum(maxIteraciones); progressBar.setValue(searchProgress++); model.setSearchProgress(searchProgress); } public void updateProblemView() { String funcion = model.getPropValue("funcion").toString(); ConcreteFactory factory = new ConcreteFactory(funcion); Component pv = factory.createView(model.getPropsMap()).getComponent(); panel_7.removeAll(); panel_7.add(pv); panel_7.revalidate(); } @Override public JComponent getComponent() { return this; } private void refreshFuncionFields(String fun) { if(fun.equalsIgnoreCase("funcion 1")) updateFuncionUI("tolerancia"); else if(fun.equalsIgnoreCase("Holder table")) updateFuncionUI("tolerancia"); else if(fun.equalsIgnoreCase("Schubert")) updateFuncionUI("tolerancia"); else if(fun.equalsIgnoreCase("Michalewicz")) updateFuncionUI("tolerancia"); else if(fun.equalsIgnoreCase("Problema5")) updateFuncionUI("datosOptimizar"); else if(fun.equalsIgnoreCase("Multiplexor")) updateFuncionUI(""); } public void refreshMutacionFields(String mut) { if(mut.equalsIgnoreCase("Basica")) updateMutacionUI("probFlipBit"); else if(mut.equalsIgnoreCase("Uniforme")) updateMutacionUI(""); else if(mut.equalsIgnoreCase("Insercion")) updateMutacionUI("numGens2Ins"); else if(mut.equalsIgnoreCase("Intercambio")) updateMutacionUI("numG2Inv"); else if(mut.equalsIgnoreCase("Inversion")) updateMutacionUI(""); else if(mut.equalsIgnoreCase("Heuristica")) updateMutacionUI("numGen2Perm"); else if(mut.equalsIgnoreCase("TerminalSimple")) updateMutacionUI(""); else if(mut.equalsIgnoreCase("FuncionalSimple")) updateMutacionUI(""); else if(mut.equalsIgnoreCase("NodeRestart")) updateMutacionUI(""); else if(mut.equalsIgnoreCase("PermutarArgs")) updateMutacionUI(""); } public void refreshCruceFields(String cruc) { if(cruc.equalsIgnoreCase("Monopunto")) updateCruceUI(""); else if(cruc.equalsIgnoreCase("Monopunto")) updateCruceUI(""); else if(cruc.equalsIgnoreCase("Uniforme")) updateCruceUI("probXchngGen"); else if(cruc.equalsIgnoreCase("Aritmetico")) updateCruceUI("alfa"); else if(cruc.equalsIgnoreCase("CrucePMX")) updateCruceUI(""); else if(cruc.equalsIgnoreCase("CruceERX")) updateCruceUI(""); else if(cruc.equalsIgnoreCase("CruceCO")) updateCruceUI(""); else if(cruc.equalsIgnoreCase("CruceCX")) updateCruceUI(""); else if(cruc.equalsIgnoreCase("CruceOX")) updateCruceUI(""); else if(cruc.equalsIgnoreCase("CruceOXPP")) updateCruceUI("numGens2Xchng"); else if(cruc.equalsIgnoreCase("CruceOXOP")) updateCruceUI("n2take"); else if(cruc.equalsIgnoreCase("CruceBLXalpha")) updateCruceUI("blxalpha"); } public void refreshCromosomaFields(String crom) { if(crom.equalsIgnoreCase("Binario")) updateCromosomaUI("minX, maxX, minY, maxY"); else if(crom.equalsIgnoreCase("Real")) updateCromosomaUI("numVariables, minX, maxX"); else if(crom.equalsIgnoreCase("Permutacion")) updateCromosomaUI(""); else if(crom.equalsIgnoreCase("Gramatica")) updateCromosomaUI("maxDepth, nAddrInputs, cbGramaticaInit, instrIF, bloating"); else if(crom.equalsIgnoreCase("")) updateCromosomaUI(""); } public void refreshSelectionFields(String sel) { if(sel.equalsIgnoreCase("Ranking")) updateSeleccionUI("beta"); else if(sel.equalsIgnoreCase("Truncamiento")) updateSeleccionUI("trunc"); else if(sel.equalsIgnoreCase("Ruleta")) updateSeleccionUI(""); else if(sel.equalsIgnoreCase("Estocastico")) updateSeleccionUI("kindividuos"); else if(sel.equalsIgnoreCase("Torneo")) updateSeleccionUI("tamMuestra, umbral"); } public void updateCromosomaProps() { String selF = model.getPropValue("funcion").toString(); if(selF.equalsIgnoreCase("funcion 1")) { spinnerMinX.setValue(model.getPropValue("minX")); spinnerMaxX.setValue(model.getPropValue("maxX")); spinnerMinY.setValue(model.getPropValue("minY")); spinnerMaxY.setValue(model.getPropValue("maxY")); } else if(selF.equalsIgnoreCase("Holder table")) { spinnerMinX.setValue(model.getPropValue("minX")); spinnerMaxX.setValue(model.getPropValue("maxX")); spinnerMinY.setValue(model.getPropValue("minY")); spinnerMaxY.setValue(model.getPropValue("maxY")); } else if(selF.equalsIgnoreCase("Schubert")) { spinnerMinX.setValue(model.getPropValue("minX")); spinnerMaxX.setValue(model.getPropValue("maxX")); spinnerMinY.setValue(model.getPropValue("minY")); spinnerMaxY.setValue(model.getPropValue("maxY")); } else if(selF.equalsIgnoreCase("Michalewicz")) { spinnerMinX.setValue(model.getPropValue("minX")); spinnerMaxX.setValue(model.getPropValue("maxX")); spinnerMinY.setValue(model.getPropValue("minY")); spinnerMaxY.setValue(model.getPropValue("maxY")); } else if(selF.equalsIgnoreCase("Multiplexor")) { //TODO: updateCromosomaProps } } private void addAllComponents() { JPanel panel = new JPanel(); add(panel, BorderLayout.CENTER); panel.setLayout(new BorderLayout(0, 0)); JPanel panel_1 = new JPanel(); JPanel propsPanel = new JPanel(); propsPanel.setBorder(null); propsPanel.add(panel_1); JPanel mspPanel = new JPanel(); FlowLayout fl_propsPanel = (FlowLayout) propsPanel.getLayout(); fl_propsPanel.setVgap(0); fl_propsPanel.setHgap(0); ModernScrollPane msp = new ModernScrollPane(mspPanel); msp.getVerticalScrollBar().setUnitIncrement(16); mspPanel.setLayout(new BoxLayout(mspPanel, BoxLayout.Y_AXIS)); mspPanel.add(propsPanel); panel_1.setBorder(null); panel.add(msp, BorderLayout.WEST); panel_1.setLayout(new BoxLayout(panel_1, BoxLayout.Y_AXIS)); JPanel panel_11 = new JPanel(); panel_11.setBorder(null); panel_11.setLayout(new BoxLayout(panel_11, BoxLayout.X_AXIS)); progressBar = new JProgressBar(); progressBar.setBorder(null); panel_11.add(progressBar); panel_1.add(panel_11); JPanel panel_9 = new JPanel(); panel_9.setBorder(null); panel_9.setLayout(new GridLayout(0, 2, 0, 0)); btnEjecutar = new JButton("Ejecutar"); btnEjecutar.setMnemonic('j'); btnEjecutar.setAlignmentX(Component.CENTER_ALIGNMENT); btnEjecutar.setHorizontalAlignment(SwingConstants.LEFT); panel_9.add(btnEjecutar); btnPaso = new JButton("Reset"); btnPaso.setMnemonic('R'); btnPaso.setAlignmentX(Component.CENTER_ALIGNMENT); btnPaso.setHorizontalAlignment(SwingConstants.LEFT); panel_9.add(btnPaso); panel_1.add(panel_9); JPanel panelGeneral = new JPanel(); TitledBorder border = new TitledBorder(null, "General", TitledBorder.LEADING, TitledBorder.TOP, null, null); panelGeneral.setBorder(border); panel_1.add(panelGeneral); panelGeneral.setLayout(new BorderLayout(0, 0)); JPanel panel_4 = new JPanel(); panel_4.setBorder(new EmptyBorder(0, 6, 6, 6)); panelGeneral.add(panel_4, BorderLayout.NORTH); panel_4.setLayout(new BoxLayout(panel_4, BoxLayout.Y_AXIS)); JLabel lblNewLabel = new JLabel("tama\u00F1o poblacion"); lblNewLabel.setAlignmentY(Component.TOP_ALIGNMENT); lblNewLabel.setAlignmentX(Component.CENTER_ALIGNMENT); lblNewLabel.setDisplayedMnemonic('t'); panel_4.add(lblNewLabel); spinnerTamPoblacion = new JSpinner(new SpinnerNumberModel(100,10,10000000,2)); lblNewLabel.setLabelFor(spinnerTamPoblacion); spinnerTamPoblacion.setAlignmentY(Component.TOP_ALIGNMENT); panel_4.add(spinnerTamPoblacion); JLabel lblNewLabel_1 = new JLabel("num generaciones"); lblNewLabel_1.setAlignmentX(Component.CENTER_ALIGNMENT); lblNewLabel_1.setDisplayedMnemonic('n'); panel_4.add(lblNewLabel_1); spinnerNGeneraciones = new JSpinner(new SpinnerNumberModel(100,20,10000000,1)); lblNewLabel_1.setLabelFor(spinnerNGeneraciones); spinnerNGeneraciones.setAlignmentY(Component.TOP_ALIGNMENT); panel_4.add(spinnerNGeneraciones); lblTFtolerancia = new JLabel("tolerancia"); lblTFtolerancia.setAlignmentY(Component.TOP_ALIGNMENT); lblTFtolerancia.setAlignmentX(Component.CENTER_ALIGNMENT); lblTFtolerancia.setDisplayedMnemonic('o'); panel_4.add(lblTFtolerancia); tfTolerancia = new JTextField(); lblTFtolerancia.setLabelFor(tfTolerancia); tfTolerancia.setAlignmentY(Component.TOP_ALIGNMENT); tfTolerancia.setText("0.001"); panel_4.add(tfTolerancia); tfTolerancia.setColumns(10); checkboxRandomSeed = new JCheckBox("random seed"); checkboxRandomSeed.setMnemonic('d'); checkboxRandomSeed.setAlignmentX(Component.CENTER_ALIGNMENT); checkboxRandomSeed.setToolTipText("Desactivar para obtener la misma secuencia de numeros aleatorios la siguiente ejecucion"); panel_4.add(checkboxRandomSeed); NumberFormat longFormat = NumberFormat.getIntegerInstance(); NumberFormatter numberFormatter = new NumberFormatter(longFormat); numberFormatter.setValueClass(Long.class); numberFormatter.setAllowsInvalid(false); tfSeed = new JFormattedTextField(numberFormatter); tfSeed.setColumns(10); panel_4.add(tfSeed); JLabel lblNewLabel_3 = new JLabel("funcion"); lblNewLabel_3.setAlignmentY(Component.TOP_ALIGNMENT); lblNewLabel_3.setAlignmentX(Component.CENTER_ALIGNMENT); lblNewLabel_3.setDisplayedMnemonic('f'); panel_4.add(lblNewLabel_3); cbFuncionSeleccionada = new JComboBox<>(); lblNewLabel_3.setLabelFor(cbFuncionSeleccionada); cbFuncionSeleccionada.setAlignmentY(Component.TOP_ALIGNMENT); modelFunciones = new DefaultComboBoxModel<>(new Object[] { "funcion 1", "Holder table", "Schubert", "Michalewicz", "Problema5", "Multiplexor"}); cbFuncionSeleccionada.setModel(modelFunciones); panel_4.add(cbFuncionSeleccionada); lblDatosOptimizar = new JLabel("datos a optimizar"); lblDatosOptimizar.setAlignmentX(Component.CENTER_ALIGNMENT); lblDatosOptimizar.setDisplayedMnemonic('t'); panel_4.add(lblDatosOptimizar); cbDatosOptimizar = new JComboBox<>(); lblDatosOptimizar.setLabelFor(cbDatosOptimizar); cbDatosOptimizar.setModel(new DefaultComboBoxModel<Object>(new Object[] {"ajuste.dat", "datos12.dat", "datos15.dat", "datos30.dat"})); panel_4.add(cbDatosOptimizar); JPanel panelCromosoma = new JPanel(); panelCromosoma.setBorder(new TitledBorder(null, "Cromosoma", TitledBorder.LEADING, TitledBorder.TOP, null, null)); panel_1.add(panelCromosoma); panelCromosoma.setLayout(new BorderLayout(0, 0)); JPanel panel_17 = new JPanel(); panel_17.setBorder(new EmptyBorder(0, 6, 6, 6)); panelCromosoma.add(panel_17); panel_17.setLayout(new BoxLayout(panel_17, BoxLayout.Y_AXIS)); JLabel lblNewLabel_10 = new JLabel("tipo cromosoma"); lblNewLabel_10.setAlignmentY(Component.TOP_ALIGNMENT); lblNewLabel_10.setAlignmentX(Component.CENTER_ALIGNMENT); lblNewLabel_10.setDisplayedMnemonic('a'); panel_17.add(lblNewLabel_10); cbTipoCromosoma = new JComboBox<>(); lblNewLabel_10.setLabelFor(cbTipoCromosoma); cbTipoCromosoma.setAlignmentY(Component.TOP_ALIGNMENT); modelCromosomas = new DefaultComboBoxModel<Object>(new Object[] {"Binario", "Real"}); cbTipoCromosoma.setModel(modelCromosomas); panel_17.add(cbTipoCromosoma); lblNumVariables = new JLabel("num. variables"); lblNumVariables.setAlignmentY(Component.TOP_ALIGNMENT); lblNumVariables.setAlignmentX(Component.CENTER_ALIGNMENT); lblNumVariables.setDisplayedMnemonic('v'); panel_17.add(lblNumVariables); spinnerNumVariables = new JSpinner(new SpinnerNumberModel(2, 2, 10, 1)); lblNumVariables.setLabelFor(spinnerNumVariables); spinnerNumVariables.setAlignmentY(Component.TOP_ALIGNMENT); panel_17.add(spinnerNumVariables); lblMinX = new JLabel("min X"); lblMinX.setAlignmentX(Component.CENTER_ALIGNMENT); lblMinX.setDisplayedMnemonic('i'); panel_17.add(lblMinX); spinnerMinX = new JSpinner(new SpinnerNumberModel(0.0,-100000000.0 ,100000000.0,0.01)); lblMinX.setLabelFor(spinnerMinX); panel_17.add(spinnerMinX); lblMaxX = new JLabel("max X"); lblMaxX.setAlignmentX(Component.CENTER_ALIGNMENT); lblMaxX.setDisplayedMnemonic('X'); panel_17.add(lblMaxX); spinnerMaxX = new JSpinner(new SpinnerNumberModel(0.0,-100000000.0 ,100000000.0,0.01)); lblMaxX.setLabelFor(spinnerMaxX); panel_17.add(spinnerMaxX); lblMinY = new JLabel("min Y"); lblMinY.setAlignmentX(Component.CENTER_ALIGNMENT); lblMinY.setDisplayedMnemonic('Y'); panel_17.add(lblMinY); spinnerMinY = new JSpinner(new SpinnerNumberModel(0.0,-100000000.0 ,100000000.0,0.01)); lblMinY.setLabelFor(spinnerMinY); panel_17.add(spinnerMinY); lblMaxY = new JLabel("max Y"); lblMaxY.setAlignmentX(Component.CENTER_ALIGNMENT); panel_17.add(lblMaxY); spinnerMaxY = new JSpinner(new SpinnerNumberModel(0.0,-100000000.0 ,100000000.0,0.01)); lblMaxY.setLabelFor(spinnerMaxY); panel_17.add(spinnerMaxY); checkboxInstrIF = new JCheckBox("instruccion IF"); checkboxInstrIF.setSelected(true); checkboxInstrIF.setAlignmentX(Component.CENTER_ALIGNMENT); panel_17.add(checkboxInstrIF); lblMaxDepth = new JLabel("max start depth"); lblMaxDepth.setAlignmentX(Component.CENTER_ALIGNMENT); panel_17.add(lblMaxDepth); spinnerMaxDepth = new JSpinner(new SpinnerNumberModel(4, 3, 100000, 1)); lblMaxDepth.setLabelFor(spinnerMaxDepth); panel_17.add(spinnerMaxDepth); lblNaddrInputs = new JLabel("<html>" + " (<b>1</b>+1&lt;&lt;<b>1</b>= 3) inputs" + "<br>(<b>2</b>+1&lt;&lt;<b>2</b>= 6) inputs" + "<br>(<b>3</b>+1&lt;&lt;<b>3</b>=11) inputs" + "<br>(<b>4</b>+1&lt;&lt;<b>4</b>=20) inputs" + "<br><b>+5</b> no permitido" + "<br><b>nAddrInputs</b> Mux" + "<br>Multiplexor" + "</html>"); lblNaddrInputs.setAlignmentX(Component.CENTER_ALIGNMENT); panel_17.add(lblNaddrInputs); spinnerNaddrInputs = new JSpinner(new SpinnerNumberModel(2, 1, 4, 1)); lblNaddrInputs.setLabelFor(spinnerNaddrInputs); panel_17.add(spinnerNaddrInputs); lblcbGramaticaInit = new JLabel("tipo inicializacion"); lblcbGramaticaInit.setAlignmentY(Component.TOP_ALIGNMENT); lblcbGramaticaInit.setAlignmentX(Component.CENTER_ALIGNMENT); panel_17.add(lblcbGramaticaInit); cbGramaticaInit = new JComboBox<>(); lblcbGramaticaInit.setLabelFor(cbGramaticaInit); cbGramaticaInit.setAlignmentY(Component.TOP_ALIGNMENT); modelGramaticaInit = new DefaultComboBoxModel<Object>(new Object[] {"Creciente", "Completa", "Ramped"}); cbGramaticaInit.setModel(modelGramaticaInit); panel_17.add(cbGramaticaInit); lblcbBloating = new JLabel("bloating");// lblcbBloating.setDisplayedMnemonic('g'); lblcbBloating.setAlignmentY(Component.TOP_ALIGNMENT); lblcbBloating.setAlignmentX(Component.CENTER_ALIGNMENT); panel_17.add(lblcbBloating); cbBloating = new JComboBox<>(); lblcbBloating.setLabelFor(cbBloating); cbBloating.setAlignmentY(Component.TOP_ALIGNMENT); modelBloating = new DefaultComboBoxModel<Object>(new Object[] {"ninguno", "Tarpeian", "PoliMcPhee"}); cbBloating.setModel(modelBloating); panel_17.add(cbBloating); lblTarpeianN = new JLabel("Death Proportion"); lblTarpeianN.setAlignmentY(Component.TOP_ALIGNMENT); lblTarpeianN.setAlignmentX(Component.CENTER_ALIGNMENT); lblTarpeianN.setVisible(false); jslidderTarpeianN = new JSlider(); lblTarpeianN.setLabelFor(jslidderTarpeianN); jslidderTarpeianN.setValue(7); jslidderTarpeianN.setVisible(false); jslidderTarpeianN.setMinimum(2); jslidderTarpeianN.setMaximum(20); jslidderTarpeianN.setMinorTickSpacing(1); panel_17.add(lblTarpeianN); Dimension size = new Dimension(lblTarpeianN.getSize()); size.height=60; jslidderTarpeianN.setPreferredSize(size); jslidderTarpeianN.setSnapToTicks(true); jslidderTarpeianN.setPaintTicks(true); jslidderTarpeianN.setPaintLabels(true); jslidderTarpeianN.setMajorTickSpacing(1); panel_17.add(jslidderTarpeianN); cbBloating.addActionListener(e->{ if(cbBloating.getSelectedItem().equals("Tarpeian")) { lblTarpeianN.setVisible(true); jslidderTarpeianN.setVisible(true); } else { lblTarpeianN.setVisible(false); jslidderTarpeianN.setVisible(false); } }); JPanel panelSeleccion = new JPanel(); panelSeleccion.setBorder(new TitledBorder(null, "Seleccion", TitledBorder.LEADING, TitledBorder.TOP, null, null)); panel_1.add(panelSeleccion); panelSeleccion.setLayout(new BorderLayout(0, 0)); JPanel panel_10 = new JPanel(); panel_10.setBorder(new EmptyBorder(0, 6, 6, 6)); panelSeleccion.add(panel_10, BorderLayout.NORTH); panel_10.setLayout(new BoxLayout(panel_10, BoxLayout.Y_AXIS)); JLabel lblNewLabel_4 = new JLabel("tipo Seleccion"); lblNewLabel_4.setAlignmentX(Component.CENTER_ALIGNMENT); lblNewLabel_4.setDisplayedMnemonic('S'); panel_10.add(lblNewLabel_4); cbTipoSeleccion = new JComboBox<>(); lblNewLabel_4.setLabelFor(cbTipoSeleccion); modelSelecciones = new DefaultComboBoxModel<Object>(new Object[] {"Ruleta", "Estocastico", "Torneo"}); cbTipoSeleccion.setModel(modelSelecciones); panel_10.add(cbTipoSeleccion); JLabel lblNewLabel_5 = new JLabel("% elitismo"); lblNewLabel_5.setAlignmentX(Component.CENTER_ALIGNMENT); lblNewLabel_5.setDisplayedMnemonic('%'); panel_10.add(lblNewLabel_5); spinnerPorcntjElitismo = new JSpinner(new SpinnerNumberModel(0.0,0.0,1.0,0.01)); lblNewLabel_5.setLabelFor(spinnerPorcntjElitismo); panel_10.add(spinnerPorcntjElitismo); lblKindividuos = new JLabel("kindividuos"); lblKindividuos.setAlignmentX(Component.CENTER_ALIGNMENT); lblKindividuos.setDisplayedMnemonic('k'); panel_10.add(lblKindividuos); spinnerKindividuos = new JSpinner(); lblKindividuos.setLabelFor(spinnerKindividuos); spinnerKindividuos.setModel(new SpinnerNumberModel(3,2,6,1)); panel_10.add(spinnerKindividuos); lblBeta = new JLabel("beta"); lblBeta.setAlignmentX(Component.CENTER_ALIGNMENT); lblBeta.setDisplayedMnemonic('e'); panel_10.add(lblBeta); spinnerBeta = new JSpinner(); lblBeta.setLabelFor(spinnerBeta);//SeleccionRanking spinnerBeta.setModel(new SpinnerNumberModel(1.0,1.0,2.0,0.05)); panel_10.add(spinnerBeta); lblUmbral = new JLabel("umbral"); lblUmbral.setAlignmentX(Component.CENTER_ALIGNMENT); lblUmbral.setDisplayedMnemonic('l'); panel_10.add(lblUmbral); spinnerUmbral = new JSpinner(); lblUmbral.setLabelFor(spinnerUmbral); spinnerUmbral.setModel(new SpinnerNumberModel(1.0,0.0,1.0,0.05)); panel_10.add(spinnerUmbral); lblTamMuestra = new JLabel("tamMuestra"); lblTamMuestra.setAlignmentX(Component.CENTER_ALIGNMENT); panel_10.add(lblTamMuestra); spinnerTamMuestra = new JSpinner(); spinnerTamMuestra.setModel(new SpinnerNumberModel(3,2,6,1)); panel_10.add(spinnerTamMuestra); lblTrunc = new JLabel("trunc"); lblTrunc.setAlignmentX(Component.CENTER_ALIGNMENT); panel_10.add(lblTrunc); spinnerTrunc = new JSpinner(new SpinnerNumberModel(0.5d,0.1d,0.5d,0.05d));//SeleccionTruncamiento panel_10.add(spinnerTrunc); JPanel panelCruce = new JPanel(); panelCruce.setBorder(new TitledBorder(null, "Cruce", TitledBorder.LEADING, TitledBorder.TOP, null, null)); panel_1.add(panelCruce); panelCruce.setLayout(new BorderLayout(0, 0)); JPanel panel_13 = new JPanel(); panel_13.setBorder(new EmptyBorder(0, 6, 6, 6)); panelCruce.add(panel_13, BorderLayout.NORTH); panel_13.setLayout(new BoxLayout(panel_13, BoxLayout.Y_AXIS)); JLabel lblNewLabel_6 = new JLabel("tipo Cruce"); lblNewLabel_6.setAlignmentX(Component.CENTER_ALIGNMENT); lblNewLabel_6.setDisplayedMnemonic('C'); panel_13.add(lblNewLabel_6); cbTipoCruce = new JComboBox<>(); lblNewLabel_6.setLabelFor(cbTipoCruce); modelCruces = new DefaultComboBoxModel<>( new String[] {"Monopunto", "Uniforme", "Aritmetico"}); cbTipoCruce.setModel(modelCruces); panel_13.add(cbTipoCruce); JLabel lblNewLabel_7 = new JLabel("probabilidad"); lblNewLabel_7.setAlignmentX(Component.CENTER_ALIGNMENT); panel_13.add(lblNewLabel_7); spinnerProbCruce = new JSpinner(new SpinnerNumberModel(0.6,0.6,1.0,0.01)); panel_13.add(spinnerProbCruce); lblAlfa = new JLabel("alfa"); lblAlfa.setAlignmentX(Component.CENTER_ALIGNMENT); panel_13.add(lblAlfa); spinnerAlfa = new JSpinner();//CruceAritmetico spinnerAlfa.setModel(new SpinnerNumberModel(0.2, 0.2, 0.6, 0.05)); panel_13.add(spinnerAlfa); lblNumGens2Xchng = new JLabel("numGens2Xchng"); lblNumGens2Xchng.setAlignmentX(Component.CENTER_ALIGNMENT); panel_13.add(lblNumGens2Xchng); spinnerNumGens2Xchng = new JSpinner();//CruceOXPP spinnerNumGens2Xchng.setModel(new SpinnerNumberModel(2, 2, 6, 1)); panel_13.add(spinnerNumGens2Xchng); lblProbXchngGen = new JLabel("probXchngGen"); lblProbXchngGen.setAlignmentX(Component.CENTER_ALIGNMENT); panel_13.add(lblProbXchngGen); spinnerProbXchngGen = new JSpinner();//CruceUniforme spinnerProbXchngGen.setModel(new SpinnerNumberModel(0.4, 0.2, 0.5, 0.05)); panel_13.add(spinnerProbXchngGen); lblBLXalpha = new JLabel("blx-alpha"); lblBLXalpha.setAlignmentX(Component.CENTER_ALIGNMENT); panel_13.add(lblBLXalpha); spinnerBLXalpha = new JSpinner(); spinnerBLXalpha.setModel(new SpinnerNumberModel(0.5, 0.0, 1.0, 0.01)); panel_13.add(spinnerBLXalpha); lblOXOPn2take = new JLabel("n2take"); lblOXOPn2take.setAlignmentX(Component.CENTER_ALIGNMENT); panel_13.add(lblOXOPn2take); spinnerOXOPn2take = new JSpinner(); spinnerOXOPn2take.setModel(new SpinnerNumberModel(4, 2, 10, 1)); panel_13.add(spinnerOXOPn2take); JPanel panelMutacion = new JPanel(); panelMutacion.setBorder(new TitledBorder(null, "Mutacion", TitledBorder.LEADING, TitledBorder.TOP, null, null)); panel_1.add(panelMutacion); panelMutacion.setLayout(new BorderLayout(0, 0)); JPanel panel_15 = new JPanel(); panel_15.setBorder(new EmptyBorder(0, 6, 6, 6)); panelMutacion.add(panel_15, BorderLayout.NORTH); panel_15.setLayout(new BoxLayout(panel_15, BoxLayout.Y_AXIS)); JLabel lblNewLabel_8 = new JLabel("tipo Mutacion"); lblNewLabel_8.setAlignmentX(Component.CENTER_ALIGNMENT); lblNewLabel_8.setDisplayedMnemonic('m'); panel_15.add(lblNewLabel_8); cbTipoMutacion = new JComboBox<>(); lblNewLabel_8.setLabelFor(cbTipoMutacion); modelMutaciones = new DefaultComboBoxModel<>(new Object[] {"Basica", "Uniforme"}); cbTipoMutacion.setModel(modelMutaciones); panel_15.add(cbTipoMutacion); JLabel lblNewLabel_9 = new JLabel("probabilidad"); lblNewLabel_9.setAlignmentX(Component.CENTER_ALIGNMENT); panel_15.add(lblNewLabel_9); spinnerProbMutacion = new JSpinner(new SpinnerNumberModel(0.1,0.0,1.0,0.01)); panel_15.add(spinnerProbMutacion); lblProbFlipBit = new JLabel("probFlipBit"); lblProbFlipBit.setAlignmentX(Component.CENTER_ALIGNMENT); panel_15.add(lblProbFlipBit); spinnerProbFlipBit = new JSpinner();//MutacionBasica spinnerProbFlipBit.setModel(new SpinnerNumberModel(0.15,0,1,0.05)); panel_15.add(spinnerProbFlipBit); lblNumGen2Perm = new JLabel("numGen2Perm"); lblNumGen2Perm.setAlignmentX(Component.CENTER_ALIGNMENT); panel_15.add(lblNumGen2Perm); spinnerNumGen2Perm = new JSpinner();//MutacionHeuristica spinnerNumGen2Perm.setModel(new SpinnerNumberModel(3, 0,6,1)); panel_15.add(spinnerNumGen2Perm); lblNumGens2Ins = new JLabel("numGens2Ins"); lblNumGens2Ins.setAlignmentX(Component.CENTER_ALIGNMENT); panel_15.add(lblNumGens2Ins); spinnerNumGens2Ins = new JSpinner(new SpinnerNumberModel(1, 1,6,1));//MutacionInsercion panel_15.add(spinnerNumGens2Ins); lblNumG2Inv = new JLabel("numG2Inv"); lblNumG2Inv.setAlignmentX(Component.CENTER_ALIGNMENT); panel_15.add(lblNumG2Inv); spinnerNumG2Inv = new JSpinner();//MutacionIntercambio spinnerNumG2Inv.setModel(new SpinnerNumberModel(2,1,6,1)); panel_15.add(spinnerNumG2Inv); //----------------- JPanel panel_2 = new JPanel(); panel.add(panel_2, BorderLayout.CENTER); panel_2.setLayout(new BorderLayout(0, 0)); tabbedPane = new JTabbedPane(); panel_2.add(tabbedPane, BorderLayout.CENTER); panel_6 = new JPanel(); tabbedPane.addTab("Aprendizaje", null, panel_6, null); tabbedPane.setMnemonicAt(0, KeyEvent.VK_Z); panel_6.setLayout(new BorderLayout(0, 0)); p2d = new Plot2DPanel(); p2d.addLinePlot("Globales", new double[] {0}); p2d.addLinePlot("Locales", new double[] {0}); p2d.addLinePlot("media", new double[] {0}); p2d.addLegend("WEST"); panel_6.add(p2d); labelSolucion = new JLabel("solucion: ninguna"); panel_6.add(labelSolucion, BorderLayout.SOUTH); panel_7 = new JPanel(true); tabbedPane.addTab("Problem View", null, panel_7, null); tabbedPane.setMnemonicAt(1, KeyEvent.VK_3); panel_7.setLayout(new BorderLayout(0, 0)); JPanel panel_8 = new JPanel(); tabbedPane.addTab("Log", null, panel_8, null); // tabbedPane.setMnemonicAt(2, KeyEvent.VK_G); panel_8.setLayout(new BorderLayout(0, 0)); JScrollPane scrollPane = new JScrollPane(); panel_8.add(scrollPane, BorderLayout.CENTER); jtaLog = new JTextArea(); scrollPane.setViewportView(jtaLog); tabbedPane.setSelectedIndex(0); jEditorPane = new JEditorPane(); jEditorPane.setEditable(false); jEditorPane.setContentType("text/html"); HTMLEditorKit hek = new HTMLEditorKit(); StyleSheet csshek = hek.getStyleSheet(); csshek.addRule("body{margin:0px 20px;font-family: \"Segoe UI\", Arial, Helvetica, sans-serif;}"); jEditorPane.setCursor(hek.getDefaultCursor()); jEditorPane.setEditorKit(hek); try { jEditorPane.read(getClass().getModule().getResourceAsStream("res/help.html"), hek); } catch (IOException e) { } JScrollPane spHtml = new JScrollPane(jEditorPane); tabbedPane.addTab("Ayuda", spHtml); tabbedPane.setMnemonicAt(3, KeyEvent.VK_U); jEditorPane.addHyperlinkListener(new CustomHyperLinkListener()); panelGeneral .addMouseListener(new TitleClickAdapter(panel_4)); panelCromosoma.addMouseListener(new TitleClickAdapter(panel_17)); panelSeleccion.addMouseListener(new TitleClickAdapter(panel_10)); panelCruce .addMouseListener(new TitleClickAdapter(panel_13)); panelMutacion .addMouseListener(new TitleClickAdapter(panel_15)); } }
true
79db26ac22006ac8d37989a79fff963ad0afe039
Java
temvvo/loan-process
/spring-app/src/main/java/com/loanprocess/handler/dto/LoanSubmited.java
UTF-8
407
1.945313
2
[]
no_license
package com.loanprocess.handler.dto; import com.loanprocess.domain.entity.Borrower; import lombok.*; import java.math.BigDecimal; @NoArgsConstructor @Builder(toBuilder = true) @AllArgsConstructor @Getter public class LoanSubmited { Integer loanId; BigDecimal requestedAmount; Integer termMonths; Integer termYears; BigDecimal annualInterest; String type; Borrower borrower; }
true
d278e48d3d69134533d8b7f0beac3d4c1301853f
Java
zonepast/BuSoftAdmin
/app/src/main/java/com/prudent/busoftadmin/data/api/model/DashboardData/Request/DashboardDataRequest.java
UTF-8
1,125
1.875
2
[]
no_license
package com.prudent.busoftadmin.data.api.model.DashboardData.Request; import javax.annotation.Generated; import com.google.gson.annotations.SerializedName; @Generated("net.hexar.json2pojo") @SuppressWarnings("unused") public class DashboardDataRequest { public DashboardDataRequest(String mCorpcentre, String mReportname, String mUserId) { this.mCorpcentre = mCorpcentre; this.mReportname = mReportname; this.mUserId = mUserId; } @SerializedName("corpcentre") private String mCorpcentre; @SerializedName("reportname") private String mReportname; @SerializedName("userId") private String mUserId; public String getCorpcentre() { return mCorpcentre; } public void setCorpcentre(String corpcentre) { mCorpcentre = corpcentre; } public String getReportname() { return mReportname; } public void setReportname(String reportname) { mReportname = reportname; } public String getUserId() { return mUserId; } public void setUserId(String userId) { mUserId = userId; } }
true
4e1a3ef87e13952de6505dc8b0f01dc81f604df4
Java
JamesDansie/CS143
/PA4/csc143/data_structures/OverfillException.java
UTF-8
175
2.140625
2
[]
no_license
package csc143.data_structures; public class OverfillException extends DataStructureException { public OverfillException(String msg) { super(msg); } }
true
ec4741e4279d90df2aa64554ac0a536d6412c839
Java
yuanguojie/new1
/Hospital_Fixed_Asset_Management_System/src/main/java/domainextand/takestockview.java
UTF-8
2,144
1.875
2
[]
no_license
package domainextand; public class takestockview { private Integer id; private String billNo; private String TSDate; private Integer flowFlag; private String deptId; private String createEmpId; private String storageId; private Integer sortCode; private Integer depr_id; private Integer totalAmount; private Integer lostAmount; private String assetId; private String operation; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getBillNo() { return billNo; } public void setBillNo(String billNo) { this.billNo = billNo; } public String getTSDate() { return TSDate; } public void setTSDate(String tSDate) { TSDate = tSDate; } public Integer getFlowFlag() { return flowFlag; } public void setFlowFlag(Integer flowFlag) { this.flowFlag = flowFlag; } public String getDeptId() { return deptId; } public void setDeptId(String deptId) { this.deptId = deptId; } public String getCreateEmpId() { return createEmpId; } public void setCreateEmpId(String createEmpId) { this.createEmpId = createEmpId; } public String getStorageId() { return storageId; } public void setStorageId(String storageId) { this.storageId = storageId; } public Integer getSortCode() { return sortCode; } public void setSortCode(Integer sortCode) { this.sortCode = sortCode; } public Integer getDepr_id() { return depr_id; } public void setDepr_id(Integer depr_id) { this.depr_id = depr_id; } public Integer getTotalAmount() { return totalAmount; } public void setTotalAmount(Integer totalAmount) { this.totalAmount = totalAmount; } public Integer getLostAmount() { return lostAmount; } public void setLostAmount(Integer lostAmount) { this.lostAmount = lostAmount; } public String getAssetId() { return assetId; } public void setAssetId(String assetId) { this.assetId = assetId; } public String getOperation() { return operation; } public void setOperation(String operation) { this.operation = operation; } }
true
e242afcd040b455f80b748e060b3dab48efd8f72
Java
adamszysiak/library_management
/src/main/java/com/spring/librarymanagement/models/BookEntity.java
UTF-8
3,214
2.6875
3
[]
no_license
package com.spring.librarymanagement.models; import javax.persistence.*; import java.util.Date; import java.util.Objects; @Entity @Table(name = "books") public class BookEntity { public BookEntity() { } @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "ID") private Long id; @Column(name = "NAME", nullable = false) private String name; @Column(name = "AUTHOR") private String author; @Column(name = "PUBLISHER") private String publisher; @Column(name = "QUANTITY") private int quantity; @Column(name = "ISSUED") private int issued; @Column(name = "ADDED_DATE") private Date addedDate; @Column(name = "USER_ID") private Long userID; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getPublisher() { return publisher; } public void setPublisher(String publisher) { this.publisher = publisher; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public int getIssued() { return issued; } public void setIssued(int issued) { this.issued = issued; } public Date getAddedDate() { return addedDate; } public void setAddedDate(Date addedDate) { this.addedDate = addedDate; } public Long getUserID() { return userID; } public void setUserID(Long userID) { this.userID = userID; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; BookEntity bookEntity = (BookEntity) o; return quantity == bookEntity.quantity && issued == bookEntity.issued && Objects.equals(id, bookEntity.id) && Objects.equals(name, bookEntity.name) && Objects.equals(author, bookEntity.author) && Objects.equals(publisher, bookEntity.publisher) && Objects.equals(addedDate, bookEntity.addedDate) && Objects.equals(userID, bookEntity.userID); } @Override public int hashCode() { return Objects.hash(id, name, author, publisher, quantity, issued, addedDate, userID); } @Override public String toString() { return "BookEntity{" + "id=" + id + ", name='" + name + '\'' + ", author='" + author + '\'' + ", publisher='" + publisher + '\'' + ", quantity=" + quantity + ", issued=" + issued + ", addedDate='" + addedDate + '\'' + ", userID=" + userID + '}'; } }
true
79292014551e01b549c394460ac591dedae2521a
Java
reddysainathn/servlets
/StructsWebProj/src/com/interceptor/CustomInterceptor.java
UTF-8
584
2.40625
2
[]
no_license
package com.interceptor; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.AbstractInterceptor; public class CustomInterceptor extends AbstractInterceptor { @Override public String intercept(ActionInvocation actionInvocation) throws Exception { System.out .println("********CustomInterceptor::prerequest Processing********"); // It will invoke the result from ActionClass String result = actionInvocation.invoke(); System.out .println("********CustomInterceptor::postrequest Processing********"); return result; } }
true
7764a2d3f90ec53ef93a58218429128304d538eb
Java
jb332/projet_poo_clavardage
/POO_Clavardage/src/network/LogoutPacket.java
UTF-8
997
3.109375
3
[]
no_license
package network; /** * Disconnection request packet. */ public class LogoutPacket extends LoginPacket { /** * The MAC address of the requesting user. */ private String requestingUserMacAddress; /** * Constructor. * @param macAddress the requesting user MAC address */ protected LogoutPacket(String macAddress) { this.requestingUserMacAddress = macAddress; } /** * Get the requesting user MAC address. * @return the requesting user MAC address */ protected String getRequestingUserMacAddress() { return this.requestingUserMacAddress; } /** * Serialization method converting this packet to a string to be sent over the network. It implements the abstract method from the mother class. * @return the serialized packet */ @Override protected String getDataToSend() { return super.getFlag() + ";" + this.getRequestingUserMacAddress() + ";"; } }
true
6b1387f0099c06b7fe8be84fec81791217bb97c0
Java
alexiszaharia/MeasureAppPDM
/app/src/main/java/com/example/stud/measureapp/WidgetService.java
UTF-8
366
1.78125
2
[]
no_license
package com.example.stud.measureapp; import android.content.Intent; import android.widget.RemoteViewsService; /** * Created by stud on 3/28/2018. */ public class WidgetService extends RemoteViewsService { @Override public RemoteViewsFactory onGetViewFactory(Intent intent) { return new MasuratoareWidgetFactory(getApplicationContext()); } }
true
db7a3f36ce8b459011dbb7da2087bce332e0f126
Java
hoangquan1807/HoangQuan1
/ProgramRun.java
UTF-8
6,635
3.09375
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 view; import controller.ComputerAction; import dao.ComputerDAO; import dto.ComputerDTO; import java.util.List; import java.util.Scanner; /** * * @author Nups */ public class ProgramRun { public double checkDouble(String s){ try{ double n = Double.parseDouble(s); return n; }catch(Exception e){ return -1; } } public int checkInt(String s){ try{ int m = Integer.parseInt(s); return m; }catch(Exception e){ return -1; } } public static void main(String[] args) { // DBConnector con = new DBConnector(); // Statement st = null; // ResultSet rs = null; // String s = "SELECT * FROM COMPUTER"; // try { // st = con.getCon().createStatement(); // rs = st.executeQuery(s); // } catch (SQLException ex) { // Logger.getLogger(ProgramRun.class.getName()).log(Level.SEVERE, null, ex); // } ComputerDTO dt = new ComputerDTO(); ComputerDAO dao = new ComputerDAO(); Scanner sc = new Scanner(System.in); ComputerAction action = new ComputerAction(); do{ System.out.println("CHOICE NUMBER"); System.out.println("1. ADD"); System.out.println("2. LIST"); System.out.println("3. UPDATE"); System.out.println("4. DELETE"); System.out.println("5. LIST BY PRICE"); System.out.println("6. SEARCH"); System.out.println("7. SEARCH BY NAME"); System.out.println("8. Exit"); int choice = sc.nextInt(); switch(choice){ case 1: System.out.println("NHAP DU LIEU CHO COMPUTER: "); System.out.println("Nhap code: "); String code = sc.next(); dt.setCode(code); System.out.println("Nhap name: "); String name = sc.next(); dt.setName(name); System.out.println("Nhap price: "); double price = sc.nextDouble(); dt.setPrice(price); System.out.println("Nhap quantity: "); int quantity = sc.nextInt(); dt.setQuantity(quantity); action.create(dt); break; case 2: System.out.println("LIST ALL:"); for(ComputerDTO c: dao.readAll()){ System.out.println("----------------------------------"); System.out.println(c.getCode()); System.out.println(c.getName()); System.out.println(c.getPrice()); System.out.println(c.getQuantity()); System.out.println("----------------------------------"); } break; case 3: System.out.println("UPDATE PRICE TU COMPUTER DUA VAO CODE: "); System.out.println("Nhap code: "); String code1 = sc.next(); dt.setCode(code1); System.out.println("Nhap Price: "); double price1 = sc.nextDouble(); dt.setPrice(price1); action.update(dt); break; case 4: System.out.println("XOA DU LIEU COMPUTER DUA VAO PRICE: "); System.out.println("Nhap price: "); String code5 = sc.next(); dt.setCode(code5); action.delete(code5); break; case 5: System.out.println("Nhap Price"); double price3 = sc.nextDouble(); dt.setPrice(price3); List<ComputerDTO> lst = action.readByPrice(); for(ComputerDTO item : lst){ System.out.println("----------------------------------"); System.out.println(item.getCode()); System.out.println(item.getName()); System.out.println(item.getPrice()); System.out.println(item.getQuantity()); System.out.println("----------------------------------"); } break; case 6: System.out.println("Nhap price 1: "); double price4 = sc.nextDouble(); dt.setPrice(price4); System.out.println("Nhap price 2: "); double price5 = sc.nextDouble(); dt.setPrice(price5); for(ComputerDTO prs: dao.readByPriceBetween(price4, price5)){ System.out.println("----------------------------------"); System.out.println(prs.getCode()); System.out.println(prs.getName()); System.out.println(prs.getPrice()); System.out.println(prs.getQuantity()); System.out.println("----------------------------------"); } break; case 7: System.out.println("Nhap name: "); String name1 = sc.next(); dt.setName(name1); for(ComputerDTO nas: dao.readByName(name1)){ System.out.println("----------------------------------"); System.out.println(nas.getCode()); System.out.println(nas.getName()); System.out.println(nas.getPrice()); System.out.println(nas.getQuantity()); System.out.println("----------------------------------"); } break; case 8: System.exit(choice); } }while(true); } }
true
bf86d90dd155638e2f93ee1c45ee4e0c1fb60229
Java
finnmans/ProjetoLPOO
/src/br/com/poli/utils/Vector2Int.java
UTF-8
676
3.03125
3
[]
no_license
/* Projeto de LPOO Dupla: Alexandre Candido Souza Felipe Vasconcelos */ package br.com.poli.utils; /** * Classe Auxiliar que guarda um par ordenado de inteiros (X,Y); */ public class Vector2Int { private int x; private int y; public int getY() { return y; } public int getX() { return x; } public final void setXY(int x, int y) { this.setX(x); this.setY(y); } public final void setX(int x) { this.x = x; } public final void setY(int y) { this.y = y; } public Vector2Int(int x, int y) { this.setX(x); this.setY(y); } public boolean compare(int x, int y) { return this.getX() == x && this.getY() == y; } }
true
d59b1b12fa818112601c56cee983a32bfe0c862b
Java
Themion/Calculator
/app/src/main/java/com/example/themion/calculator/Node.java
UTF-8
2,726
2.671875
3
[]
no_license
package com.example.themion.calculator; /** * Created by Themion on 2017-05-24. */ class Node { final int NOT_AN_OPERATOR = -1; final int noFunc = 0; /*------------------------------------------------------------------------------------------------------------------------------*/ private double printData; private double calcData; private int calcOp; private int printOp; private int point; private int func; private boolean pm; private boolean hit; private Node next; private Node prev; private CalculateList motherList; private CalculateList bracList; /*------------------------------------------------------------------------------------------------------------------------------*/ Node() { this.printData = 0; this.calcData = 0; this.printOp = NOT_AN_OPERATOR; this.calcOp = NOT_AN_OPERATOR; this.point = 0; this.func = noFunc; this.pm = false; //plus or minus this.hit = false; //if calculation butten is hit this.next = null; this.prev = null; this.motherList = null; this.bracList = null; } /*------------------------------------------------------------------------------------------------------------------------------*/ double getPrintData() {return this.printData;} double getCalcData() {return this.calcData;} int getPrintOp() {return this.printOp;} int getCalcOp() {return this.calcOp;} int getPoint() {return this.point;} int getFunc() {return this.func;} boolean getPM() {return this.pm;} boolean getHit() {return this.hit;} Node getNext() {return this.next;} Node getPrev() {return this.prev;} CalculateList getMotherList() {return this.motherList;} CalculateList getBracList() {return this.bracList;} /*------------------------------------------------------------------------------------------------------------------------------*/ void setPrintData(double printData) {this.printData = printData; this.calcData = printData;} void setCalcData(double calcData) {this.calcData = calcData;} void setPrintOp(int printOp) {this.printOp = printOp; this.calcOp = printOp;} void setCalcOp(int calcOp) {this.calcOp = calcOp;} void setPoint(int point) {this.point = point;} void setFunc(int func) {this.func = func;} void setPM(boolean pm) {this.pm = pm;} void setHit(boolean hit) {this.hit = hit;} void setNext(Node next) {this.next = next;} void setPrev(Node prev) {this.prev = prev;} void setMotherList(CalculateList motherList) {this.motherList = motherList;} void setBracList(CalculateList bracList) {this.bracList = bracList;} }
true
21f0f9dd2208876fff19811d231f1178361af97e
Java
bellmit/app-demo
/demo-admin/src/main/java/com/drakelee/demo/admin/controller/member/MemberController.java
UTF-8
5,367
1.929688
2
[]
no_license
package com.drakelee.demo.admin.controller.member; import com.base.components.common.util.ConvertUtil; import com.drakelee.demo.admin.dto.common.JsonResult; import com.drakelee.demo.admin.dto.fancytree.TreeNodeData; import com.drakelee.demo.admin.dto.member.TreeParam; import com.drakelee.demo.admin.service.auth.SysRoleService; import com.drakelee.demo.admin.service.member.MemberNodeBuilder; import com.drakelee.demo.admin.service.member.SysMemberAttrService; import com.drakelee.demo.admin.service.member.SysMemberService; import com.drakelee.demo.common.constants.sys.GatewayPath; import com.drakelee.demo.common.domain.admin.SysMember; import com.drakelee.demo.database.dao.admin.SysMemberDao; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.List; import java.util.Map; /** * MemberController * * @author <a href="drakelee1221@gmail.com">LiGeng</a> * @version 1.0.0, 2018-03-17 10:33 */ @Controller @RequestMapping(GatewayPath.ADMIN) public class MemberController { @Autowired private SysMemberService sysMemberService; @Autowired private SysMemberAttrService sysMemberAttrService; @Autowired private SysRoleService sysRoleService; @GetMapping(value = {"/member/index"}) public String index(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) { return "member/index"; } @GetMapping(value = {"/member/tree"}) @ResponseBody public ResponseEntity tree(HttpServletRequest request, HttpServletResponse response) { List<TreeNodeData<SysMember>> treeNodeData = sysMemberService.loadTreeNodes(new TreeParam(request), new MemberNodeBuilder(), SysMemberDao.ADMIN_TREE_KIND); return ResponseEntity.ok(treeNodeData); } @GetMapping(value = {"/member/attr/tree"}) @ResponseBody public ResponseEntity selectedTree(HttpServletRequest request, HttpServletResponse response, @RequestParam Map<String, String> params) { return ResponseEntity.ok( sysMemberAttrService.loadMemberAttrTree(new TreeParam(request), ConvertUtil.checkNotNull(params, "memberId", String.class))); } @PostMapping(value = {"/member/attr/tree/select"}) @ResponseBody public ResponseEntity updateMemberTree(HttpServletRequest request, HttpServletResponse response, @RequestParam Map<String, String> params) { String selectIds = params.get("selectIds"); String[] ids = StringUtils.split(selectIds, ","); sysMemberAttrService .updateMemberTree(ids, ConvertUtil.checkNotNull(params, "memberId", String.class)); return ResponseEntity.ok(JsonResult.success()); } @GetMapping(value = {"/member/attr/tree/select"}) @ResponseBody public ResponseEntity getMemberTree(HttpServletRequest request, HttpServletResponse response, @RequestParam Map<String, String> params) { List data = sysMemberAttrService .getMemberTree(ConvertUtil.checkNotNull(params, "memberId", String.class)); return ResponseEntity.ok(JsonResult.success(data)); } @PostMapping("/member/saveOrUpdate") @ResponseBody public ResponseEntity saveOrUpdate(SysMember member) { member.setTreeKind(SysMemberDao.ADMIN_TREE_KIND); SysMember rs; if (StringUtils.isNotBlank(member.getId())) { rs = sysMemberService.updateBaseInfo(member); } else { rs = sysMemberService.addMember(member); } return ResponseEntity.ok(JsonResult.success(new MemberNodeBuilder().buildNode(rs, null, null))); } @PostMapping("/member/delete") @ResponseBody public ResponseEntity deleteMember(String id) { sysMemberService.delete(id); return ResponseEntity.ok(JsonResult.success()); } @PostMapping("/member/doMove") @ResponseBody public ResponseEntity doMove(String srcId, String targetId, String hitMode) { sysMemberService.updateToMove(srcId, targetId, hitMode); return ResponseEntity.ok(JsonResult.success()); } @GetMapping(value = {"/member/role"}) @ResponseBody public ResponseEntity memberRoles(HttpServletRequest request, HttpServletResponse response, @RequestParam Map<String, String> param) { String id = ConvertUtil.checkNotNull(param, "memberId", String.class); return ResponseEntity.ok(sysRoleService.findRoleByMemberId(id)); } @GetMapping(value = {"/member/auth/tree"}) @ResponseBody public ResponseEntity memberAuthTree(HttpServletRequest request, HttpServletResponse response, @RequestParam Map<String, String> param) { String id = ConvertUtil.checkNotNull(param, "memberId", String.class); return ResponseEntity.ok(sysRoleService.findAuthAppInfoByMemberId(id)); } }
true
5a17066dad9c4c96ac00696b5d266e295b1b2cf5
Java
rufuszhu/Test
/TaxiLimoNewUI/src/digital/dispatch/TaxiLimoNewUI/Adapters/NavigationItemAdapter.java
UTF-8
235
2.109375
2
[]
no_license
package digital.dispatch.TaxiLimoNewUI.Adapters; public class NavigationItemAdapter { public String title; public int icon; public NavigationItemAdapter(String title, int icon) { this.title = title; this.icon = icon; } }
true
2d9140b441658f06a6b7139fb1a6433e13657fe9
Java
nottpty/SoftSpecProj
/core/src/com/mygdx/game/skills/DoubleDamage_Skill.java
UTF-8
1,880
3.0625
3
[]
no_license
package com.mygdx.game.skills; import com.mygdx.game.sprites.Player; /** * Created by SAS-Maxnot19 on 28/5/2559. */ public class DoubleDamage_Skill implements SkillHero { private boolean check,canUse; private int level,price; private String name; private Player player; private float duration; private int cooldown; public DoubleDamage_Skill(Player player){ canUse = true; check = false; this.player = player; name = "x2 Damage"; this.level = 0; price = 400; duration = 0; cooldown = 90; } @Override public void doAction(Player player) { if(canUse) { player.setDmg(player.getDmg() * 2); canUse = false; } } @Override public boolean check() { return check; } @Override public void buySkill() { if(check) upgrade(); if(!check) { this.check = true; levelUp(); } } @Override public String getName() { return this.name; } @Override public String getText() { return this.name+"\nLevel : "+this.level+"\nPrice : "+this.price; } @Override public void levelUp() { level++; cooldown -= 5; price += (int)(price*1.2); } public void upgrade() { if(check) { levelUp(); } } public boolean canUse(){ return canUse; } @Override public int getPrice() { return this.price; } public void update(float dt){ duration += dt; if(duration >= 10){ player.setDmg(player.getNormalDamage()); checkCooldown(); } } public void checkCooldown(){ if(duration >= cooldown) { duration = 0; canUse = true; } } }
true
0f3e2889d37d167dccd59e1e0fd2415c0c212bf6
Java
AlanEmersic/web-shop
/src/main/java/hr/kingict/webshop/mapper/ProductDtoMapper.java
UTF-8
196
2.0625
2
[]
no_license
package hr.kingict.webshop.mapper; import hr.kingict.webshop.dto.ProductDto; import hr.kingict.webshop.entity.Product; public interface ProductDtoMapper { ProductDto map(Product product); }
true