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
b2b3c092bd8912a3b284cdc22cf2358cd69ff053
Java
Ramon-Arias25/neo-tp4
/neotp4Model/Canine.java
UTF-8
863
2.84375
3
[]
no_license
package neotp4Model; /** * * @author ramon.arias * date: 13/05/2021 * current version: 1 * Canina class: to instantiate k9 member through its subclasses * */ public abstract class Canine { private String id; private String name; private String type; private String breed; private String sex; public Canine(String id, String nombre, String tipo, String raza, String sexo) { super(); this.id = id; this.name = nombre; this.type = tipo; this.breed = raza; this.sex = sexo; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } @Override public String toString() { return "Canine [id=" + id + ", name=" + name + ", type=" + type + ", breed=" + breed + ", sex=" + sex + "]"; } }
true
5f6477edc3782bccb6b817688566eda8bc22dd44
Java
mjochab/PZ_2019_Lab2_Gr2
/Dziennik/src/main/java/modelFX/FrequentlyFx.java
UTF-8
1,929
2.78125
3
[ "MIT" ]
permissive
package modelFX; import Modele.Frequently; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleLongProperty; import javafx.beans.property.SimpleObjectProperty; import java.util.Date; public class FrequentlyFX extends Frequently { private SimpleLongProperty frequentlyID = new SimpleLongProperty(); private SimpleIntegerProperty absense= new SimpleIntegerProperty(); private Date date = new Date(); private ObjectProperty<StudentFx> StudentFxObjectProperty = new SimpleObjectProperty<>(); public long getFrequentlyID() { return frequentlyID.get(); } public SimpleLongProperty frequentlyIDProperty() { return frequentlyID; } public void setFrequentlyID(long frequentlyID) { this.frequentlyID.set(frequentlyID); } public int getAbsense() { return absense.get(); } public SimpleIntegerProperty absenseProperty() { return absense; } public void setAbsense(int absense) { this.absense.set(absense); } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public StudentFx getStudentFxObjectProperty() { return StudentFxObjectProperty.get(); } public ObjectProperty<StudentFx> studentFxObjectPropertyProperty() { return StudentFxObjectProperty; } public void setStudentFxObjectProperty(StudentFx studentFxObjectProperty) { this.StudentFxObjectProperty.set(studentFxObjectProperty); } @Override public String toString() { return "FrequentlyFX{" + "frequentlyID=" + frequentlyID + ", absense=" + absense + ", date=" + date + ", StudentFxObjectProperty=" + StudentFxObjectProperty + '}'; } }
true
5502d2d5453c0973802210fe0bb33957ad6dd2c7
Java
fmselab/codecover2
/misc/instrumentation/parsers/release/src/org/gbt2/instrumentation/cobol85/manipulators/ConditionManipulator.java
UTF-8
1,261
2.359375
2
[]
no_license
/////////////////////////////////////////////////////////////////////////////// // // $Id: ConditionManipulator.java 1 2007-12-12 17:37:26Z t-scheller $ // // created at: 26.03.2007 23:49:39 // /////////////////////////////////////////////////////////////////////////////// package org.gbt2.instrumentation.cobol85.manipulators; import java.io.PrintWriter; import org.gbt2.instrumentation.cobol85.syntaxtree.ProgramUnit; /** * This is an interface for condition manipulators. A condition manipulator * should be used to insert counters into the source code. The counter * variable declaration is also placed in a statement manipulator. * * @author Stefan Franke * @version 1.0 - 27.03.2007 * */ public interface ConditionManipulator { /** * Generates all condition counter that appears in the given program unit. * Writes results to the output writer. * * @param programUnit the active program unit * @param printWriter the output writer */ void generateConditionCounter(ProgramUnit programUnit, PrintWriter printWriter); /** * Manipulates the source code for condition coverage criteria. * * @param printWriter the output writer */ void manipulate(PrintWriter printWriter); }
true
d35c2dc28a42955a047f921a3b2669ee2cadcd85
Java
hongchao1117/ALoffer
/src/Interview/TencentDemo01.java
UTF-8
1,000
3.046875
3
[]
no_license
package Interview; import java.util.ArrayList; import java.util.Scanner; public class TencentDemo01 { public static void main(String[] args) { Scanner input = new Scanner(System.in); int t = input.nextInt(); for (int i = 0; i < t; i++) { int len = input.nextInt(); String s = input.next(); if (len<11){ System.out.println("NO"); continue; } ArrayList<Character> list = new ArrayList<>(); char[] chars = s.toCharArray(); for (int j = 0; j < chars.length; j++) { if (list.size()==0 && chars[j] == '8'){ list.add(chars[j]); } if (list.size()>0){ list.add(chars[j]); } } if (list.size()>=11){ System.out.println("YES"); }else { System.out.println("NO"); } } } }
true
6e3b5fcd3daaf976d6cdadd97cb26108fe1671ee
Java
maggan1968/JavaProgramming_B23
/replit/Loop_Practice/PrintVowels.java
UTF-8
859
3.4375
3
[]
no_license
package Loop_Practice; import java.util.Scanner; public class PrintVowels { public static void main(String[] args) { Scanner scan= new Scanner(System.in); String word = scan.nextLine(); //write your code below String result=""; for(int i=0; i<word.length();i++){ char ch=word.charAt(i); if( ch=='A' || ch=='E'|| ch=='I'|| ch=='O' ||ch=='U'|| ch=='a' || ch=='e'|| ch== 'i' || ch=='o' ||ch=='u'){ result +=ch; } } System.out.print(result); } } /* Create a program that will take the given String In and print out all the vowels from the String. Example: Input: howdyho Output: oo Input: howdyho Output: oo Input: huehuehuehue Output: ueueueue */
true
b90ccf8560b0b3ba3ab1382234853db3b3ec8a73
Java
fengling1106/lark
/lark-bean/src/main/java/com/valen/lark/bean/message/RequestMsgBody.java
UTF-8
1,412
2.234375
2
[]
no_license
/** * <p>Title: BusinessInfo.java</p> * <p>Description: </p> * <p>Copyright: Copyright (c) 2019</p> * <p>Company: valen.com</p> * @author fengling * @date 2020年2月21日 * @version 1.0 */ package com.valen.lark.bean.message; import java.io.Serializable; /** * <p>Title: BusinessInfo</p> * <p>Description: </p> * @author fengling * @date 2020年2月21日 */ public class RequestMsgBody implements Serializable { private static final long serialVersionUID = 300002020022102L; //消息体 private int mainBusiId; //主业务类型,长度8位 private int subBusiId; //子业务类型,长度8位 private int operateType; //业务操作类型,长度8位 private Object busiObj; //业务对象 public void setMainBusiId(int mainBusiId) { this.mainBusiId = mainBusiId; } public int getMainBusiId() { return this.mainBusiId; } // public void setSubBusiId(int subBusiId) { this.subBusiId = subBusiId; } public int getSubBusiType() { return this.subBusiId; } // public void setOperateType(int operateType) { this.operateType = operateType; } public int getOperateType() { return this.operateType; } // public void setBusiObj(Object busiObj) { this.busiObj = busiObj; } public Object getBusiObj() { return this.busiObj; } }
true
1a827ce1b074ca49fc7168d319320ed5c98b0c81
Java
KnnethKong/housekeeper
/app/src/main/java/com/haiwai/housekeeper/wxapi/WXPayEntryActivity.java
UTF-8
2,281
1.9375
2
[]
no_license
package com.haiwai.housekeeper.wxapi; import com.haiwai.housekeeper.R; import com.haiwai.housekeeper.https.Contants; import com.haiwai.housekeeper.utils.DateUtil; import com.haiwai.housekeeper.utils.MD5Util; import com.haiwai.housekeeper.view.TopViewNormalBar; import com.tencent.mm.sdk.constants.ConstantsAPI; import com.tencent.mm.sdk.modelbase.BaseReq; import com.tencent.mm.sdk.modelbase.BaseResp; import com.tencent.mm.sdk.modelpay.PayReq; import com.tencent.mm.sdk.openapi.IWXAPI; import com.tencent.mm.sdk.openapi.IWXAPIEventHandler; import com.tencent.mm.sdk.openapi.WXAPIFactory; import android.app.Activity; import android.app.AlertDialog; import android.content.Intent; import android.os.Bundle; import android.provider.SyncStateContract; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.TextView; import java.util.Random; public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler { private static final String TAG = "MicroMsg.SDKSample.WXPayEntryActivity"; private IWXAPI api; TopViewNormalBar wx_result; TextView tv_show; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.pay_result); api = WXAPIFactory.createWXAPI(this, Contants.APP_ID); api.handleIntent(getIntent(), this); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); setIntent(intent); api.handleIntent(intent, this); } @Override public void onReq(BaseReq req) { } @Override public void onResp(BaseResp resp) { if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) { wx_result = (TopViewNormalBar) findViewById(R.id.wx_result); wx_result.setOnBackListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); tv_show = (TextView) findViewById(R.id.tv_show); if (resp.errCode == 0) { tv_show.setText("支付成功"); } else { tv_show.setText("支付失败"); } } } }
true
f669b13dc2310cc937ca9d99c3e1bb31025fb1e4
Java
DEIS-Project-EU/DDI-Scripting-Tools
/ODE_Metamodel/ode.concept.deis/src/top/failureLogic/Cause.java
UTF-8
2,301
2.046875
2
[ "MIT", "Apache-2.0", "BSD-3-Clause" ]
permissive
/** */ package top.failureLogic; import top.odeBase.BaseElement; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Cause</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link top.failureLogic.Cause#getCauseType <em>Cause Type</em>}</li> * <li>{@link top.failureLogic.Cause#getFailure <em>Failure</em>}</li> * </ul> * * @see top.failureLogic.FailureLogic_Package#getCause() * @model * @generated */ public interface Cause extends BaseElement { /** * Returns the value of the '<em><b>Cause Type</b></em>' attribute. * The literals are from the enumeration {@link top.failureLogic.CauseType}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Cause Type</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Cause Type</em>' attribute. * @see top.failureLogic.CauseType * @see #setCauseType(CauseType) * @see top.failureLogic.FailureLogic_Package#getCause_CauseType() * @model * @generated */ CauseType getCauseType(); /** * Sets the value of the '{@link top.failureLogic.Cause#getCauseType <em>Cause Type</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Cause Type</em>' attribute. * @see top.failureLogic.CauseType * @see #getCauseType() * @generated */ void setCauseType(CauseType value); /** * Returns the value of the '<em><b>Failure</b></em>' reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Failure</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Failure</em>' reference. * @see #setFailure(Failure) * @see top.failureLogic.FailureLogic_Package#getCause_Failure() * @model * @generated */ Failure getFailure(); /** * Sets the value of the '{@link top.failureLogic.Cause#getFailure <em>Failure</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Failure</em>' reference. * @see #getFailure() * @generated */ void setFailure(Failure value); } // Cause
true
45e754bca9f9b817de78f30b4db31728426427b3
Java
zhuifengshen/JavaDemo
/src/mike/principle/QuackBehavior.java
UTF-8
127
2.0625
2
[]
no_license
package mike.principle; /** * Created by Devin on 2016/7/22. */ public interface QuackBehavior { public void quack(); }
true
8fd9eba48b06f095141306071a18fc25426f918b
Java
marinovtom/Algorithms
/SearchAndSort/BinarySearch.java
UTF-8
796
3.796875
4
[ "MIT" ]
permissive
public class BinarySearch { private static int binarySearch(int[] sortedArray, int searchFor, int startIndex, int endIndex) { int halfArrayIndex = (endIndex + startIndex) / 2; if(sortedArray[halfArrayIndex] == searchFor) { return halfArrayIndex; } if(sortedArray[halfArrayIndex] > searchFor) { return binarySearch(sortedArray, searchFor, startIndex, halfArrayIndex); } if(sortedArray[halfArrayIndex] < searchFor) { return binarySearch(sortedArray, searchFor, halfArrayIndex, endIndex); } return -1; } public static void main(String[] args) { int[] sortedArray = {1, 7, 9, 14, 18, 21, 222, 901, 140981}; // example data int binarySearchResult = binarySearch(sortedArray, 222, 0, sortedArray.length - 1); System.out.println(binarySearchResult); } }
true
7173dacc00d812c888722c5330a39e37799bc7ad
Java
DTStack/Taier
/taier-scheduler/src/main/java/com/dtstack/taier/scheduler/executor/DatasourceOperator.java
UTF-8
6,293
1.789063
2
[ "Apache-2.0" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dtstack.taier.scheduler.executor; import com.alibaba.fastjson.JSONObject; import com.dtstack.taier.common.enums.EComponentType; import com.dtstack.taier.common.exception.ErrorCode; import com.dtstack.taier.common.exception.TaierDefineException; import com.dtstack.taier.datasource.api.base.ClientCache; import com.dtstack.taier.datasource.api.client.IClient; import com.dtstack.taier.datasource.api.dto.FileStatus; import com.dtstack.taier.datasource.api.dto.source.ISourceDTO; import com.dtstack.taier.pluginapi.constrant.ConfigConstant; import com.dtstack.taier.pluginapi.exception.ExceptionUtil; import com.dtstack.taier.pluginapi.pojo.ComponentTestResult; import com.dtstack.taier.pluginapi.pojo.FileResult; import com.dtstack.taier.scheduler.datasource.convert.engine.PluginInfoToSourceDTO; import com.dtstack.taier.scheduler.service.ClusterService; import com.dtstack.taier.scheduler.service.ComponentService; import com.google.common.collect.Lists; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; import java.util.Objects; /** * rdb executor * * @author :wangchuan * date:Created in 14:04 2022/10/8 * company: www.dtstack.com */ @Component public class DatasourceOperator { @Autowired private ComponentService componentService; @Autowired private ClusterService clusterService; public ComponentTestResult testConnect(Integer dataSourceType, String pluginInfo) { // 获取对应的数据源类型 JSONObject jsonObject = JSONObject.parseObject(pluginInfo); jsonObject.put(ConfigConstant.DATA_SOURCE_TYPE, dataSourceType); ISourceDTO sourceDTO = PluginInfoToSourceDTO.getSourceDTO(jsonObject.toJSONString()); IClient client = ClientCache.getClient(dataSourceType); ComponentTestResult componentTestResult = new ComponentTestResult(); try { Boolean result = client.testCon(sourceDTO); componentTestResult.setResult(result); } catch (Exception e) { componentTestResult.setResult(Boolean.FALSE); componentTestResult.setErrorMsg(StringUtils.isNotEmpty(e.getMessage()) ? e.getMessage() : ExceptionUtil.getErrorMessage(e)); } return componentTestResult; } /** * 上传 string 到 hdfs 路径 * * @param pluginInfo pluginInfo * @param tenantId 租户 id * @param strContent str 信息 * @param hdfsPath hdfs 路径 * @return 路径 */ public String uploadToHdfs(JSONObject pluginInfo, Long tenantId, String strContent, String hdfsPath) { handleHdfsPluginInfo(pluginInfo, tenantId); ISourceDTO sourceDTO = PluginInfoToSourceDTO.getSourceDTO(pluginInfo.toJSONString()); return ClientCache.getHdfs(sourceDTO.getSourceType()).uploadStringToHdfs(sourceDTO, strContent, hdfsPath); } /** * 上传字节数组到 hdfs 路径 * * @param pluginInfo pluginInfo * @param tenantId 租户 id * @param bytes 字节数组 * @param hdfsPath hdfs 路径 */ public void uploadInputStreamToHdfs(JSONObject pluginInfo, Long tenantId, byte[] bytes, String hdfsPath) { handleHdfsPluginInfo(pluginInfo, tenantId); ISourceDTO sourceDTO = PluginInfoToSourceDTO.getSourceDTO(pluginInfo.toJSONString()); ClientCache.getHdfs(sourceDTO.getSourceType()).uploadInputStreamToHdfs(sourceDTO, bytes, hdfsPath); } /** * 处理 pluginInfo 添加 dataSourceType * * @param pluginInfo pluginInfo * @param tenantId 租户信息 */ public void handleHdfsPluginInfo(JSONObject pluginInfo, Long tenantId) { Long clusterId = clusterService.getClusterIdByTenantId(tenantId); // 获取组件信息 com.dtstack.taier.dao.domain.Component component = componentService.getComponentByClusterId(clusterId, EComponentType.HDFS.getTypeCode(), null); if (Objects.isNull(component)) { throw new TaierDefineException(String.format(ErrorCode.DEPEND_ON_COMPONENT_NOT_CONFIG.getMsg().replaceAll("\\{}", "%s"), EComponentType.HDFS.getName())); } // 获取对应的数据源类型 pluginInfo.put(ConfigConstant.DATA_SOURCE_TYPE, component.getDatasourceType()); } /** * 上传 string 到 hdfs 路径 * * @param pluginInfo pluginInfo * @param tenantId 租户 id * @param hdfsPath hdfs 路径 * @return 路径 */ public List<FileResult> listFiles(JSONObject pluginInfo, Long tenantId, String hdfsPath, boolean isPathPattern) { handleHdfsPluginInfo(pluginInfo, tenantId); ISourceDTO sourceDTO = PluginInfoToSourceDTO.getSourceDTO(pluginInfo.toJSONString()); List<FileStatus> statuses = ClientCache.getHdfs(sourceDTO.getSourceType()).listFiles(sourceDTO, hdfsPath, isPathPattern); List<FileResult> results = Lists.newArrayList(); for (FileStatus status : statuses) { FileResult fileResult = new FileResult(); fileResult.setBlockSize(status.getBlocksize()); fileResult.setName(status.getPath()); fileResult.setPath(status.getPath()); fileResult.setOwner(status.getOwner()); fileResult.setModificationTime(status.getModification_time()); results.add(fileResult); } return results; } }
true
60dde1b624c7378693d8345c9f8176626b651fda
Java
JuliusCesarEstrope/2015-Recycle-Rush
/Double DJ Jammer/src/org/usfirst/frc/team818/robot/autonomi/Auton3.java
UTF-8
507
1.71875
2
[]
no_license
package org.usfirst.frc.team818.robot.autonomi; import edu.wpi.first.wpilibj.command.CommandGroup; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; //import org.usfirst.frc.team818.robot.commands.DriveTimed; //import org.usfirst.frc.team818.robot.commands.TowerDownCommand; import org.usfirst.frc.team818.robot.commands.TowerUpCommand; public class Auton3 extends CommandGroup { public Auton3() { addSequential(new TowerUpCommand(true, SmartDashboard.getNumber("Number 6"))); } }
true
3d335adb85e07dd3ef95197241874e822e690477
Java
specs-feup/lara-framework
/LaraDoc/src/pt/up/fe/specs/lara/doc/aspectir/elements/AspectElement.java
UTF-8
1,255
2.265625
2
[ "Apache-2.0" ]
permissive
package pt.up.fe.specs.lara.doc.aspectir.elements; import com.google.common.base.Preconditions; import pt.up.fe.specs.lara.doc.comments.LaraDocComment; import pt.up.fe.specs.lara.doc.jsdoc.JsDocTagName; import pt.up.fe.specs.lara.doc.jsdoc.JsDocTagProperty; public class AspectElement extends AAspectIrElement { public AspectElement(LaraDocComment laraDocComment) { super(laraDocComment); } public String getAspectName() { // System.out.println("LAST TAG ASPECT:" + getComment().getLastTag(JsDocTagName.ASPECT)); // System.out.println("LAST TAG ASPECT NAME_PATH:" // + getComment().getLastTag(JsDocTagName.ASPECT).getValue(JsDocTagProperty.NAME_PATH)); String aspectName = getComment().getTag(JsDocTagName.ASPECT).getValue(JsDocTagProperty.NAME_PATH); Preconditions.checkNotNull(aspectName, "AspectElements should always have a name"); return aspectName; } @Override public String getName() { return getAspectName(); } // // public List<String> getParameters() { // return getComment().getTags(JsDocTagName.PARAM).stream() // .map(jsdoctag -> jsdoctag.getValue(JsDocTagProperty.NAME)) // .collect(Collectors.toList()); // // } }
true
dcb982411cee082a1c3d5754bf4ae2027bdcc692
Java
houdinisparks/Gestures
/core/src/com/gameworld/GameRenderer.java
UTF-8
4,236
2.21875
2
[]
no_license
package com.gameworld; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.math.Rectangle; import com.gestureDetection.GestureRecognizerInputProcessor; import com.gesturepath.swipe.mesh.SwipeTriStrip; import org.w3c.dom.Text; import java.util.ArrayList; /** * Created by yanyee on 2/22/2016. */ public class GameRenderer { private GameWorld myWorld; private OrthographicCamera camera; private ShapeRenderer shapeRenderer; private String tag = "GameRenderer"; private GestureRecognizerInputProcessor gestureRecognizerInputProcessor; private Texture texture; private SpriteBatch batch; private SwipeTriStrip swipeTriStrip; private Rectangle gameObject; public GameRenderer(GameWorld world , GestureRecognizerInputProcessor gestureRecognizerInputProcessor) { int screenWidth = Gdx.graphics.getWidth(); int screenHeight = Gdx.graphics.getHeight(); this.gestureRecognizerInputProcessor = gestureRecognizerInputProcessor; myWorld = world; camera = new OrthographicCamera(); camera.setToOrtho(false ,screenWidth , screenHeight); swipeTriStrip = new SwipeTriStrip(); this.gestureRecognizerInputProcessor.minDistance = 10; this.gestureRecognizerInputProcessor.minDistance = 10; texture = new Texture(Gdx.files.internal("gesturepath/gradient.png")); texture.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear); batch = new SpriteBatch(); shapeRenderer = new ShapeRenderer(); shapeRenderer.setProjectionMatrix(camera.combined); gameObject = world.getEnemyGang().getRect(); } public void render(float runTime) { Gdx.app.log(tag, "rendering"); /* Draw a black background. */ Gdx.gl.glClearColor(0, 0, 0, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // try { // shapeRenderer.begin(ShapeRenderer.ShapeType.Filled); // shapeRenderer.setColor(255.0f, 255.0f, 255.0f, 1); // // Gdx.app.log(tag, "before rect rendering"); // shapeRenderer.rect(0, 10f, 10f, 10f); // Gdx.app.log(tag, "after rect rendering"); // shapeRenderer.end(); // } catch (Exception e) { // Gdx.app.log(tag, "exception caught"); // // e.printStackTrace(); // } texture.bind(); swipeTriStrip.endcap = 5f; swipeTriStrip.thickness = 30f; swipeTriStrip.update(gestureRecognizerInputProcessor.path()); swipeTriStrip.color = Color.WHITE; swipeTriStrip.draw(camera); // shapeRenderer.begin(ShapeRenderer.ShapeType.Filled); // shapeRenderer.setColor(255.0f, 255.0f, 255.0f, 1); // // Gdx.app.log(tag, "before rect rendering"); // //shapeRenderer.rect(0, 10f, 10f, 10f); // Gdx.app.log(tag, "after rect rendering"); // // // // EnemyGang enemyGang = myWorld.getEnemyGang(); // ArrayList<Rectangle> listOfRectangles= enemyGang.getEnemyArray(); // // try { // // for (Rectangle rectangle :listOfRectangles) { // shapeRenderer.rect(rectangle.x, rectangle.y, rectangle.width, // rectangle.height); // } // // shapeRenderer.end(); // // shapeRenderer.begin(ShapeRenderer.ShapeType.Line); // shapeRenderer.setColor(255 / 255.0f, 109 / 255.0f, 120 / 255.0f, 1); // // for (Rectangle rectangle : listOfRectangles) { // shapeRenderer.rect(rectangle.x, rectangle.y, rectangle.width, // rectangle.height); // } // // // // } catch (NullPointerException e) { // e.printStackTrace(); // } // shapeRenderer.end(); //EnemyGang = gameWorld.getEnemyGang. //Draw enemy gang.getx,gety,get use a for loop to draw the array //of triangles. } }
true
dd3e821604b2ad6544462e4834a4df66bceb9697
Java
ragavanravi65/WhatsTheOutput
/WhatsOutputSeries/src/Main.java
UTF-8
526
3.5
4
[]
no_license
final class Square{ private double length=102,breadth; public Square(double length,double breadth) { this.length=length; this.breadth=breadth; } Square(Square sq){ System.out.println("copy constructor invoked"); length=this.length; breadth=sq.breadth; } public String toString() { return "("+length+"+" + breadth +"i)"; } } public class Main { public static void main(String[] args) { Square s1=new Square(110,115); Square s2=new Square(s1); System.out.println(s2); } }
true
2fc5f3cd05a81c33a7b07f04fcdebfa13e03392a
Java
NMAI-lab/LFO-Simulator
/src/lfo/simulator/shapes/Square.java
UTF-8
2,568
3.03125
3
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package lfo.simulator.shapes; import lfo.simulator.objects.BoundingBox; import util.XMLWriter; import java.awt.geom.Point2D; import org.jdom.Element; /** * * @author santi */ public class Square extends Shape { double dx,dy; public Square(double a_dx, double a_dy) { dx = a_dx; dy = a_dy; } public Square(Element e) { dx = Double.parseDouble(e.getAttributeValue("dx")); dy = Double.parseDouble(e.getAttributeValue("dy")); } public double getDx() { return dx; } public double getDy() { return dy; } public boolean collision(Point2D.Double p, double a, Shape s2, Point2D.Double p2, double a2) throws Exception { if (s2 instanceof Square) { Square ss2 = (Square)s2; if (a!=0 || a2!=0) throw new Exception("Collision between Square and Square with angle different than 0 is not yet implemented!"); if (p.x+dx/2 <= p2.x-ss2.dx/2) return false; if (p2.x+ss2.dx/2 <= p.x-dx/2) return false; if (p.y+dy/2 <= p2.y-ss2.dy/2) return false; if (p2.y+ss2.dy/2 <= p.y-dy/2) return false; return true; } else if (s2 instanceof Circle) { if (a!=0) throw new Exception("Collision between Square and Circle with angle different than 0 is not yet implemented!"); // Find the closest point to the circle within the rectangle double closestX = Math.min(Math.max(p2.x, p.x-dx/2), p.x+dx/2); double closestY = Math.min(Math.max(p2.y, p.y-dy/2), p.y+dy/2); // Calculate the distance between the circle's center and this closest point double distanceX = p2.x - closestX; double distanceY = p2.y - closestY; // If the distance is less than the circle's radius, an intersection occurs double distanceSquared = (distanceX * distanceX) + (distanceY * distanceY); return distanceSquared < (((Circle)s2).getRadius() * ((Circle)s2).getRadius()); } else { throw new Exception("Collision between Square and " + s2.getClass().getName() + " not yet implemented!"); } } public void toxml(XMLWriter w) { w.tagWithAttributes("square","dx = \"" + dx + "\" dy = \"" + dy + "\""); w.tag("/square"); } public BoundingBox getBoundingBox() { Square s = new Square(dx,dy); return new BoundingBox(s,0,0); } }
true
043957faea9a14c53637021848ef39f2a858d25b
Java
tiobe/pmd
/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symboltable/GlobalScopeTest.java
UTF-8
1,482
2.328125
2
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.symboltable; import static org.junit.Assert.assertEquals; import java.util.List; import java.util.Map; import org.junit.Test; import net.sourceforge.pmd.PMD; import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit; import net.sourceforge.pmd.lang.symboltable.NameDeclaration; import net.sourceforge.pmd.lang.symboltable.NameOccurrence; import net.sourceforge.pmd.lang.symboltable.Scope; public class GlobalScopeTest extends BaseNonParserTest { @Test public void testClassDeclAppears() { ASTCompilationUnit acu = parseCode(TEST1); Scope scope = acu.getScope(); Map<NameDeclaration, List<NameOccurrence>> m = scope.getDeclarations(); ClassNameDeclaration classNameDeclaration = (ClassNameDeclaration) m.keySet().iterator().next(); assertEquals(classNameDeclaration.getImage(), "Foo"); } @Test public void testEnums() { java5.parse(TEST2); } private static final String TEST1 = "public class Foo {}" + PMD.EOL; private static final String TEST2 = "public enum Bar {" + PMD.EOL + " FOO1 { " + PMD.EOL + " private static final String FIELD_NAME = \"\";" + PMD.EOL + " }," + PMD.EOL + " FOO2 { " + PMD.EOL + " private static final String FIELD_NAME = \"\";" + PMD.EOL + " }" + PMD.EOL + "}" + PMD.EOL; }
true
c6230779623841df57e788674fc2a2d2867d6547
Java
hehaisheng/WeikeAndroid
/app/src/main/java/com/weike/data/model/viewmodel/MsgDetailItemVM.java
UTF-8
1,510
1.828125
2
[]
no_license
package com.weike.data.model.viewmodel; import android.app.Activity; import android.databinding.ObservableField; import android.support.v4.app.FragmentActivity; import com.weike.data.R; import com.weike.data.base.BaseVM; import com.weike.data.listener.OnReduceListener; /** * Created by LeoLu on 2018/6/1. */ public class MsgDetailItemVM extends BaseVM { public ObservableField<String> content = new ObservableField<>(); public ObservableField<String> title = new ObservableField<>(); public String id; public int remindType; public int handleType; public ObservableField<String> rightText = new ObservableField<>("稍后提醒"); public ObservableField<String> time = new ObservableField<>(); public ObservableField<Boolean> isTextRemind = new ObservableField<>(true); /** * 是否是已读 */ public ObservableField<Boolean> isRead = new ObservableField<>(); /** * 是否选中 */ public ObservableField<Boolean> isSle = new ObservableField<>(); public ObservableField<Boolean> isCheck = new ObservableField<>(); public ObservableField<Boolean> isSystemMsg = new ObservableField<>(false); public OnReduceListener<MsgDetailItemVM> listener; public void setListener(OnReduceListener<MsgDetailItemVM> listener) { this.listener = listener; } public void rightClick(){ listener.onReduce(this); } public MsgDetailItemVM(Activity activity) { super(activity); } }
true
6fdcd641c9cf0ed8751d5284622e57ba2528b1bd
Java
jarrettkenny/dillo-bot
/src/main/java/com/dillos/dillobot/commands/InformationalCommands.java
UTF-8
1,261
2.125
2
[]
no_license
package com.dillos.dillobot.commands; import com.dillos.dillobot.annotations.Channel; import com.dillos.dillobot.annotations.Command; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.entities.MessageChannel; @Component public class InformationalCommands { Logger log = LoggerFactory.getLogger(InformationalCommands.class); @Value("${discord.bot.redirect_uri}") String redirectUri; @Command("/help") public void help(@Channel MessageChannel channel) { log.info("/help"); channel.sendMessage( new EmbedBuilder() .setTitle("DilloBot", redirectUri) .setDescription("by Discord server Dillos the Third. Available commands:") .addField("Informational", "`/help`", false) .addField("GitHub", "`/request`, `/issues`, `/repository`, `/issue`, `/updateIssue`, `/closeIssue`, `/claimIssue`, `/linkGitHub`", false) .addField("Subscriptions", "`/subscribe birthday`, `/unsubscribe birthday`", false) .build() ).queue(); } }
true
9d5f2ded3396d56b250f66fc8ec670bb47e02e63
Java
sieben8nein/SE02_Projekt
/Aservio/src/aservio/presentation/platform/controllers/Login.java
UTF-8
2,410
2.625
3
[]
no_license
package aservio.presentation.platform.controllers; import aservio.presentation.PresentationInterfaceManager; import aservio.presentation.platform.interfaces.contracts.ILogin; import java.io.File; import java.net.URL; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Label; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; public class Login implements Initializable { private final ILogin interFace = PresentationInterfaceManager.getILogin(); @FXML public ImageView logoImageView; @FXML private TextField usernameField; @FXML private PasswordField passwordField; @FXML private Label inputWarningLabel; @Override public void initialize(URL url, ResourceBundle rb) { File file = new File("resources/logo/LogoLarge.png"); Image logo = new Image(file.toURI().toString()); logoImageView.setImage(logo); } /** * Clicking the login button or hitting enter logs the user in, if the input * is acceptable. checkForNoIllegalInput returns a string "inputOK" if * validated, else returns a string containing an error message displaying * it to the user. * * @param event */ @FXML private void validateLogin(ActionEvent event) { String username = usernameField.getText(); String password = passwordField.getText(); String result = interFace.checkForNoIllegalInput(username, password); if (result.equals("inputOK")) { String verifyResult = interFace.verifyUser(username, password); if (verifyResult.equals("true")) { interFace.setUser(username, password); interFace.loadScene(); } else { inputWarningLabel.setText(verifyResult); } } else { inputWarningLabel.setText(result); } } /** * Userinput 'enter' on login button equals to pressing it. * @param event */ @FXML private void onLoginBtnEnter(KeyEvent event) { if (event.getCode().equals(KeyCode.ENTER)) { validateLogin(new ActionEvent()); } } }
true
113b1c6f0bbfc2d370a1489d1e5eb479e5df8151
Java
NElight/javaee_eclipse
/ssh/src/main/java/ssh/test/anno/NameAction.java
UTF-8
1,267
2.015625
2
[]
no_license
package ssh.test.anno; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import javax.annotation.*; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.ServletActionContext; import org.springframework.stereotype.Controller; import ssh.model.User; import ognl.*; @Controller("nameController") public class NameAction { @SuppressWarnings("restriction") @Resource private NameService nameService; private ArrayList<String> list; private ArrayList<Map<String, String>> listmap; public ArrayList<Map<String, String>> getListmap() { return listmap; } public void setListmap(ArrayList<Map<String, String>> listmap) { this.listmap = listmap; } public String execute() { setList(nameService.getNames()); listmap = new ArrayList<Map<String,String>>(); HashMap<String, String > a1 = new HashMap<String, String>(); a1.put("xh", "1223"); a1.put("xm", "zhangsan"); listmap.add(a1); HashMap<String, String> a2 = new HashMap<String, String>(); a2.put("xh", "1213"); a2.put("xm", "lisi"); listmap.add(a2); return "index"; } public ArrayList<String> getList() { return list; } public void setList(ArrayList<String> list) { this.list = list; } }
true
082f4f17b1eb1357f3e568a612b7f884e73f327f
Java
flyfire/Forward
/javalib/src/main/java/com/oman/lib/proxy/Test.java
UTF-8
1,759
2.734375
3
[]
no_license
package com.oman.lib.proxy; import java.io.FileOutputStream; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import sun.misc.ProxyGenerator; /** * @author:ZhouJiang * @date:2020/5/17 22:29 * @email:zhoujiang2012@163.com */ public class Test { public static void main(String[] args) throws Exception { // static agent Service s = new Agent(); s.service(5); System.out.println("----------------"); // dynamic agent Service s2 = new BeautyService(); Object o = Proxy.newProxyInstance(Test.class.getClassLoader(), new Class[]{Service.class}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { method.invoke(s2, args); return null; } }); Service service = (Service) o; service.service(6); proxy(); proxy1(); } private static void proxy() throws Exception { String name = Service.class.getName() + "$proxy"; byte[] bytes = ProxyGenerator.generateProxyClass(name, new Class[]{Service.class}); FileOutputStream fos = new FileOutputStream("javalib/" + name + ".class"); fos.write(bytes); fos.close(); } private static void proxy1() throws Exception { String name = OnClickListener.class.getName() + "$proxy1"; byte[] bytes = ProxyGenerator.generateProxyClass(name, new Class[]{OnClickListener.class}); FileOutputStream fos = new FileOutputStream("javalib/" + name + ".class"); fos.write(bytes); fos.close(); } } interface OnClickListener { void onClick(String v); }
true
7629a9135647ad2bf5afc37134d9bd03eff0d19b
Java
KoenHopmans/music-hexagon
/src/main/java/com/novi/hexagon/service/FileStorageService.java
UTF-8
3,858
2.46875
2
[]
no_license
package com.novi.hexagon.service; import com.novi.hexagon.exceptions.FileStorageException; import com.novi.hexagon.exceptions.MyFileNotFoundException; import com.novi.hexagon.exceptions.RecordNotFoundException; import com.novi.hexagon.model.User; import com.novi.hexagon.property.FileStorageProperties; import com.novi.hexagon.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.Resource; import org.springframework.core.io.UrlResource; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; @Service public class FileStorageService { private final Path fileStorageLocation; @Autowired private UserRepository userRepository; @Autowired public FileStorageService(FileStorageProperties fileStorageProperties) { this.fileStorageLocation = Paths.get(fileStorageProperties.getUploadDir()) .toAbsolutePath().normalize(); try { Files.createDirectories(this.fileStorageLocation); } catch (Exception ex) { throw new FileStorageException("Could not create the directory where the uploaded files will be stored.", ex); } } public void uploadFile(MultipartFile file) { try { Path copyLocation = Paths .get(fileStorageLocation + File.separator + StringUtils.cleanPath(file.getOriginalFilename())); Files.copy(file.getInputStream(), copyLocation, StandardCopyOption.REPLACE_EXISTING); } catch (Exception e) { e.printStackTrace(); throw new FileStorageException("Could not store file " + file.getOriginalFilename() + ". Please try again!"); } } public void updateFile(MultipartFile file,String username) { System.out.println(username); if (!userRepository.existsById(username)) throw new RecordNotFoundException(); User user = userRepository.findById(username).get(); if(!(user.getPhoto() == null)){ try { deleteFile(user.getPhoto()); System.out.println("PHOTO test"); System.out.println(); } catch (IOException e) { e.printStackTrace(); } } try { Path copyLocation = Paths .get(fileStorageLocation + File.separator + StringUtils.cleanPath(file.getOriginalFilename())); Files.copy(file.getInputStream(), copyLocation, StandardCopyOption.REPLACE_EXISTING); } catch (Exception e) { e.printStackTrace(); throw new FileStorageException("Could not store file " + file.getOriginalFilename() + ". Please try again!"); } } public void deleteFile(String filename) throws IOException { Path deleteLocation = Paths .get(fileStorageLocation + File.separator + StringUtils.cleanPath(filename)); Files.delete(deleteLocation); } public Resource loadFileAsResource(String fileName) { try { Path filePath = this.fileStorageLocation.resolve(fileName).normalize(); Resource resource = new UrlResource(filePath.toUri()); if (resource.exists()) { return resource; } else { throw new MyFileNotFoundException("File not found " + fileName); } } catch (MalformedURLException ex) { throw new MyFileNotFoundException("File not found " + fileName, ex); } } }
true
75e8dd6335e5703ee7ff438f22437cf5452b45fc
Java
superdGeorge/privateLedge-server
/src/main/java/com/projectx/BaseServlet.java
UTF-8
1,771
2.390625
2
[]
no_license
package com.projectx; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.firebase.auth.FirebaseToken; import datamodel.RequestParams; import util.AuthHelper; import util.JsonHelper; import util.Pair; @SuppressWarnings("serial") public class BaseServlet extends HttpServlet { private static final int BAD_REQUEST = 400; private List<String> errorMsg = new ArrayList<>(); private Map<String, Object> map = new HashMap<>(); public List<String> getErrorMessageList(){ return errorMsg; } public void addErrorMessage(String error) { errorMsg.add(error); } public Map<String, Object> getMap(){ return map; } public void addResponse(String key, Object val) { map.put(key, val); } public <T extends RequestParams> Pair<FirebaseToken, T> prepare(HttpServletRequest request, Class<T> clazz) throws IOException{ T requestParams = JsonHelper.fromJson(request.getReader(), clazz); if(requestParams == null) { return null; } FirebaseToken decodedToken = null; if(requestParams.needAuth) { decodedToken = AuthHelper.verifyToken(requestParams.authToken, errorMsg); } return new Pair<FirebaseToken, T>(decodedToken, requestParams); } public void prepareResponse(HttpServletResponse response) throws IOException { response.setContentType("application/json"); PrintWriter out = response.getWriter(); if(!errorMsg.isEmpty()) { response.setStatus(BAD_REQUEST); map.put("error", errorMsg); } out.print(JsonHelper.toJson(map)); out.flush(); } }
true
f2a60c15e97248823fe8008b8b7e3e8ea8ebca2c
Java
dewiayuparaswatti97/TIGOL.com
/app/src/main/java/com/example/tigol/Card.java
UTF-8
893
2.5625
3
[ "MIT" ]
permissive
package com.example.tigol; public class Card { String imagePath,nama,harga,deskripsi; public Card(String imagePath, String nama, String harga, String deskripsi) { this.imagePath = imagePath; this.nama = nama; this.harga = harga; this.deskripsi = deskripsi; } public String getImagePath() { return imagePath; } public void setImagePath(String imagePath) { this.imagePath = imagePath; } public String getNama() { return nama; } public void setNama(String nama) { this.nama = nama; } public String getHarga() { return harga; } public void setHarga(String harga) { this.harga = harga; } public String getDeskripsi() { return deskripsi; } public void setDeskripsi(String deskripsi) { this.deskripsi = deskripsi; } }
true
045e79cb77c2ebde046cbe6c47bdcc0016cf76ab
Java
OriginLU/common-module
/tenancy/tenancy-client/src/main/java/com/zeroone/tenancy/aop/TenancyDataSourceAspect.java
UTF-8
5,217
2.265625
2
[]
no_license
package com.zeroone.tenancy.aop; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.zeroone.tenancy.annotation.TenancyDataSource; import com.zeroone.tenancy.provider.TenantDataSourceProvider; import com.zeroone.tenancy.utils.TenantIdentifierHelper; import com.zeroone.tenancy.thread.pool.ThreadPoolProxyFactory; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.aspectj.lang.reflect.MethodSignature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.CollectionUtils; import org.springframework.util.ReflectionUtils; import java.lang.reflect.Method; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * 商户数据源切面处理 */ @Aspect public class TenancyDataSourceAspect{ private final Logger log = LoggerFactory.getLogger(TenancyDataSourceAspect.class); public static ExecutorService pool = ThreadPoolProxyFactory.createThreadPoolExecutor( 5, 200, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1024), new ThreadFactoryBuilder().setNameFormat("task-pool-%d").build(), new ThreadPoolExecutor.AbortPolicy()); private final TenantDataSourceProvider tenantDataSourceProvider; public TenancyDataSourceAspect(TenantDataSourceProvider tenantDataSourceProvider) { this.tenantDataSourceProvider = tenantDataSourceProvider; } @Pointcut("@annotation(com.zeroone.tenancy.annotation.TenancyDataSource)") private void pointcut() { } /** * 切面执行前 */ @Before("pointcut()") public void before(JoinPoint joinPoint) { log.debug("the tenant is {} invoking method {} before. ", TenantIdentifierHelper.getTenant(), ((MethodSignature) joinPoint.getSignature()).getMethod().getName()); } /** * 多租户执行 */ @Around("pointcut()") public Object around(ProceedingJoinPoint joinPoint) { MethodSignature sign = (MethodSignature) joinPoint.getSignature(); Method method = sign.getMethod(); TenancyDataSource annotation = method.getAnnotation(TenancyDataSource.class); Set<String> tenantCodes = new HashSet<>(Arrays.asList(annotation.value())); if (CollectionUtils.isEmpty(tenantCodes)) { tenantCodes = tenantDataSourceProvider.getDataSourceMap().keySet(); } Object result = null; if (annotation.async()) { log.info("async execute method:{} cannot get result", method); if (null != TenantIdentifierHelper.getTenant()) { result = executeMethod(joinPoint, method, TenantIdentifierHelper.getTenant()); } else { for (String tenantCode : tenantCodes) { executeMethodAsync(joinPoint,method, tenantCode); } } } else { for (String tenantCode : tenantCodes) { result = executeMethod(joinPoint, method, tenantCode); } } if (tenantCodes.size() > 1) { log.info("result is the last executed,method:{}, tenant codes:{}", method, tenantCodes); } return result; } /** * 异步执行方法 */ private void executeMethodAsync(ProceedingJoinPoint joinPoint,Method method, String tenantCode) { try { TenantIdentifierHelper.setTenant(tenantCode); pool.execute(() -> ReflectionUtils.invokeMethod(method, joinPoint.getTarget())); } catch (Exception e) { log.error("invoking method :{},tenant code:{} throwable:{}", method.getName(),tenantCode, e); } finally { log.debug("the tenant is {} invoking method finally. ", TenantIdentifierHelper.getTenant()); TenantIdentifierHelper.remove(); } } /** * 同步执行 */ private Object executeMethod(ProceedingJoinPoint joinPoint, Method method, String tenantCode) { Object result = null; try { TenantIdentifierHelper.setTenant(tenantCode); result = joinPoint.proceed(); } catch (Throwable e) { // 防止某个数据源操作异常导致其他数据源无法操作 log.error("invoking method :{},tenant code:{} throwable:{}", method.getName(),tenantCode, e); } finally { log.debug("the tenant is {} invoking method finally. ", TenantIdentifierHelper.getTenant()); TenantIdentifierHelper.remove(); } return result; } /** * 切面执行后 */ @After("pointcut()") public void after(JoinPoint joinPoint) { log.debug("invoking method {} after.", ((MethodSignature) joinPoint.getSignature()).getMethod().getName()); if (null != TenantIdentifierHelper.getTenant()) { TenantIdentifierHelper.remove(); } } }
true
bb0c3704f28d182181fb80765e5e9642529f04e0
Java
manwindersingh1712/DataStructures
/src/Assignment3/Q6_NumberOfDigitsInNUmber.java
UTF-8
585
3.375
3
[]
no_license
package Assignment3; import java.util.Scanner; public class Q6_NumberOfDigitsInNUmber { public static void main(String[] args) { Scanner scrn = new Scanner(System.in); int num = scrn.nextInt(); int digit = scrn.nextInt(); System.out.println(numberOfDigits(num, digit)); } private static int numberOfDigits(int num, int digit) { int c = 0; while (num != 0) { int a = num % 10; if (a == digit) { c++; } num = num / 10; } return c; } }
true
6ab82957e0ad9e55708e571ea87219a2fb1feb85
Java
Skn0tt/lkDatenstrukturen
/Queue/src/Main.java
UTF-8
400
2.890625
3
[]
no_license
import java.io.Serializable; /** * Created by simon.knott on 17.11.2017. */ public class Main { public static void main(String... args) { Queue<Integer> stack = new Queue<>(); for (int i = 0; i < 20; i++) { stack.enqueue(i); } while(!stack.isEmpty()) { System.out.println(stack.front()); stack.dequeue(); } } }
true
8e97bb4f68dc1652b45011f24fd3ccdf1176d65b
Java
yeluo1942/ShowUserInfo
/src/web/DeleteSelected.java
GB18030
1,272
2.484375
2
[]
no_license
package web; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import service.Service; import service.ServiceImpl; /** * ɾѡ * @author yeluo1942 * */ @WebServlet("/DeleteSelected") public class DeleteSelected extends HttpServlet{ /** * */ private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); //ȡuid String[] uids = req.getParameterValues("uid"); if(uids != null && uids.length > 0) { Service service = new ServiceImpl(); service.delSelected(uids); }else { //ʾϢ req.setAttribute("error", "ѡһ¼ɾ"); } //ɾɣתUserServlet req.getRequestDispatcher("/UserServlet").forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } }
true
bc0f8d1bfe049dd4502ef410f8c9832fa08581f9
Java
yokesh-sparkout/zipchat-clone-new
/zipchat-clone/src/main/java/com/chat/zipchat/clone/Activity/ProfileActivity.java
UTF-8
9,362
1.679688
2
[ "MIT" ]
permissive
package com.chat.zipchat.clone.Activity; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.bumptech.glide.Glide; import com.chat.zipchat.clone.Common.BaseClass; import com.chat.zipchat.clone.Model.ProfileImageUpdate.ProfileImageResponse; import com.chat.zipchat.clone.Model.ProfileUpdate.ProfileUpdateRequest; import com.chat.zipchat.clone.Model.ProfileUpdate.ProfileUpdateResponse; import com.chat.zipchat.clone.R; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.theartofdev.edmodo.cropper.CropImage; import com.theartofdev.edmodo.cropper.CropImageView; import java.io.File; import java.util.HashMap; import de.hdodenhof.circleimageview.CircleImageView; import okhttp3.MultipartBody; import okhttp3.RequestBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import static com.chat.zipchat.clone.Common.BaseClass.ConvertedDateTime; import static com.chat.zipchat.clone.Common.BaseClass.MY_REQUEST_CODE_IMAGE; import static com.chat.zipchat.clone.Common.BaseClass.apiInterface; import static com.chat.zipchat.clone.Common.BaseClass.getRealPathFromURI; import static com.chat.zipchat.clone.Common.BaseClass.isOnline; import static com.chat.zipchat.clone.Common.BaseClass.myLog; import static com.chat.zipchat.clone.Common.BaseClass.removeProgressDialog; import static com.chat.zipchat.clone.Common.BaseClass.requestOptionsD; import static com.chat.zipchat.clone.Common.BaseClass.sessionManager; import static com.chat.zipchat.clone.Common.BaseClass.showSimpleProgressDialog; import static com.chat.zipchat.clone.Common.BaseClass.snackbar; import static okhttp3.MediaType.parse; public class ProfileActivity extends AppCompatActivity implements View.OnClickListener { CircleImageView mImgProfile, mBtnCamera; EditText mEtName; Button mBtnContinue; String id, profile_picture; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); mImgProfile = findViewById(R.id.mImgProfile); mBtnCamera = findViewById(R.id.mBtnCamera); mEtName = findViewById(R.id.mEtName); mBtnContinue = findViewById(R.id.mBtnContinue); mBtnCamera.setOnClickListener(this); mBtnContinue.setOnClickListener(this); id = getIntent().getStringExtra("id"); } @Override public void onClick(View v) { int i = v.getId(); if (i == R.id.mBtnContinue) { if (TextUtils.isEmpty(mEtName.getText().toString())) { mEtName.setError("Enter your Name"); mEtName.requestFocus(); } else { UpdateProfileService(); } } else if (i == R.id.mBtnCamera) { imagePicker(); } } private void imagePicker() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_REQUEST_CODE_IMAGE); } else { getImageFromGallery(); } } else { getImageFromGallery(); } } private void getImageFromGallery() { CropImage.activity() .setGuidelines(CropImageView.Guidelines.ON) .start(this); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) { CropImage.ActivityResult result = CropImage.getActivityResult(data); if (resultCode == RESULT_OK) { Uri resultUri = result.getUri(); Glide.with(this).setDefaultRequestOptions(requestOptionsD()).load(resultUri).into(mImgProfile); String filePath = getRealPathFromURI(this, resultUri); UpdateProfileImageService(filePath); } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) { Exception error = result.getError(); } } } private void UpdateProfileImageService(String filePath) { if (isOnline(this)) { showSimpleProgressDialog(this); //pass it like this File file = new File(filePath); // Parsing any Media type file RequestBody requestBody = RequestBody.create(parse("*/*"), file); MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("media", file.getName(), requestBody); final Call<ProfileImageResponse> registerResponseCall = apiInterface.updateProfileImage(fileToUpload); registerResponseCall.enqueue(new Callback<ProfileImageResponse>() { @Override public void onResponse(Call<ProfileImageResponse> call, Response<ProfileImageResponse> response) { removeProgressDialog(); if (response.isSuccessful()) { profile_picture = response.body().getResult().getUrl(); } else if (response.code() == 104) { } } @Override public void onFailure(Call<ProfileImageResponse> call, Throwable t) { removeProgressDialog(); myLog("OnFailure", t.toString()); } }); } else { snackbar(this, mBtnContinue, BaseClass.NO_INTERNET); } } private void UpdateProfileService() { if (isOnline(this)) { showSimpleProgressDialog(this); ProfileUpdateRequest profileUpdateRequest = new ProfileUpdateRequest(); profileUpdateRequest.setFull_name(mEtName.getText().toString()); profileUpdateRequest.setProfile_picture(profile_picture); profileUpdateRequest.setStatus("Available"); final Call<ProfileUpdateResponse> registerResponseCall = apiInterface.updateProfile(id, profileUpdateRequest); registerResponseCall.enqueue(new Callback<ProfileUpdateResponse>() { @Override public void onResponse(Call<ProfileUpdateResponse> call, Response<ProfileUpdateResponse> response) { removeProgressDialog(); if (response.isSuccessful()) { sessionManager(ProfileActivity.this).createLoginSession( response.body().getResult().getId(), response.body().getResult().getFullName(), response.body().getResult().getProfilePicture(), response.body().getResult().getAuthorization(), response.body().getResult().getMobileNumber(), response.body().getResult().getCountry_code(), response.body().getResult().getStatus(), response.body().getResult().getStellarAddress(), response.body().getResult().getStellarSeed()); HashMap<String, String> map = new HashMap<>(); map.put("name", response.body().getResult().getFullName()); map.put("mobile-number", response.body().getResult().getMobileNumber()); map.put("profile-url", response.body().getResult().getProfilePicture()); map.put("isOnline", "1"); map.put("offline-time", ConvertedDateTime()); map.put("status", "Available"); DatabaseReference referenceUserInsert = FirebaseDatabase.getInstance().getReference("user-details").child(response.body().getResult().getId()).child("profile-details"); referenceUserInsert.setValue(map); Intent intent = new Intent(ProfileActivity.this, MainActivity.class); startActivity(intent); finish(); } else if (response.code() == 104) { } } @Override public void onFailure(Call<ProfileUpdateResponse> call, Throwable t) { removeProgressDialog(); myLog("OnFailure", t.toString()); } }); } else { snackbar(this, mBtnContinue, BaseClass.NO_INTERNET); } } @Override public void onRequestPermissionsResult(int RC, String per[], int[] PResult) { switch (RC) { case MY_REQUEST_CODE_IMAGE: getImageFromGallery(); break; } } }
true
ae9c4103fc44d57e3580b65b22a3382fa0d16e1f
Java
vivekmaheshsahu/K-th-_-pp
/app/src/main/java/com/vivek/hack/katha_app/Share_App.java
UTF-8
475
1.976563
2
[]
no_license
package com.vivek.hack.katha_app; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; public class Share_App extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(com.vivek.hack.katha_app.R.layout.activity_share__app); Toast.makeText(this, "Welcome to Share App", Toast.LENGTH_SHORT).show(); } }
true
9b82e447a406cf4bd0eba43f389b3be5d54015f0
Java
rencsaridogan/processout-android
/processout-sdk/src/main/java/com/processout/processout_sdk/MiscGatewayRequest.java
UTF-8
1,114
2.15625
2
[]
no_license
package com.processout.processout_sdk; import android.util.Base64; import com.google.gson.Gson; import com.google.gson.annotations.SerializedName; import java.util.Map; public class MiscGatewayRequest { @SerializedName("url") private String URL; @SerializedName("method") private String method; @SerializedName("headers") private Map<String, String> headers; @SerializedName("body") private String body; public MiscGatewayRequest(String body) { this.body = body; } public String generateToken() { return "gway_req_" + Base64.encodeToString(new Gson().toJson(this, MiscGatewayRequest.class).getBytes(), Base64.NO_WRAP); } public String getURL() { return URL; } public void setURL(String URL) { this.URL = URL; } public String getMethod() { return method; } public Map<String, String> getHeaders() { return headers; } public void setHeaders(Map<String, String> headers) { this.headers = headers; } public String getBody() { return body; } }
true
5de6a7803bfadba804d410b410bcdab77c3be683
Java
iisa-gallego/CalculadorNotas-ECO
/app/src/main/java/com/example/s3notas/ResultadoActivity.java
UTF-8
2,320
2.0625
2
[]
no_license
package com.example.s3notas; import androidx.appcompat.app.AppCompatActivity; import androidx.constraintlayout.widget.ConstraintLayout; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextClock; import android.widget.TextView; import java.text.DecimalFormat; public class ResultadoActivity extends AppCompatActivity implements View.OnClickListener { private TextView muestraNombre; private TextView muestraResultado; private Button calcularOtraVez; private ConstraintLayout fondomu ; private String col; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_resultado); String nombre = getIntent().getExtras().getString("nombre"); muestraNombre = findViewById(R.id.muestraNombre); muestraResultado= findViewById(R.id.muestraResultado); calcularOtraVez = findViewById(R.id.calculaOtraVez); fondomu = findViewById(R.id.fondomu); SharedPreferences preferencias = getSharedPreferences("buzonColor",MODE_PRIVATE); col = preferencias.getString("coloreado","nocoloreado"); if (col.equals("Predeterminado")) { fondomu.setBackgroundColor(Color.rgb(192, 201, 255)); } if (col.equals("Claro")) { fondomu.setBackgroundColor(Color.rgb(255, 255, 255)); } if(col.equals("Oscuro")) { fondomu.setBackgroundColor(Color.rgb(110,112,124)); } double noticas = getIntent().getExtras().getDouble("notas"); DecimalFormat decimales = new DecimalFormat("#.00"); muestraResultado.setText("" + decimales.format( noticas)); Log.d("pasaste",""+ noticas); muestraNombre.setText(nombre); calcularOtraVez.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.calculaOtraVez: Intent u = new Intent(this,MainActivity.class); startActivity(u); break; } } }
true
b3a4a74d84e4db726024add9b7a7a059d1dcf90f
Java
a5502015/MyJavaClass
/0821/CountDownLatchDemo.java
BIG5
1,887
3.5
4
[]
no_license
import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; class Student implements Runnable{ private CountDownLatch downLatch; private String name; public Student(CountDownLatch downLatch, String name){ this.downLatch = downLatch; this.name = name; } public void run() { this.doWork(); try{ TimeUnit.SECONDS.sleep(new Random().nextInt(10)); }catch(InterruptedException ie){ } System.out.println(this.name + "\ҰF!"); this.downLatch.countDown(); } private void doWork(){ System.out.println(this.name + "bVOg\Ҥ....!"); } } class Teacher implements Runnable { private CountDownLatch downLatch; public Teacher(CountDownLatch downLatch){ this.downLatch = downLatch; } public void run() { System.out.println("ѮvbҦǥͧ\ҧ@......"); try { this.downLatch.await(); } catch (InterruptedException e) { } System.out.println("ѮvҦ@~F"); } } class CountDownLatchDemo { public static void main(String[] args) { ExecutorService executor = Executors.newCachedThreadPool(); CountDownLatch latch = new CountDownLatch(3); Student w1 = new Student(latch,"iT"); Student w2 = new Student(latch,"|"); Student w3 = new Student(latch,"G"); Teacher boss = new Teacher(latch); executor.execute(w3); executor.execute(w2); executor.execute(w1); executor.execute(boss); executor.shutdown(); } }
true
4c910ba0ea0edeb057b6bebef4b0f31040b54f07
Java
pabloAMD/CitasMedicas
/CitasMedicasOnline/src/modelo/Suscripcion.java
UTF-8
1,761
2.296875
2
[]
no_license
package modelo; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.OneToOne; @Entity public class Suscripcion implements Serializable{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private double saldo; @OneToOne @JoinColumn private Paciente pacient; @OneToMany(cascade = CascadeType.ALL, mappedBy = "suscripcion") private List<LibroDiario> libroDiarioList; public Suscripcion() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public double getSaldo() { return saldo; } public void setSaldo(double saldo) { this.saldo = saldo; } public Paciente getPacient() { return pacient; } public void setPacient(Paciente pacient) { this.pacient = pacient; } public List<LibroDiario> getLibroDiarioList() { return libroDiarioList; } public void setLibroDiarioList(List<LibroDiario> libroDiarioList) { this.libroDiarioList = libroDiarioList; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + id; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Suscripcion other = (Suscripcion) obj; if (id != other.id) return false; return true; } }
true
f21fd4909cee04dd4f9d0c88ac00db6fe78c4388
Java
SyAuler/Training-Camp
/Java/Intro POO/ACCH - Pet - Simone Auler/src/cadastros/CadAnimal.java
UTF-8
4,940
3.140625
3
[]
no_license
package cadastros; import dados.Animal; import dados.Proprietario; import dados.Raca; import java.util.ArrayList; import java.util.Date; import javax.swing.JOptionPane; import tela.Janela; public class CadAnimal implements Cadastro { static ArrayList<Animal> animal = new ArrayList<Animal>(); private CadRaca cadRaca; private CadProprietario cadProprietario; public CadAnimal(CadRaca cadRaca, CadProprietario cadProprietario) { this.cadRaca = cadRaca; this.cadProprietario = cadProprietario; } public static void dadosPadrao() { Animal[] animal = new Animal[5]; animal[0] = new Animal("Batata", "cao", "macho", "23/11/2015"); animal[1] = new Animal("Thor", "reptil", "macho", "09/08/2013"); animal[2] = new Animal("Amora", "cao", "femea", "15/01/2014"); animal[3] = new Animal("Batutinha", "passaro", "macho", "06/03/2015"); Animal sel = (Animal) JOptionPane.showInputDialog(null, "Selecione a raça", "Animal", JOptionPane.INFORMATION_MESSAGE, null, animal, animal[0]); if (sel == null) { JOptionPane.showMessageDialog(null, "Nenhuma"); } else { JOptionPane.showMessageDialog(null, sel.getCaracteristica()); } } @Override public boolean adicionar() { String cpf = Janela.lerString("Informe o CPF do Proprietário", true); Proprietario proprietario = cadProprietario.buscarProprietarioPorCPF(cpf); if (proprietario == null) { Janela.erro("O proprietário não foi localizado pelo CPF " + cpf); } else if (!cpf.matches("[0-9]{3}\\.?[0-9]{3}\\.?[0-9]{3}\\-?[0-9]{2}")) { Janela.erro("Informe um cpf válido" + cpf); } else { proprietario.setCpf(cpf); if (animal.contains(cpf)) { Janela.erro("CPF já cadastrado" + cpf); } else { String descricao = Janela.lerString("Informe a raca do animal", true); Raca raca = cadRaca.buscarRaca(descricao); if (raca == null) { Janela.erro("A raça não foi localizada"); } else { Animal objeto = new Animal(proprietario); String nome = Janela.lerString("Informe o nome do animal ", true).toUpperCase(); if (nome == null) { Janela.erro("Informe um nome válido"); } else { String caract = Janela.lerString("Informe as características do animal", true); if (caract == null) { Janela.erro("Informe características válidas"); } else { Date dataNasc = Janela.lerData("Informe a data de nascimento do animal. Ex: 01/01/2000", true); if (dataNasc == null) { Janela.erro("Informe uma data de nascimento válida"); } else { String sexo = Janela.lerString("Informe o sexo do animal", true); if (sexo == null) { Janela.erro("Informe um sexo válido"); } else { objeto.setNome(nome); animal.add(objeto); } } } } } } } return false; } @Override public boolean remover() { return false; } @Override public void listar() { String msg = ""; for (int i = 0; i < animal.size(); i++) { msg = msg + "Nome: " + animal.get(i).getNome() + " Característica: " + animal.get(i).getCaracteristica() + " Nascimento: " + animal.get(i).getNasc() + " Sexo: " + animal.get(i).getSexo() + " Raça: " + animal.get(i).getRaca().getDescricao() + " Tipo de Animal: " + animal.get(i).getRaca().getTipoAnimal().getDescricao() + " Proprietário " + animal.get(i).getProprietario().getNome() + " Telefone " + animal.get(i).getProprietario().getTelefone() + "\n"; } Janela.mensagem(msg); } @Override public void lerArquivo(ArrayList objeto) { animal = objeto; } @Override public ArrayList gravarArquivo() { return animal; } public static Animal buscarAnimalPorNome(String nome) { for (int index = 0; index < animal.size(); index++) { if (animal.get(index).getNome().equalsIgnoreCase(nome)) { return animal.get(index); } } return null; } }
true
7e9e35d10030c7bf702eea7b6ab025c453656570
Java
kontza/javatmospi
/src/main/java/org/kontza/atmospi/Settings.java
UTF-8
1,739
2.484375
2
[ "MIT" ]
permissive
/* * 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 org.kontza.atmospi; import com.fasterxml.jackson.annotation.JsonProperty; /** * * @author juharuotsalainen */ public class Settings { // How far into the past should data be loaded (in seconds)? Default to 1 week. @JsonProperty("range_seconds") private int rangeSeconds; // The number of digits after the decimal place that will be stored. private int precision; // Temperature unit of measure (C or F). @JsonProperty("t_unit") private String temperatureUnit; public Settings(int rangeSeconds, int precision, String temperatureUnit) { this.rangeSeconds = rangeSeconds; this.precision = precision; this.temperatureUnit = temperatureUnit; } public Settings() { rangeSeconds = 7 * 24 * 3600; precision = 2; temperatureUnit = AtmospiSettings.TEMP_C; } public int getRangeSeconds() { return rangeSeconds; } public void setRangeSeconds(int rangeSeconds) { this.rangeSeconds = rangeSeconds; } public int getPrecision() { return precision; } public void setPrecision(int precision) { this.precision = precision; } public String getTemperatureUnit() { return temperatureUnit; } public void setTemperatureUnit(String temperatureUnit) { if (temperatureUnit.toUpperCase() == AtmospiSettings.TEMP_C) { this.temperatureUnit = AtmospiSettings.TEMP_C; } else { this.temperatureUnit = AtmospiSettings.TEMP_F; } } }
true
7b42521ad4a785e1bfc86d34f615a8c7d17bd97e
Java
sumanshil/TopCoder
/TopCoder/src/main/java/com/leetcode/MeetingRoom.java
UTF-8
1,896
3.3125
3
[]
no_license
package com.leetcode; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; import java.util.List; //https://leetcode.com/problems/meeting-rooms/ public class MeetingRoom { class Pair { int low; int high; Pair(int low, int high) { this.low = low; this.high = high; } } public boolean canAttendMeetings(int[][] intervals) { Comparator<int[]> mycomparator = (a, b) -> { if (a[0] < b[0]) { return -1; } else { return 1; } }; Arrays.sort(intervals, mycomparator); for (int i = 0 ; i < intervals.length-1 ; i++) { if (intervals[i][1] > intervals[i+1][0]) { return false; } } return true; } /** public boolean canAttendMeetings(int[][] intervals) { int low = intervals[0][0]; int high = intervals[0][1]; List<Pair> list = new LinkedList<>(); list.add(new Pair(low, high)); for (int i = 1 ; i < intervals.length ; i++) { int low1 = intervals[i][0]; int high1 = intervals[i][1]; for (Pair pair : list) { if ((high1 <= pair.low) || (low1 >= pair.high)) { continue; } else { return false; } } list.add(new Pair(low1, high1)); } return true; } **/ public static void main(String[] args) { int[][] matrix = { {16, 22}, {28, 45}, {3, 9}, {46, 50}, {13, 14} }; boolean result = new MeetingRoom().canAttendMeetings(matrix); System.out.println(result); } }
true
0330cd19c6e847a9459b2ddc832324e25f5032a8
Java
austonricardo/simulaAlocacao2
/src/Alocacao.java
ISO-8859-1
6,494
3.046875
3
[]
no_license
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Alocacao { public static List<Candidato> candidatos; public static List<Local> ofertas; //Todos os locais at com 0 vagas /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub popular(); imprimirSituacao(candidatos); System.out.println("----------------Result 1----------------------------"); List<Candidato> result =alocar(); imprimirSituacao(result); System.out.println("----------------Result 2----------------------------"); List<Candidato> result2 = alocar2(); imprimirSituacao(result2); System.out.println("----------------Result 3----------------------------"); List<Candidato> result3 = alocarRecursivo(); imprimirSituacao(result3); } public static void popular(){ candidatos = new ArrayList<Candidato>(); candidatos.add(new Candidato(1, 1, 3, 1,2)); candidatos.add(new Candidato(2, 2, 2, 3,1)); candidatos.add(new Candidato(3, 3, 1, 2,3)); candidatos.add(new Candidato(4, 4, 1, 3)); candidatos.add(new Candidato(5, 5, 4, 1,2)); candidatos.add(new Candidato(6, 6, 4, 1,2,3)); candidatos.add(new Candidato(7, 7, 1, 2,3)); candidatos.add(new Candidato(8, 8, 1, 3)); candidatos.add(new Candidato(9, 9, 4, 1,2)); candidatos.add(new Candidato(10, 10, 4, 1,2,3)); candidatos.add(new Candidato(11, 11, 3, 1,2)); candidatos.add(new Candidato(12, 12, 2, 3,1)); candidatos.add(new Candidato(13, 13, 1, 2,3)); candidatos.add(new Candidato(14, 14, 1, 3)); candidatos.add(new Candidato(15, 15, 4, 1,2)); candidatos.add(new Candidato(16, 16, 4, 1,2,3)); candidatos.add(new Candidato(17, 17, 1, 2,3)); candidatos.add(new Candidato(18, 18, 1, 3)); candidatos.add(new Candidato(19, 19, 4, 1,2)); candidatos.add(new Candidato(20, 20, 4, 1,2,3)); ofertas = new ArrayList<Local>(); ofertas.add(new Local(1, 0)); ofertas.add(new Local(2, 0)); ofertas.add(new Local(3, 0)); ofertas.add(new Local(4, 0)); } //Super concorrncia pra um mesmo lugar public static void popular2() { candidatos = new ArrayList<Candidato>(); candidatos.add(new Candidato(1, 1, 3, 1,2)); candidatos.add(new Candidato(2, 2, 2, 1,3)); candidatos.add(new Candidato(3, 3, 1, 2)); candidatos.add(new Candidato(4, 4, 3, 1,2)); candidatos.add(new Candidato(4, 4, 4, 1,2)); candidatos.add(new Candidato(5, 5, 4, 1,2,3)); ofertas = new ArrayList<Local>(); ofertas.add(new Local(1, 0)); ofertas.add(new Local(2, 0)); ofertas.add(new Local(3, 0)); //ofertas.add(new Local(4, 0)); } public static List<Candidato> alocar() { List<Candidato> result = candidatos; Collections.sort(result); int movimentacoes; do{ movimentacoes=0; for(Candidato c:result){ for(int i =0; i< c.grauSatisfacao;i++){ Integer pref = c.preferencias.get(i); Local local = recuperaLocal(pref); if(local.vagasAbertas>0) { movimentaLocal(c, local); movimentacoes++; break; } } } }while(movimentacoes>0); return result; } public static List<Candidato> alocar2() { List<Candidato> result = candidatos; Collections.sort(result); Local limbo = criarLimbo(); enviaParaLimbo(result, limbo); for(int i=0; i< result.size(); i++){ Candidato candidato = result.get(i); boolean monvimento = false; for(Integer pref:candidato.preferencias){ Local local = recuperaLocal(pref); if(local.vagasAbertas>0) { movimentaLocal(candidato, local); monvimento = true; break; } } //checa se no houve movimentao, e piora o cara anterior if(!monvimento){ System.out.println("BT: C" + candidato.id + " sem alocao disponvel"); //ver quem da cadeia de cima pode ser piorado int candidatoApiorarIndice=0; for(int k = i-1; k >= 0; k--) { Candidato candidatoApiorar = result.get(k); if (candidatoApiorar.grauSatisfacao < candidatoApiorar.preferencias.size()-1)//Ainda d pra piorar { candidatoApiorarIndice=k; break; } } Candidato candidatoAnterior = result.get(candidatoApiorarIndice); //Piora a situacao do cara anterior Local proximaPreferencia = recuperaLocal(candidatoAnterior.preferencias.get(candidatoAnterior.grauSatisfacao+1)); movimentaLocal(candidatoAnterior, proximaPreferencia); //Move os cara abaixo dele para o limbo novamente for(int j=candidatoApiorarIndice+1; j< result.size(); j++){ movimentaLocal(result.get(j), limbo); } monvimento=true; i = candidatoApiorarIndice; } } return result; } public static void movimentaLocal(Candidato c, Local para) { System.out.println("MOV:C" + c.id + " de L"+c.localAtual + " para L"+para.id); Local localAtual = recuperaLocal(c.localAtual); localAtual.vagasAbertas++; c.localAtual=para.id; c.grauSatisfacao = c.preferencias.indexOf(para.id); para.vagasAbertas--; } public static Local recuperaLocal(int id) { for(Local c: ofertas) { if(c.id==id) return c; } return null; } public static void imprimirSituacao(List<Candidato> list) { for(Candidato c:list) { System.out.println("C" + c.id + " L"+c.localAtual + " S" + c.grauSatisfacao); } } public static List<Candidato> alocarRecursivo(){ List<Candidato> result = candidatos; Collections.sort(result); Local limbo = criarLimbo(); enviaParaLimbo(result, limbo); if(alocarRecursivo(result, 0, limbo)){ System.out.println("Soluo encontrada!"); } else { System.out.println("Problema sem soluo!"); } return result; } private static boolean alocarRecursivo(List<Candidato> result, int index, Local limbo){ if(index >= result.size()){ // caso base return true; } Candidato c = result.get(index); for(Integer prefId : c.preferencias){ Local pref = recuperaLocal(prefId); if(pref.vagasAbertas > 0){ movimentaLocal(c, pref); if(alocarRecursivo(result, index+1, limbo)){ return true; } } } System.out.println("BT: C" + c.id + " sem alocao disponvel"); movimentaLocal(c, limbo); return false; } private static Local criarLimbo(){ Local limbo = new Local(99, 0); ofertas.add(limbo); return limbo; } private static void enviaParaLimbo(List<Candidato> result, Local limbo){ for(Candidato c2:result) { c2.preferencias.add(c2.localAtual); movimentaLocal(c2, limbo); } } }
true
0e32c2aa507200772be532890d1fd1224ee6ef7f
Java
mahmoudbakar/BeetleWare
/app/src/main/java/com/beetleware/task/utils/Regex.java
UTF-8
218
1.695313
2
[]
no_license
package com.beetleware.task.utils; public interface Regex { String REGEX_PASSWORD = ".{6,}"; String REGEX_EGYPT_MOBILE = "(01)[0-9]{9}"; String REGEX_NAME = ".{2,}"; String REGEX_MESSAGE = ".{10,}"; }
true
fa9b1bb2b36c5eacebd6877ff2209617ea88291b
Java
zalopay-oss/hey-app
/hey-backend/src/main/java/com/hey/handler/WsHandler.java
UTF-8
9,526
2.203125
2
[ "MIT" ]
permissive
package com.hey.handler; import com.hey.manager.UserWsChannelManager; import com.hey.model.*; import com.hey.service.APIService; import com.hey.util.GenerationUtils; import io.vertx.core.CompositeFuture; import io.vertx.core.Future; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; public class WsHandler extends BaseHandler{ private UserWsChannelManager userWsChannelManager; private APIService apiService; public void setApiService(APIService apiService) { this.apiService = apiService; } public void setUserWsChannelManager(UserWsChannelManager userWsChannelManager) { this.userWsChannelManager = userWsChannelManager; } public void handleChatContainerRequest(ChatContainerRequest request, String channelId, String userId) { String sessionId = request.getSessionId(); Future<List<ChatItem>> futureChatItems = getChatItems(sessionId); futureChatItems.compose(chatItems -> { Future<Long> deleteUnseenCountFuture = dataRepository.deleteUnseenCount(userId, sessionId); deleteUnseenCountFuture.compose(deleteUnseenCountFutureRes -> { ChatContainerResponse response = new ChatContainerResponse(); response.setChatGroup(false); response.setSessionId(sessionId); response.setChatItems(chatItems); response.setType(IWsMessage.TYPE_CHAT_ITEM_RESPONSE); userWsChannelManager.selfSendMessage(response, channelId); }, Future.future().setHandler(handler -> { throw new RuntimeException(handler.cause()); })); }, Future.future().setHandler(handler -> { throw new RuntimeException(handler.cause()); })); } public void handleChatMessageRequest(ChatMessageRequest request, String channelId, String userId) { if("-1".equals(request.getSessionId())){ if(request.getUsernames().size() == 1){ insertChatMessageBetweenTwoOnNewChatSessionId(request, channelId, userId); }else{ insertChatMessageGroupOnNewChatSessionId(request, channelId, userId); } }else{ insertChatMessageOnExistedChatSessionId(request, channelId, userId); } } private void insertChatMessageOnNewChatSessionId(ChatMessageRequest request, String channelId, List<String> userIds){ Future<List<UserFull>> getUserFullsFuture = apiService.getUserFulls(userIds); getUserFullsFuture.compose(userFulls -> { List<UserHash> userHashes = new ArrayList<>(); for(UserFull userFull : userFulls){ userHashes.add(new UserHash(userFull.getUserId(), userFull.getFullName())); } String sessionId = GenerationUtils.generateId(); ChatMessage chatMessage = new ChatMessage(); chatMessage.setUserHash(userHashes.get(0)); chatMessage.setSessionId(sessionId); chatMessage.setMessage(request.getMessage()); chatMessage.setCreatedDate(new Date()); ChatList chatList = new ChatList(); chatList.setSessionId(sessionId); chatList.setUpdatedDate(new Date()); chatList.setUserHashes(userHashes); chatList.setLastMessage(chatMessage.getMessage()); chatList.setUpdatedDate(chatMessage.getCreatedDate()); Future<ChatList> insertChatListFuture = dataRepository.insertChatList(chatList); Future<ChatMessage> insertChatMessageFuture = dataRepository.insertChatMessage(chatMessage); List<String> userFriendIds = userIds.subList(1, userIds.size()); Future<HashMap<String, Long>> increaseUnseenCountFuture = apiService.increaseUnseenCount(userFriendIds, chatList.getSessionId()); CompositeFuture cp = CompositeFuture.all(insertChatMessageFuture, insertChatListFuture, increaseUnseenCountFuture); cp.setHandler(ar -> { if (ar.succeeded()) { NewChatSessionResponse newChatSessionResponse = new NewChatSessionResponse(); newChatSessionResponse.setType(IWsMessage.TYPE_CHAT_NEW_SESSION_RESPONSE); newChatSessionResponse.setSessionId(chatMessage.getSessionId()); //userWsChannelManager.selfSendMessage(newChatSessionResponse, channelId); for(UserHash userhash: chatList.getUserHashes()){ userWsChannelManager.sendMessage(newChatSessionResponse, userhash.getUserId()); } } else { throw new RuntimeException(ar.cause()); } }); }, Future.future().setHandler(handler -> { throw new RuntimeException(handler.cause()); })); } private void insertChatMessageBetweenTwoOnNewChatSessionId(ChatMessageRequest request, String channelId, String userId){ List<String> userIds = new ArrayList<>(); userIds.add(userId); userIds.add(request.getUsernames().get(0)); insertChatMessageOnNewChatSessionId(request, channelId, userIds); } private void insertChatMessageGroupOnNewChatSessionId(ChatMessageRequest request, String channelId, String userId){ Future<List<UserAuth>> getUserAuthsFuture = apiService.getUserAuths(request.getUsernames()); getUserAuthsFuture.compose(userAuths -> { List<String> userIds = new ArrayList<>(); userIds.add(userId); for(UserAuth userAuth : userAuths){ userIds.add(userAuth.getUserId()); } insertChatMessageOnNewChatSessionId(request, channelId, userIds); }, Future.future().setHandler(handler -> { throw new RuntimeException(handler.cause()); })); } private void insertChatMessageOnExistedChatSessionId(ChatMessageRequest request, String channelId, String userId){ Future<UserFull> getUserFullFuture = dataRepository.getUserFull(userId); long startTime = System.currentTimeMillis(); getUserFullFuture.compose(userFull -> { long elapsed = System.currentTimeMillis() - startTime; //System.out.println("Handler: " + elapsed); ChatMessage chatMessage = new ChatMessage(); chatMessage.setUserHash(new UserHash(userFull.getUserId(), userFull.getFullName())); chatMessage.setSessionId(request.getSessionId()); chatMessage.setMessage(request.getMessage()); chatMessage.setCreatedDate(new Date()); Future<ChatMessage> insertChatMessagesAndUpdateChatListAndUpdateUnseenCountFuture = apiService.insertChatMessagesAndUpdateChatListAndUpdateUnseenCount(chatMessage); Future<ChatList> getChatListBySessionIdFuture = apiService.getChatListBySessionId(chatMessage.getSessionId()); CompositeFuture cp = CompositeFuture.all(insertChatMessagesAndUpdateChatListAndUpdateUnseenCountFuture, getChatListBySessionIdFuture); cp.setHandler(ar -> { if (ar.succeeded()) { ChatList chatList = cp.resultAt(1); ChatMessageResponse response = new ChatMessageResponse(); response.setType(IWsMessage.TYPE_CHAT_MESSAGE_RESPONSE); response.setCreatedDate(chatMessage.getCreatedDate()); response.setName(userFull.getFullName()); response.setMessage(chatMessage.getMessage()); response.setSessionId(chatMessage.getSessionId()); response.setUserId(chatMessage.getUserHash().getUserId()); //userWsChannelManager.selfSendMessage(response, channelId); for(UserHash userhash: chatList.getUserHashes()){ userWsChannelManager.sendMessage(response, userhash.getUserId()); } } else { throw new RuntimeException(ar.cause()); } }); } , Future.future().setHandler(handler -> { throw new RuntimeException(handler.cause()); })); } private Future<List<ChatItem>> getChatItems(String sessionId) { Future<List<ChatItem>> future = Future.future(); List<ChatItem> chatItems = new ArrayList<>(); Future<List<ChatMessage>> getChatMessagesFuture = apiService.getChatMessages(sessionId); getChatMessagesFuture.compose(chatMessages -> { for(ChatMessage chatMessage : chatMessages){ ChatItem chatItem = new ChatItem(); chatItem.setUserId(chatMessage.getUserHash().getUserId()); chatItem.setName(chatMessage.getUserHash().getFullName()); chatItem.setMessage(chatMessage.getMessage()); chatItem.setCreatedDate(chatMessage.getCreatedDate()); chatItems.add(chatItem); } future.complete(chatItems); } , Future.future().setHandler(handler -> { future.fail(handler.cause()); })); return future; } public Future<List<FriendList>> getFriendLists(String userId) { return apiService.getFriendLists(userId); } public Future<UserFull> getUserFull(String userId) { return dataRepository.getUserFull(userId); } }
true
8c88dbe98e37f8b884f294e00cefcbb13a5c3926
Java
Angavi/Gadgets
/project1/src/main/java/com/niit/daoimpl/CategoryDaoImpl.java
UTF-8
2,145
2.359375
2
[]
no_license
package com.niit.daoimpl; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.Query; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.niit.dao.CategoryDao; import com.niit.model.Category; import com.niit.model.Product; @Repository public class CategoryDaoImpl implements CategoryDao { @Autowired private SessionFactory sessionFactory; public void saveCategory(Category category) { Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); System.out.println("PRODUCT ID BEFORE INSERTION" + category.getCid()); session.save(category); System.out.println("PRODUCT ID AFTER INSERTION" + category.getCid()); transaction.commit(); session.close(); } public List<Category> getAllCategories() { Session session = sessionFactory.openSession(); Query query = session.createQuery("from Category"); List<Category> categories = query.list(); session.close(); return categories; } public Category getCategoryById(int cid) { Session session = sessionFactory.openSession(); Category category = (Category) session.get(Category.class, cid); session.close(); return category; } public void deleteCategory(int cid) { Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); Category category = (Category) session.get(Category.class, cid); session.delete(category); transaction.commit(); session.close(); } public void updateCategory(Category category) { Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); session.update(category); transaction.commit(); session.close(); } public List<Category> getAllCategory() { Session session = sessionFactory.openSession(); Query query = session.createQuery("from Category"); List<Category> category = query.list(); session.close(); return category; } }
true
36cf3ad0469eba1709a4c66e159ef740b1f771d6
Java
phillipus85/ETLMetricsDataset
/2015-02/Individual Projects/Grupo 6/DocumentalToSql/src/main/java/co/com/ap/core/Conexion.java
UTF-8
2,102
2.765625
3
[]
no_license
package co.com.ap.core; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class Conexion { private static String JDBC_DRIVER = "com.mysql.jdbc.Driver"; private static String JDBC_URL = "jdbc:mysql://localhost/automatizacion"; private static String JDBC_USER = "desarrollo"; private static String JDBC_PASS = "desarrollo"; private static Driver driver = null; public static synchronized Connection getConnection() throws SQLException{ if(driver == null){ @SuppressWarnings("rawtypes") Class jdbcDriverClass = null; try { jdbcDriverClass = Class.forName(JDBC_DRIVER); driver = (Driver) jdbcDriverClass.newInstance(); DriverManager.registerDriver(driver); } catch (InstantiationException e) { System.out.println("Problemas cargando driver "+e); } catch (IllegalAccessException e) { System.out.println("Problemas cargando driver "+e); }catch (ClassNotFoundException e) { System.out.println("Problemas cargando driver "+e); } } return DriverManager.getConnection(JDBC_URL,JDBC_USER,JDBC_PASS); } public static void close(ResultSet rs){ try { if(rs != null) rs.close(); } catch (Exception e) { System.out.println("Error close"); } } public static void close(PreparedStatement stmt){ try { if(stmt != null) stmt.close(); } catch (Exception e) { System.out.println("Error close"); } } public static void close(Connection conn){ try { if(conn != null) conn.close(); } catch (Exception e) { System.out.println("Error close"); } } public static String getJDBC_URL() { return JDBC_URL; } public static void setJDBC_URL(String jDBC_URL) { JDBC_URL = jDBC_URL; } public static String getJDBC_USER() { return JDBC_USER; } public static void setJDBC_USER(String jDBC_USER) { JDBC_USER = jDBC_USER; } public static String getJDBC_PASS() { return JDBC_PASS; } public static void setJDBC_PASS(String jDBC_PASS) { JDBC_PASS = jDBC_PASS; } }
true
42050fbb59ee4c2995999035d420bd326325921d
Java
TencentCloud/tencentcloud-sdk-java-intl-en
/src/main/java/com/tencentcloudapi/mps/v20190612/models/DescribeTaskDetailResponse.java
UTF-8
21,439
1.851563
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencentcloudapi.mps.v20190612.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class DescribeTaskDetailResponse extends AbstractModel{ /** * The task type. Valid values: <li>WorkflowTask</li> <li>EditMediaTask</li> <li>LiveStreamProcessTask</li> <li>ScheduleTask (scheme)</li> */ @SerializedName("TaskType") @Expose private String TaskType; /** * Task status. Valid values: <li>WAITING: Waiting;</li> <li>PROCESSING: Processing;</li> <li>FINISH: Completed.</li> */ @SerializedName("Status") @Expose private String Status; /** * Creation time of a task in [ISO date format](https://intl.cloud.tencent.com/document/product/266/11732?from_cn_redirect=1#iso-.E6.97.A5.E6.9C.9F.E6.A0.BC.E5.BC.8F). */ @SerializedName("CreateTime") @Expose private String CreateTime; /** * Start time of task execution in [ISO date format](https://intl.cloud.tencent.com/document/product/266/11732?from_cn_redirect=1#iso-.E6.97.A5.E6.9C.9F.E6.A0.BC.E5.BC.8F). */ @SerializedName("BeginProcessTime") @Expose private String BeginProcessTime; /** * End time of task execution in [ISO date format](https://intl.cloud.tencent.com/document/product/266/11732?from_cn_redirect=1#iso-.E6.97.A5.E6.9C.9F.E6.A0.BC.E5.BC.8F). */ @SerializedName("FinishTime") @Expose private String FinishTime; /** * Video editing task information. This field has a value only when `TaskType` is `EditMediaTask`. */ @SerializedName("EditMediaTask") @Expose private EditMediaTask EditMediaTask; /** * Information of a video processing task. This field has a value only when `TaskType` is `WorkflowTask`. Note: This field may return null, indicating that no valid values can be obtained. */ @SerializedName("WorkflowTask") @Expose private WorkflowTask WorkflowTask; /** * Information of a live stream processing task. This field has a value only when `TaskType` is `LiveStreamProcessTask`. Note: This field may return null, indicating that no valid values can be obtained. */ @SerializedName("LiveStreamProcessTask") @Expose private LiveStreamProcessTask LiveStreamProcessTask; /** * Event notification information of a task. Note: This field may return null, indicating that no valid values can be obtained. */ @SerializedName("TaskNotifyConfig") @Expose private TaskNotifyConfig TaskNotifyConfig; /** * Task flow priority. Value range: [-10, 10]. */ @SerializedName("TasksPriority") @Expose private Long TasksPriority; /** * The ID used for deduplication. If there was a request with the same ID in the last seven days, the current request will return an error. The ID can contain up to 50 characters. If this parameter is left empty or an empty string is entered, no deduplication will be performed. */ @SerializedName("SessionId") @Expose private String SessionId; /** * The source context which is used to pass through the user request information. The task flow status change callback will return the value of this field. It can contain up to 1,000 characters. */ @SerializedName("SessionContext") @Expose private String SessionContext; /** * Extended information field, used in specific scenarios. */ @SerializedName("ExtInfo") @Expose private String ExtInfo; /** * The information of a scheme. This parameter is valid only if `TaskType` is `ScheduleTask`. Note: This field may return null, indicating that no valid values can be obtained. */ @SerializedName("ScheduleTask") @Expose private ScheduleTask ScheduleTask; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. */ @SerializedName("RequestId") @Expose private String RequestId; /** * Get The task type. Valid values: <li>WorkflowTask</li> <li>EditMediaTask</li> <li>LiveStreamProcessTask</li> <li>ScheduleTask (scheme)</li> * @return TaskType The task type. Valid values: <li>WorkflowTask</li> <li>EditMediaTask</li> <li>LiveStreamProcessTask</li> <li>ScheduleTask (scheme)</li> */ public String getTaskType() { return this.TaskType; } /** * Set The task type. Valid values: <li>WorkflowTask</li> <li>EditMediaTask</li> <li>LiveStreamProcessTask</li> <li>ScheduleTask (scheme)</li> * @param TaskType The task type. Valid values: <li>WorkflowTask</li> <li>EditMediaTask</li> <li>LiveStreamProcessTask</li> <li>ScheduleTask (scheme)</li> */ public void setTaskType(String TaskType) { this.TaskType = TaskType; } /** * Get Task status. Valid values: <li>WAITING: Waiting;</li> <li>PROCESSING: Processing;</li> <li>FINISH: Completed.</li> * @return Status Task status. Valid values: <li>WAITING: Waiting;</li> <li>PROCESSING: Processing;</li> <li>FINISH: Completed.</li> */ public String getStatus() { return this.Status; } /** * Set Task status. Valid values: <li>WAITING: Waiting;</li> <li>PROCESSING: Processing;</li> <li>FINISH: Completed.</li> * @param Status Task status. Valid values: <li>WAITING: Waiting;</li> <li>PROCESSING: Processing;</li> <li>FINISH: Completed.</li> */ public void setStatus(String Status) { this.Status = Status; } /** * Get Creation time of a task in [ISO date format](https://intl.cloud.tencent.com/document/product/266/11732?from_cn_redirect=1#iso-.E6.97.A5.E6.9C.9F.E6.A0.BC.E5.BC.8F). * @return CreateTime Creation time of a task in [ISO date format](https://intl.cloud.tencent.com/document/product/266/11732?from_cn_redirect=1#iso-.E6.97.A5.E6.9C.9F.E6.A0.BC.E5.BC.8F). */ public String getCreateTime() { return this.CreateTime; } /** * Set Creation time of a task in [ISO date format](https://intl.cloud.tencent.com/document/product/266/11732?from_cn_redirect=1#iso-.E6.97.A5.E6.9C.9F.E6.A0.BC.E5.BC.8F). * @param CreateTime Creation time of a task in [ISO date format](https://intl.cloud.tencent.com/document/product/266/11732?from_cn_redirect=1#iso-.E6.97.A5.E6.9C.9F.E6.A0.BC.E5.BC.8F). */ public void setCreateTime(String CreateTime) { this.CreateTime = CreateTime; } /** * Get Start time of task execution in [ISO date format](https://intl.cloud.tencent.com/document/product/266/11732?from_cn_redirect=1#iso-.E6.97.A5.E6.9C.9F.E6.A0.BC.E5.BC.8F). * @return BeginProcessTime Start time of task execution in [ISO date format](https://intl.cloud.tencent.com/document/product/266/11732?from_cn_redirect=1#iso-.E6.97.A5.E6.9C.9F.E6.A0.BC.E5.BC.8F). */ public String getBeginProcessTime() { return this.BeginProcessTime; } /** * Set Start time of task execution in [ISO date format](https://intl.cloud.tencent.com/document/product/266/11732?from_cn_redirect=1#iso-.E6.97.A5.E6.9C.9F.E6.A0.BC.E5.BC.8F). * @param BeginProcessTime Start time of task execution in [ISO date format](https://intl.cloud.tencent.com/document/product/266/11732?from_cn_redirect=1#iso-.E6.97.A5.E6.9C.9F.E6.A0.BC.E5.BC.8F). */ public void setBeginProcessTime(String BeginProcessTime) { this.BeginProcessTime = BeginProcessTime; } /** * Get End time of task execution in [ISO date format](https://intl.cloud.tencent.com/document/product/266/11732?from_cn_redirect=1#iso-.E6.97.A5.E6.9C.9F.E6.A0.BC.E5.BC.8F). * @return FinishTime End time of task execution in [ISO date format](https://intl.cloud.tencent.com/document/product/266/11732?from_cn_redirect=1#iso-.E6.97.A5.E6.9C.9F.E6.A0.BC.E5.BC.8F). */ public String getFinishTime() { return this.FinishTime; } /** * Set End time of task execution in [ISO date format](https://intl.cloud.tencent.com/document/product/266/11732?from_cn_redirect=1#iso-.E6.97.A5.E6.9C.9F.E6.A0.BC.E5.BC.8F). * @param FinishTime End time of task execution in [ISO date format](https://intl.cloud.tencent.com/document/product/266/11732?from_cn_redirect=1#iso-.E6.97.A5.E6.9C.9F.E6.A0.BC.E5.BC.8F). */ public void setFinishTime(String FinishTime) { this.FinishTime = FinishTime; } /** * Get Video editing task information. This field has a value only when `TaskType` is `EditMediaTask`. * @return EditMediaTask Video editing task information. This field has a value only when `TaskType` is `EditMediaTask`. */ public EditMediaTask getEditMediaTask() { return this.EditMediaTask; } /** * Set Video editing task information. This field has a value only when `TaskType` is `EditMediaTask`. * @param EditMediaTask Video editing task information. This field has a value only when `TaskType` is `EditMediaTask`. */ public void setEditMediaTask(EditMediaTask EditMediaTask) { this.EditMediaTask = EditMediaTask; } /** * Get Information of a video processing task. This field has a value only when `TaskType` is `WorkflowTask`. Note: This field may return null, indicating that no valid values can be obtained. * @return WorkflowTask Information of a video processing task. This field has a value only when `TaskType` is `WorkflowTask`. Note: This field may return null, indicating that no valid values can be obtained. */ public WorkflowTask getWorkflowTask() { return this.WorkflowTask; } /** * Set Information of a video processing task. This field has a value only when `TaskType` is `WorkflowTask`. Note: This field may return null, indicating that no valid values can be obtained. * @param WorkflowTask Information of a video processing task. This field has a value only when `TaskType` is `WorkflowTask`. Note: This field may return null, indicating that no valid values can be obtained. */ public void setWorkflowTask(WorkflowTask WorkflowTask) { this.WorkflowTask = WorkflowTask; } /** * Get Information of a live stream processing task. This field has a value only when `TaskType` is `LiveStreamProcessTask`. Note: This field may return null, indicating that no valid values can be obtained. * @return LiveStreamProcessTask Information of a live stream processing task. This field has a value only when `TaskType` is `LiveStreamProcessTask`. Note: This field may return null, indicating that no valid values can be obtained. */ public LiveStreamProcessTask getLiveStreamProcessTask() { return this.LiveStreamProcessTask; } /** * Set Information of a live stream processing task. This field has a value only when `TaskType` is `LiveStreamProcessTask`. Note: This field may return null, indicating that no valid values can be obtained. * @param LiveStreamProcessTask Information of a live stream processing task. This field has a value only when `TaskType` is `LiveStreamProcessTask`. Note: This field may return null, indicating that no valid values can be obtained. */ public void setLiveStreamProcessTask(LiveStreamProcessTask LiveStreamProcessTask) { this.LiveStreamProcessTask = LiveStreamProcessTask; } /** * Get Event notification information of a task. Note: This field may return null, indicating that no valid values can be obtained. * @return TaskNotifyConfig Event notification information of a task. Note: This field may return null, indicating that no valid values can be obtained. */ public TaskNotifyConfig getTaskNotifyConfig() { return this.TaskNotifyConfig; } /** * Set Event notification information of a task. Note: This field may return null, indicating that no valid values can be obtained. * @param TaskNotifyConfig Event notification information of a task. Note: This field may return null, indicating that no valid values can be obtained. */ public void setTaskNotifyConfig(TaskNotifyConfig TaskNotifyConfig) { this.TaskNotifyConfig = TaskNotifyConfig; } /** * Get Task flow priority. Value range: [-10, 10]. * @return TasksPriority Task flow priority. Value range: [-10, 10]. */ public Long getTasksPriority() { return this.TasksPriority; } /** * Set Task flow priority. Value range: [-10, 10]. * @param TasksPriority Task flow priority. Value range: [-10, 10]. */ public void setTasksPriority(Long TasksPriority) { this.TasksPriority = TasksPriority; } /** * Get The ID used for deduplication. If there was a request with the same ID in the last seven days, the current request will return an error. The ID can contain up to 50 characters. If this parameter is left empty or an empty string is entered, no deduplication will be performed. * @return SessionId The ID used for deduplication. If there was a request with the same ID in the last seven days, the current request will return an error. The ID can contain up to 50 characters. If this parameter is left empty or an empty string is entered, no deduplication will be performed. */ public String getSessionId() { return this.SessionId; } /** * Set The ID used for deduplication. If there was a request with the same ID in the last seven days, the current request will return an error. The ID can contain up to 50 characters. If this parameter is left empty or an empty string is entered, no deduplication will be performed. * @param SessionId The ID used for deduplication. If there was a request with the same ID in the last seven days, the current request will return an error. The ID can contain up to 50 characters. If this parameter is left empty or an empty string is entered, no deduplication will be performed. */ public void setSessionId(String SessionId) { this.SessionId = SessionId; } /** * Get The source context which is used to pass through the user request information. The task flow status change callback will return the value of this field. It can contain up to 1,000 characters. * @return SessionContext The source context which is used to pass through the user request information. The task flow status change callback will return the value of this field. It can contain up to 1,000 characters. */ public String getSessionContext() { return this.SessionContext; } /** * Set The source context which is used to pass through the user request information. The task flow status change callback will return the value of this field. It can contain up to 1,000 characters. * @param SessionContext The source context which is used to pass through the user request information. The task flow status change callback will return the value of this field. It can contain up to 1,000 characters. */ public void setSessionContext(String SessionContext) { this.SessionContext = SessionContext; } /** * Get Extended information field, used in specific scenarios. * @return ExtInfo Extended information field, used in specific scenarios. */ public String getExtInfo() { return this.ExtInfo; } /** * Set Extended information field, used in specific scenarios. * @param ExtInfo Extended information field, used in specific scenarios. */ public void setExtInfo(String ExtInfo) { this.ExtInfo = ExtInfo; } /** * Get The information of a scheme. This parameter is valid only if `TaskType` is `ScheduleTask`. Note: This field may return null, indicating that no valid values can be obtained. * @return ScheduleTask The information of a scheme. This parameter is valid only if `TaskType` is `ScheduleTask`. Note: This field may return null, indicating that no valid values can be obtained. */ public ScheduleTask getScheduleTask() { return this.ScheduleTask; } /** * Set The information of a scheme. This parameter is valid only if `TaskType` is `ScheduleTask`. Note: This field may return null, indicating that no valid values can be obtained. * @param ScheduleTask The information of a scheme. This parameter is valid only if `TaskType` is `ScheduleTask`. Note: This field may return null, indicating that no valid values can be obtained. */ public void setScheduleTask(ScheduleTask ScheduleTask) { this.ScheduleTask = ScheduleTask; } /** * Get The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @return RequestId The unique request ID, which is returned for each request. RequestId is required for locating a problem. */ public String getRequestId() { return this.RequestId; } /** * Set The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @param RequestId The unique request ID, which is returned for each request. RequestId is required for locating a problem. */ public void setRequestId(String RequestId) { this.RequestId = RequestId; } public DescribeTaskDetailResponse() { } /** * NOTE: Any ambiguous key set via .set("AnyKey", "value") will be a shallow copy, * and any explicit key, i.e Foo, set via .setFoo("value") will be a deep copy. */ public DescribeTaskDetailResponse(DescribeTaskDetailResponse source) { if (source.TaskType != null) { this.TaskType = new String(source.TaskType); } if (source.Status != null) { this.Status = new String(source.Status); } if (source.CreateTime != null) { this.CreateTime = new String(source.CreateTime); } if (source.BeginProcessTime != null) { this.BeginProcessTime = new String(source.BeginProcessTime); } if (source.FinishTime != null) { this.FinishTime = new String(source.FinishTime); } if (source.EditMediaTask != null) { this.EditMediaTask = new EditMediaTask(source.EditMediaTask); } if (source.WorkflowTask != null) { this.WorkflowTask = new WorkflowTask(source.WorkflowTask); } if (source.LiveStreamProcessTask != null) { this.LiveStreamProcessTask = new LiveStreamProcessTask(source.LiveStreamProcessTask); } if (source.TaskNotifyConfig != null) { this.TaskNotifyConfig = new TaskNotifyConfig(source.TaskNotifyConfig); } if (source.TasksPriority != null) { this.TasksPriority = new Long(source.TasksPriority); } if (source.SessionId != null) { this.SessionId = new String(source.SessionId); } if (source.SessionContext != null) { this.SessionContext = new String(source.SessionContext); } if (source.ExtInfo != null) { this.ExtInfo = new String(source.ExtInfo); } if (source.ScheduleTask != null) { this.ScheduleTask = new ScheduleTask(source.ScheduleTask); } if (source.RequestId != null) { this.RequestId = new String(source.RequestId); } } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamSimple(map, prefix + "TaskType", this.TaskType); this.setParamSimple(map, prefix + "Status", this.Status); this.setParamSimple(map, prefix + "CreateTime", this.CreateTime); this.setParamSimple(map, prefix + "BeginProcessTime", this.BeginProcessTime); this.setParamSimple(map, prefix + "FinishTime", this.FinishTime); this.setParamObj(map, prefix + "EditMediaTask.", this.EditMediaTask); this.setParamObj(map, prefix + "WorkflowTask.", this.WorkflowTask); this.setParamObj(map, prefix + "LiveStreamProcessTask.", this.LiveStreamProcessTask); this.setParamObj(map, prefix + "TaskNotifyConfig.", this.TaskNotifyConfig); this.setParamSimple(map, prefix + "TasksPriority", this.TasksPriority); this.setParamSimple(map, prefix + "SessionId", this.SessionId); this.setParamSimple(map, prefix + "SessionContext", this.SessionContext); this.setParamSimple(map, prefix + "ExtInfo", this.ExtInfo); this.setParamObj(map, prefix + "ScheduleTask.", this.ScheduleTask); this.setParamSimple(map, prefix + "RequestId", this.RequestId); } }
true
e6ab84d714314b2960f0aedced10cec125ec3a31
Java
MosesRen/leetcode-idea
/src/leetcode/editor/cn/476.数字的补数.java
UTF-8
271
2.640625
3
[]
no_license
/* * @lc app=leetcode.cn id=476 lang=java * * [476] 数字的补数 */ class Solution { public int findComplement(int num) { // ~num 取反 //Integer.highestOneBit(num) 取最高位 return ~num & (Integer.highestOneBit(num) - 1); } }
true
8b7cd8c39060d03e2f5eb6c83743bab93d133573
Java
hanonator/RS2-Emulator
/src/org/hannes/rs2/content/misc/CommonObjectEventHandler.java
UTF-8
554
2.453125
2
[]
no_license
package org.hannes.rs2.content.misc; import org.hannes.entity.Player; import org.hannes.event.ObjectInteractionEvent; import org.hannes.event.hub.EventHandler; /** * Event handler for ladders, bookcases, drawers, crates, etc. * * @author red * */ public class CommonObjectEventHandler implements EventHandler<ObjectInteractionEvent> { @Override public void handleEvent(ObjectInteractionEvent event, Player player) throws Exception { System.out.println(event.getId() + "," + event.getX() + "," + event.getY() + "," + event.getAction()); } }
true
6cedf105bc2b925d364ac886bcc387112de7a93a
Java
arineto/SiscomRFID
/src/util/Util.java
IBM852
4,212
2.765625
3
[]
no_license
package util; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.math.BigInteger; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.List; import java.util.Random; public class Util { private static final int QTD_BITS = 96; public static void startBrowser(String url) { String os = System.getProperty("os.name").toLowerCase(); Runtime rt = Runtime.getRuntime(); try{ if (os.indexOf( "win" ) >= 0) { // this doesn't support showing urls in the form of "page.html#nameLink" rt.exec( "rundll32 url.dll,FileProtocolHandler " + url); } else if (os.indexOf( "mac" ) >= 0) { rt.exec( "open " + url); } else if (os.indexOf( "nix") >=0 || os.indexOf( "nux") >=0) { // Do a best guess on unix until we get a platform independent way // Build a list of browsers to try, in this order. String[] browsers = {"epiphany", "firefox", "mozilla", "konqueror", "netscape","opera","links","lynx"}; // Build a command string which looks like "browser1 "url" || browser2 "url" ||..." StringBuffer cmd = new StringBuffer(); for (int i=0; i<browsers.length; i++) { cmd.append( (i==0 ? "" : " || " ) + browsers[i] +" \"" + url + "\" "); } rt.exec(new String[] { "sh", "-c", cmd.toString() }); } else { System.out.println("Erro ao abrir navegador!"); System.out.println("s imagens foram geradas na pasta ~/index/dfsa ou ~/index/tree, " + "para protocolos DFSA e baseados em rvore, respectivamente."); return; } }catch (Exception e){ System.out.println("Erro ao abrir navegador!"); System.out.println("s imagens foram geradas na pasta ~/index/dfsa ou ~/index/tree, " + "para protocolos DFSA e baseados em rvore, respectivamente."); return; } } /** * Cria um numero X de tags (96 bits) aleatorias, sem repeticao, * de acordo com o valor passado como parametro. * * @param qtdTags * Quantidadade de tags que devem ser geradas. * @return Buffer com todas as tags, uma por linha. */ private static StringBuilder criarTags(int qtdTags) { StringBuilder builder = null; List<String> l = null; BigInteger a = null; String tag = null; builder = new StringBuilder(); l = new ArrayList<String>(); for(int j = 0; j < qtdTags; j++) { a = new BigInteger(140, new Random()); if(!l.contains(a)) { tag = a.toString(2).substring(0, QTD_BITS); l.add(tag); builder.append(tag.concat("\r\n")); } } return builder; } /** * Gera 1000 arquivos, numerados de 1 a 1000, * com o numero de tags passado como parametro, * salvando-os em seus respectivos diretorios. * * @param qtdTags * Numero de tags em cada arquivo criado. */ private static void salvarArquivos(int qtdTags) { byte[] buffer = null; RandomAccessFile raf = null; FileChannel channel = null; ByteBuffer byteBuffer = null; try { for(int i = 1; i <= 500; i++) { buffer = criarTags(qtdTags).toString().getBytes(); raf = new RandomAccessFile("tags/"+qtdTags+"/"+i+".txt", "rw"); channel = raf.getChannel(); byteBuffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, buffer.length); byteBuffer.put(buffer); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if(channel != null) { channel.close(); } if (raf != null) { raf.close(); } } catch (IOException e) { e.printStackTrace(); } } } /** * Gera todos os arquivos para os testes. */ public static void gerarArquivosTags() { for(int qtdTags = 100; qtdTags <= 1000; qtdTags+=100) { System.out.printf("Criando arquivos com %d tags... ", qtdTags); salvarArquivos(qtdTags); System.out.println("OK!"); } System.out.println("rquivos criados!"); } public static void main(String[] args) { gerarArquivosTags(); } }
true
576d0bdf8fce982a6c95a2d39b6188f7e6cecf07
Java
ataramasco/ExampleAppiumaws
/appium_ex_homeLogin/src/test/java/Tests/WebViewTest.java
UTF-8
995
2.59375
3
[]
no_license
package Tests; import Pages.WebViewPage; import Tests.AbstractBaseTests.TestBase; import org.testng.Assert; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; /** * Tests for a webview */ public class WebViewTest extends TestBase { private final String FULL_URL = "http://www.google.com"; private final String WEBVIEW_ACCESSIBILITY = "Google"; private WebViewPage webViewPage; @Override public String getName() { return "Web"; } /** * Sets up the webview page */ @BeforeTest @Override public void setUpPage() { webViewPage = new WebViewPage(driver); } /** * Inputs navigates to a URL and then checks if the url is loaded by * checking the webview's content description */ @Test public void testWebView() throws InterruptedException { webViewPage.gotoUrl(FULL_URL); Assert.assertTrue(webViewPage.getWebDescription(WEBVIEW_ACCESSIBILITY)); } }
true
cef58884375173d3d48dfd6724259a62a317b527
Java
Nedelosk/Modular-Machines
/src/main/java/modularmachines/common/modules/tools/ModuleModeMachine.java
UTF-8
2,002
2.453125
2
[ "MIT" ]
permissive
package modularmachines.common.modules.tools; import modularmachines.api.modules.IModulePage; import modularmachines.api.modules.containers.IModuleContainer; import modularmachines.api.modules.containers.IModuleProvider; import modularmachines.api.modules.state.IModuleState; import modularmachines.api.modules.tools.IModuleModeMachine; import modularmachines.api.modules.tools.ModuleMachine; import modularmachines.api.property.PropertyToolMode; import modularmachines.api.recipes.IToolMode; import modularmachines.common.modules.pages.ControllerPage; import modularmachines.common.modules.pages.MainPage; public abstract class ModuleModeMachine extends ModuleMachine implements IModuleModeMachine { public final PropertyToolMode MODE; public ModuleModeMachine(String name, IToolMode defaultMode) { super(name); MODE = new PropertyToolMode("mode", getModeClass(), defaultMode); } @Override public IModuleState createState(IModuleProvider provider, IModuleContainer container) { return super.createState(provider, container).register(MODE); } protected abstract Class<? extends IToolMode> getModeClass(); @Override public IToolMode getNextMode(IModuleState state) { IToolMode[] modes = getModeClass().getEnumConstants(); IToolMode mode = getCurrentMode(state); if (mode.ordinal() == modes.length - 1) { return getMode(0); } return getMode(mode.ordinal() + 1); } @Override public IToolMode getMode(int index) { IToolMode[] modes = getModeClass().getEnumConstants(); if (modes.length <= index) { return null; } return modes[index]; } @Override public IToolMode getCurrentMode(IModuleState state) { return state.get(MODE); } @Override public void setCurrentMode(IModuleState state, IToolMode mode) { state.set(MODE, mode); } @Override protected Class<? extends IModulePage> getMainPageClass() { return MainPage.class; } @Override protected IModulePage getControllerPage(IModuleState state) { return new ControllerPage(state); } }
true
77d1e5d3ec6b48fa98a7a00be2c31a8a2f4a5cb7
Java
GabrielGamarano/Java
/Vendas/src/model/service/NovoEstoqueService.java
UTF-8
482
2.15625
2
[]
no_license
package model.service; import java.util.List; import model.dao.DaoFactory; import model.dao.NovoEstoqueDao; import model.entidades.PedidoEstoque; public class NovoEstoqueService { private NovoEstoqueDao dao = DaoFactory.createNovoEstoqueDao(); public List<PedidoEstoque> findAll(){ return dao.findAll(); } public void saveOrUpdate(PedidoEstoque obj) { if (obj.getOrderId() == null) { dao.insert(obj); }else { dao.update(obj); } } }
true
2ce5f8138d149a6a2d6bf25d0a52e6d24db25228
Java
Cny0306/v17
/v17-web/v17-order/src/main/java/com/hgz/v17order/controller/OrderController.java
UTF-8
790
2.296875
2
[]
no_license
package com.hgz.v17order.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /** * @author huangguizhao * 1.进入订单确认页 * 1.1 当前身份合法认证,是否已登录() * 1.2 展示相关数据() */ @Controller @RequestMapping("order") public class OrderController { @RequestMapping("toConfirm") public String toConfirm(){ System.out.println("进入订单确认页逻辑,获取各种数据....."); //1.获取到当前用户 //2.获取当前用户对应的购物车信息 //3.获取当前用户的收件人信息 //4.获取付款方式 //5.获取物流商信息 //6,跳转到页面展示 return "confirm"; } }
true
fda04a1bcfb11a386e0a30dffcf695028c2b23d6
Java
alexcmd/JGooglePlay
/src/com/google/play/proto/BillingInstrumentsProto.java
UTF-8
2,863
2.28125
2
[ "Apache-2.0" ]
permissive
// Code generated by Wire protocol buffer compiler, do not edit. // Source file: proto/Purchase.proto package com.google.play.proto; import com.squareup.wire.Message; import com.squareup.wire.ProtoField; import java.util.Collections; import java.util.List; import static com.squareup.wire.Message.Datatype.STRING; import static com.squareup.wire.Message.Label.REPEATED; public final class BillingInstrumentsProto extends Message { public static final List<BillingInstrumentProto> DEFAULT_BILLINGINSTRUMENT = Collections.emptyList(); public static final String DEFAULT_DEFAULTBILLINGINSTRUMENTID = ""; @ProtoField(tag = 4, label = REPEATED) public final List<BillingInstrumentProto> billingInstrument; @ProtoField(tag = 8, type = STRING) public final String defaultBillingInstrumentId; public BillingInstrumentsProto(List<BillingInstrumentProto> billingInstrument, String defaultBillingInstrumentId) { this.billingInstrument = immutableCopyOf(billingInstrument); this.defaultBillingInstrumentId = defaultBillingInstrumentId; } private BillingInstrumentsProto(Builder builder) { this(builder.billingInstrument, builder.defaultBillingInstrumentId); setBuilder(builder); } @Override public boolean equals(Object other) { if (other == this) return true; if (!(other instanceof BillingInstrumentsProto)) return false; BillingInstrumentsProto o = (BillingInstrumentsProto) other; return equals(billingInstrument, o.billingInstrument) && equals(defaultBillingInstrumentId, o.defaultBillingInstrumentId); } @Override public int hashCode() { int result = hashCode; if (result == 0) { result = billingInstrument != null ? billingInstrument.hashCode() : 1; result = result * 37 + (defaultBillingInstrumentId != null ? defaultBillingInstrumentId.hashCode() : 0); hashCode = result; } return result; } public static final class Builder extends Message.Builder<BillingInstrumentsProto> { public List<BillingInstrumentProto> billingInstrument; public String defaultBillingInstrumentId; public Builder() { } public Builder(BillingInstrumentsProto message) { super(message); if (message == null) return; this.billingInstrument = copyOf(message.billingInstrument); this.defaultBillingInstrumentId = message.defaultBillingInstrumentId; } public Builder billingInstrument(List<BillingInstrumentProto> billingInstrument) { this.billingInstrument = checkForNulls(billingInstrument); return this; } public Builder defaultBillingInstrumentId(String defaultBillingInstrumentId) { this.defaultBillingInstrumentId = defaultBillingInstrumentId; return this; } @Override public BillingInstrumentsProto build() { return new BillingInstrumentsProto(this); } } }
true
5f12399600106f6f97397d998f5fb0cf2b51f973
Java
N0589776/MPDHeritageMalta
/app/src/main/java/com/example/hayden/heritagemalta2/MainActivity.java
UTF-8
10,211
1.789063
2
[]
no_license
package com.example.hayden.heritagemalta2; import android.Manifest; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.app.ActivityCompat; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.content.ContextCompat; import android.util.Log; import android.view.View; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; import com.google.zxing.Result; import org.json.JSONObject; import me.dm7.barcodescanner.zxing.ZXingScannerView; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, SearchActivityfrag.OnFragmentInteractionListener, MuseumDetailsFrag.OnFragmentInteractionListener,QRScannerFragment.OnFragmentInteractionListener, AudioTourFragment.OnFragmentInteractionListener, MapsFragment.OnFragmentInteractionListener{ private ZXingScannerView mScannerView; public final int REQUEST_PERMISSION_CAMERA=1; public final int REQUEST_PERMISSION_LOCATION=2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); //Get data from intents sent from fragments Bundle data1 = getIntent().getExtras(); if(data1 != null) { int activitytype = data1.getInt("ActivityType"); //If the intent came from MuseumDetails if(activitytype == 1) { //Gets the Museum object from the previous intent Museum mus = (Museum) data1.getParcelable("ITEM_EXTRA"); Bundle bundle = new Bundle(); //Puts the Museum object into the bundle for the next fragment bundle.putParcelable("message", mus); Fragment fragment = new MuseumDetailsFrag(); FragmentManager fragmentManager = getSupportFragmentManager(); fragment.setArguments(bundle); //Opens the next fragment fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();} //If the intent came from QRScanner else if(activitytype == 2){ Bundle b = new Bundle(); //puts the results of the QRScanner in the bundle for the next fragment String qrResult = data1.getString("STRING_EXTRA"); b.putString("qrResult",qrResult); Fragment fragment = new AudioTourFragment(); FragmentManager fragmentManager = getSupportFragmentManager(); fragment.setArguments(b); //Opens the next fragment fragmentManager.beginTransaction().replace(R.id.flContent,fragment).commit(); } else if(activitytype == 3){ int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION); if(permissionCheck == PackageManager.PERMISSION_GRANTED){Context context = getApplicationContext(); //Opens Maps fragment Bundle b = new Bundle(); Museum mus = data1.getParcelable("ITEM_EXTRA"); b.putParcelable("message",mus); Fragment fragment = new MapsFragment(); FragmentManager fragmentManager = getSupportFragmentManager(); fragment.setArguments(b); fragmentManager.beginTransaction().replace(R.id.flContent,fragment).commit(); } else{ //Asks for permissions ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_PERMISSION_LOCATION); } } } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_home) { Intent intent = new Intent(getApplicationContext(), MainActivity.class); startActivity(intent); // Handle the camera action } else if (id == R.id.nav_valetta) { Fragment fragment = new SearchActivityfrag(); FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.flContent,fragment).commit(); } else if (id == R.id.nav_northmalta) { Fragment fragment = new SearchActivityfrag(); FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.flContent,fragment).commit(); } else if (id == R.id.nav_southmalta) { Fragment fragment = new SearchActivityfrag(); FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.flContent,fragment).commit(); } else if (id == R.id.nav_gozo) { Fragment fragment = new SearchActivityfrag(); FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.flContent,fragment).commit(); } else if (id == R.id.nav_qrscanner) { //Stores permission status int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA); //Checks for permissions if(permissionCheck == PackageManager.PERMISSION_GRANTED){Context context = getApplicationContext(); //Opens QRScanner fragment Fragment fragment = new QRScannerFragment(); FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.flContent,fragment).commit(); } else{ //Asks for permissions ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CAMERA},REQUEST_PERMISSION_CAMERA); } } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case REQUEST_PERMISSION_CAMERA: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Context context = getApplicationContext(); Intent intent = new Intent(context, QRScannerFragment.class); startActivity(intent); } } case REQUEST_PERMISSION_LOCATION: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Bundle data1 = getIntent().getExtras(); Bundle b = new Bundle(); Museum mus = data1.getParcelable("ITEM_EXTRA"); b.putParcelable("MusMessage", mus); Fragment fragment = new MapsFragment(); FragmentManager fragmentManager = getSupportFragmentManager(); fragment.setArguments(b); fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit(); } } } } //Fragment Interaction Listeners @Override public void onSearchFragmentInteraction (Uri uri){ } @Override public void onMuseumDetailsFragmentInteraction (Uri uri){ } @Override public void onAudioTourFragmentInteraction (Uri uri){ } @Override public void onQRScannerFragmentInteraction (Uri uri){ } @Override public void onMapsFragmentInteraction (Uri uri){ } }
true
62afe6a3e7e4610ca45daa35aa18fccf2fbff035
Java
kindfei/zyf
/test-ee-web/src/main/java/test/servlet/TestMDBServlet.java
UTF-8
1,578
2.328125
2
[]
no_license
package test.servlet; import java.io.IOException; import javax.annotation.Resource; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.JMSException; import javax.jms.MessageProducer; import javax.jms.Queue; import javax.jms.Session; import javax.jms.TextMessage; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class TestMDB */ public class TestMDBServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public TestMDBServlet() { super(); // TODO Auto-generated constructor stub } @Resource(name="TestCF") private ConnectionFactory cf; @Resource(name="TestQueue") private Queue queue; protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { Connection conn = cf.createConnection(); Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(queue); for (int i = 0; i < 30; i++) { TextMessage msg = session.createTextMessage(); msg.setText(System.currentTimeMillis() + ": Hello MDB"); producer.send(msg); } producer.close(); session.close(); conn.close(); } catch (JMSException e) { e.printStackTrace(); } } }
true
aed233d322414d1a3079d7fce1f27a14e10ca03e
Java
solartcc/HwFrameWorkSource
/Mate20_9_0_0/src/main/java/java/util/stream/-$$Lambda$Collectors$oMCfAR-_eVSty8GsYzK5sec1Kag.java
UTF-8
650
2.125
2
[]
no_license
package java.util.stream; import java.util.DoubleSummaryStatistics; import java.util.function.BinaryOperator; /* compiled from: lambda */ public final /* synthetic */ class -$$Lambda$Collectors$oMCfAR-_eVSty8GsYzK5sec1Kag implements BinaryOperator { public static final /* synthetic */ -$$Lambda$Collectors$oMCfAR-_eVSty8GsYzK5sec1Kag INSTANCE = new -$$Lambda$Collectors$oMCfAR-_eVSty8GsYzK5sec1Kag(); private /* synthetic */ -$$Lambda$Collectors$oMCfAR-_eVSty8GsYzK5sec1Kag() { } public final Object apply(Object obj, Object obj2) { return ((DoubleSummaryStatistics) obj).combine((DoubleSummaryStatistics) obj2); } }
true
e5c599a65207d4831ce731a792fc47662ac08e12
Java
lchueca/foodiegram
/src/main/java/main/domain/resource/PublicacionResource.java
UTF-8
405
1.539063
2
[]
no_license
package main.domain.resource; import lombok.Data; import javax.annotation.Resource; import java.sql.Date; @Resource @Data public class PublicacionResource { private Integer id; private Integer iduser; private String text; private String image; private String ciudad; private String pais; private Date fecha; private String media; private Integer numerototalval; }
true
562f942ea92247a8c3f45a79ab85b84a293d6d5c
Java
kutariyar/haaprojects
/HaaProject_CGLIB/src/org/haaproject/cglib/demo/advice/AroundAdvice.java
UTF-8
700
2.9375
3
[]
no_license
/** * * Created Date: Jan 15, 2013 */ package org.haaproject.cglib.demo.advice; import java.lang.reflect.Method; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; /** * @author geln * @version 1.0 */ public class AroundAdvice implements MethodInterceptor { public Object intercept(Object target, Method method, Object[] args, MethodProxy proxy) throws Throwable { System.out.println("before method executing ..."); // 執行目標方法,并保存目標方法執行后的返回值 Object result = proxy.invokeSuper(target, args); System.out.println("after method executing ..."); return "result:" + result; } }
true
8542b551762ed653e0a574d9178a844dc531ba13
Java
RieMatsui/InventoryManagement
/src/java/fw/UserDataUtil.java
UTF-8
772
2.296875
2
[]
no_license
package fw; import javax.ejb.Stateless; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.servlet.http.HttpSession; /** * ユーザーデータを取得しデータを渡すためのクラス * @author RieMatsui */ @Stateless public class UserDataUtil { public String sessionUserName(){ String name = null; final FacesContext facesContext = FacesContext.getCurrentInstance(); final ExternalContext externalContext = facesContext.getExternalContext(); final HttpSession session = (HttpSession) externalContext.getSession(false); name = (String) session.getAttribute("sessionKey"); return name; } }
true
9c5f56a1195d8547cc27621f5bd675eb5b3fda3b
Java
kjwjw95/algorithm
/src/com/backjun/al/치킨배달.java
UTF-8
1,908
3.03125
3
[]
no_license
package com.backjun.al; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; public class 치킨배달 { static int N, M,Ans; static ArrayList<Integer[]> chiken; static ArrayList<Integer[]> house; static boolean[] selected; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); N = Integer.parseInt(st.nextToken()); M = Integer.parseInt(st.nextToken()); house = new ArrayList<Integer[]>(); chiken = new ArrayList<Integer[]>(); Ans=0; for (int i = 0; i < N; i++) { int tmp = 0; st = new StringTokenizer(br.readLine()); while (st.hasMoreTokens()) { int n = Integer.parseInt(st.nextToken()); if (n == 1) { Integer[] a = { i, tmp }; house.add(a); } else if (n == 2) { Integer[] a = { i, tmp }; chiken.add(a); } tmp++; } } selected = new boolean[chiken.size()]; Combination(0,0,0); System.out.println(Ans); } private static void Combination(int cnt,int idx,int flag) { if (cnt == M) { int sum=0; for(int i=0;i<house.size();i++) { int min=99999; for (int j = 0; j < chiken.size(); j++) { if(!selected[j]) continue; min=Math.min(min, Length(house.get(i), chiken.get(j))); } sum+=min; } if(Ans!=0) Ans=Math.min(Ans, sum); else Ans=sum; return; } for (int i = idx; i < chiken.size(); i++) { if ((flag&1<<i)!=0) continue; selected[i] = true; Combination(cnt + 1,i,flag|(1<<i)); selected[i] = false; } } private static int Length(Integer[] house, Integer[] chiken) { return Math.abs(chiken[0]-house[0])+Math.abs(chiken[1]-house[1]); } }
true
d395de8e8c7f51053ad3b19b7602b4b0ed9a8358
Java
muzammil-moosani/java-examples
/Override2.java
UTF-8
394
3.453125
3
[]
no_license
class A { int i,j; A(int a,int b) { i=a; j=b; } void show() { System.out.println("i and j: "+i+" "+j); } } class B extends A { int k; B(int a,int b,int c) { super(a,b); k=c; } void show(String msg) { System.out.println(msg + k); } } class Override2 { public static void main(String args[]) { B subob =new B(1,2,3); subob.show(); subob.show("This is k: "); } }
true
b720bd09f0bb09ceffc18dd72d10304fcbaf3332
Java
kappaj2/AJKPhotography
/Java Code/AJK Photography/src/java/za/co/ajk/struts/actions/PackageAction.java
UTF-8
3,585
2.34375
2
[]
no_license
/* * PackageAction.java * * Created on 14 March 2008, 02:07 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package za.co.ajk.struts.actions; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.beanutils.BeanUtils; import org.apache.log4j.Logger; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import za.co.ajk.persistance.transferobjects.ImageCategory; import za.co.ajk.persistance.transferobjects.Packages; import za.co.ajk.service.CategoryMaintenanceService; import za.co.ajk.service.PackagesMaintenanceService; import za.co.ajk.struts.forms.ImageForm; import za.co.ajk.struts.forms.PackageForm; /** * * @author akapp */ public class PackageAction extends BaseDispatchAction { private static Logger log = Logger.getLogger(PackageAction.class); private PackagesMaintenanceService packagesMaintenanceService = new PackagesMaintenanceService(); private CategoryMaintenanceService categoryMaintenanceService = new CategoryMaintenanceService(); /** * This method will retrieve a master list of all the packages defined. */ public ActionForward showAllPackageList(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { PackageForm packageForm = (PackageForm)form; List<Packages> packageList = packagesMaintenanceService.findAll(); packageForm.setPackageList(packageList); log.debug("Got a execute action request!!!"); return mapping.findForward("showPackageList"); } /** * This method will display the package detail recieved. * Because the categories are listed on top by default, it is possible that they have been cleared due to a navigation right down to * the last image display. An imageform reset would have cleared them. * This will cause a problem if the package detail is activated. Normal navigation, however, would not cause this. It is just * because of the back button on the browser. * */ public ActionForward showPackageDetail(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { log.debug("Got a showPackageDetail action request!!!"); PackageForm packageForm = (PackageForm)form; long packageId = Long.parseLong(request.getParameter("packageId")); log.debug("recieved packageId value of >"+packageId+"<"); Packages packages = packagesMaintenanceService.load(packageId); log.debug("Got package >"+packages.getPackageName()); BeanUtils.copyProperties(packageForm, packages); HttpSession session = request.getSession(); session.setAttribute("packageForm", packageForm); /* * Re-populate the imageList with the "root" categories. */ ImageForm imageForm = (ImageForm)session.getAttribute("imageForm"); List<ImageCategory> imageCategoryList = categoryMaintenanceService.findAll(); imageForm.setImageList(imageCategoryList); session.setAttribute("imageForm", imageForm); return mapping.findForward("showPackageDetail"); } }
true
9e5127681ea4fd0d9a51abc38db0cb19a55a76bf
Java
abrysov/mydreams_all_gits
/mydreams_all_gits/android_old-master/app/src/main/java/com/mydreams/android/service/models/DreamDto.java
UTF-8
503
2.15625
2
[]
no_license
package com.mydreams.android.service.models; import com.google.gson.annotations.SerializedName; public class DreamDto extends DreamInfoDto { @SerializedName("owner") private UserInfoDto owner; @SerializedName("isliked") private boolean isLiked; public UserInfoDto getOwner() { return owner; } public void setOwner(UserInfoDto owner) { this.owner = owner; } public boolean isLiked() { return isLiked; } public void setIsLiked(boolean isLiked) { this.isLiked = isLiked; } }
true
317a4e162fe85c87aadb1899322f4a3481497c1c
Java
yangyadong/lanqiao
/src/EatBanana/Main.java
GB18030
4,135
3.5
4
[]
no_license
/** A group of researchers are designing an experiment to test the IQ of a monkey. They will hang a banana at the roof of a building, and at the mean time, provide the monkey with some blocks. If the monkey is clever enough, it shall be able to reach the banana by placing one block on the top another to build a tower and climb up to get its favorite food. The researchers have n types of blocks, and an unlimited supply of blocks of each type. Each type-i block was a rectangular solid with linear dimensions (xi, yi, zi). A block could be reoriented so that any two of its three dimensions determined the dimensions of the base and the other dimension was the height. They want to make sure that the tallest tower possible by stacking blocks can reach the roof. The problem is that, in building a tower, one block could only be placed on top of another block as long as the two base dimensions of the upper block were both strictly smaller than the corresponding base dimensions of the lower block because there has to be some space for the monkey to step on. This meant, for example, that blocks oriented to have equal-sized bases couldn't be stacked. Your job is to write a program that determines the height of the tallest tower the monkey can build with a given set of blocks. The input file will contain one or more test cases. The first line of each test case contains an integer n, representing the number of different blocks in the following data set. The maximum value for n is 30. Each of the next n lines contains three integers representing the values xi, yi and zi. Input is terminated by a value of zero (0) for n. For each test case, print one line containing the case number (they are numbered sequentially starting from 1) and the height of the tallest possible tower in the format "Case case: maximum height = height". 1 10 20 30 2 6 8 10 5 5 5 7 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6 6 6 7 7 7 5 31 41 59 26 53 58 97 93 23 84 62 64 33 83 27 0 Case 1: maximum height = 40 Case 2: maximum height = 21 Case 3: maximum height = 28 Case 4: maximum height = 342 */ package EatBanana; import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; public class Main { public static void main(String[] args) { int n, x, y, z, m; Scanner scanner = new Scanner(System.in); n = scanner.nextInt(); int d = 1; while (n != 0) { int[][] num = new int[6 * n][3]; for (int i = 0; i < n; i++) { m = 6 * i; x = scanner.nextInt(); y = scanner.nextInt(); z = scanner.nextInt(); { num[m + 0][0] = x; num[m + 0][1] = y; num[m + 0][2] = z; } { num[m + 1][0] = x; num[m + 1][1] = z; num[m + 1][2] = y; } { num[m + 2][0] = y; num[m + 2][1] = x; num[m + 2][2] = z; } { num[m + 3][0] = y; num[m + 3][1] = z; num[m + 3][2] = x; } { num[m + 4][0] = z; num[m + 4][1] = y; num[m + 4][2] = x; } { num[m + 5][0] = z; num[m + 5][1] = x; num[m + 5][2] = y; } } Arrays.sort(num, new MyComprator()); // ʹָ // for (int i = 0; i < num.length; i++) { // System.out.println(num[i][0] + " " + num[i][1] + " " + num[i][2]); // } int sum = 0; int maxn = 0; int[] dp = new int[num.length]; for (int i = 0; i < num.length; i++) { dp[i] = num[i][2]; for (int j = i; j >= 0; j--) { if (num[j][0] > num[i][0] && num[j][1] > num[i][1]) { dp[i] = Math.max(dp[i], dp[j] + num[i][2]); } } if (dp[i] > maxn) { maxn = dp[i]; } } System.out.println("Case "+d+": maximum height = "+maxn); d++; n = scanner.nextInt(); } } // ȽxӴСxͬʱyӴС static class MyComprator implements Comparator { public int compare(Object o1, Object o2) { // TODO Auto-generated method stub int[] arg0 = (int[]) o1; int[] arg1 = (int[]) o2; if (arg0[0] != arg1[0]) return arg0[0] < arg1[0] ? 1 : -1; else return arg0[1] < arg1[1] ? 1 : -1; } } }
true
9f429caefb5279f3240329cb3266d94d7f8bcfb0
Java
Cellena/Jbmrus
/app/src/main/java/app/com/example/isuhar/jbmrus/data/CatalogProvider.java
UTF-8
14,618
2.28125
2
[]
no_license
package app.com.example.isuhar.jbmrus.data; /** * Created by iSuhar on 17.05.2015. */ import android.content.ContentProvider; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; public class CatalogProvider extends ContentProvider { // The URI Matcher used by this content provider. private static final UriMatcher sUriMatcher = buildUriMatcher(); private CatalogDbHelper mOpenHelper; static final int OFFERS = 100; static final int OFFERS_BY_CATEGORIES = 101; static final int CATEGORIES = 102; static final int ORDERS = 103; static final int OFFERS_AND_COUNT = 104; static final int ORDERS_DELETE = 105; static final int UPDATE = 106; private static final SQLiteQueryBuilder sOffersByCategoriesQueryBuilder; static { sOffersByCategoriesQueryBuilder = new SQLiteQueryBuilder(); sOffersByCategoriesQueryBuilder.setTables( CatalogContract.OffersEntry.TABLE_NAME + " INNER JOIN " + CatalogContract.CategoriesEntry.TABLE_NAME + " ON " + CatalogContract.OffersEntry.TABLE_NAME + "." + CatalogContract.OffersEntry.COLUMN_CAT_KEY + " = " + CatalogContract.CategoriesEntry.TABLE_NAME + "." + CatalogContract.CategoriesEntry._ID); } static UriMatcher buildUriMatcher() { final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH); final String authority = CatalogContract.CONTENT_AUTHORITY; matcher.addURI(authority, CatalogContract.PATH_UPDATE, UPDATE); matcher.addURI(authority, CatalogContract.PATH_OFFERS, OFFERS); matcher.addURI(authority, CatalogContract.PATH_OFFERS + "/*", OFFERS_BY_CATEGORIES); matcher.addURI(authority, CatalogContract.PATH_ORDER + "/#", ORDERS_DELETE); matcher.addURI(authority, CatalogContract.PATH_CATEGORIES, CATEGORIES); matcher.addURI(authority, CatalogContract.PATH_ORDER, ORDERS); matcher.addURI(authority, CatalogContract.PATH_CART, OFFERS_AND_COUNT); return matcher; } @Override public boolean onCreate() { mOpenHelper = new CatalogDbHelper(getContext()); return true; } @Override public String getType(Uri uri) { final int match = sUriMatcher.match(uri); switch (match) { case UPDATE: return CatalogContract.UpdateEntry.CONTENT_ITEM_TYPE; case ORDERS_DELETE: return CatalogContract.OrderEntry.CONTENT_ITEM_TYPE; case OFFERS_AND_COUNT: return CatalogContract.OffersEntry.CONTENT_TYPE; case OFFERS_BY_CATEGORIES: return CatalogContract.OffersEntry.CONTENT_TYPE; case OFFERS: return CatalogContract.OffersEntry.CONTENT_TYPE; case CATEGORIES: return CatalogContract.CategoriesEntry.CONTENT_TYPE; case ORDERS: return CatalogContract.OffersEntry.CONTENT_TYPE; default: throw new UnsupportedOperationException("Unknown uri: " + uri); } } private Cursor getOffersByCategories(Uri uri, String[] projection, String sortOrder, String[] selectionArgs) { String selection = CatalogContract.OffersEntry.TABLE_NAME + "." + CatalogContract.OffersEntry.COLUMN_CAT_KEY + " = ? "; return mOpenHelper.getReadableDatabase().query( CatalogContract.OffersEntry.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder ); } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { Cursor retCursor; switch (sUriMatcher.match(uri)) { case UPDATE: retCursor = mOpenHelper.getReadableDatabase().query( CatalogContract.UpdateEntry.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder ); break; case OFFERS_AND_COUNT: String mySelect = "SELECT " + CatalogContract.OffersEntry.TABLE_NAME + "." + CatalogContract.OffersEntry._ID + "," + CatalogContract.OffersEntry.COLUMN_OFFER_NAME + "," + CatalogContract.OffersEntry.COLUMN_OFFER_PRICE + "," + " count(" + CatalogContract.OrderEntry.TABLE_NAME + "." + CatalogContract.OrderEntry._ID + ") as " + CatalogContract.OffersEntry.COUNT_OFFERS +", "+ CatalogContract.OffersEntry.COLUMN_OFFER_IMG + " FROM " + CatalogContract.OffersEntry.TABLE_NAME + " INNER JOIN " + CatalogContract.OrderEntry.TABLE_NAME + " ON " + CatalogContract.OrderEntry.TABLE_NAME + "." + CatalogContract.OrderEntry.COLUMN_ORDER_OFFER_ID + " = " + CatalogContract.OffersEntry.TABLE_NAME + "." + CatalogContract.OffersEntry._ID + " GROUP BY " + CatalogContract.OffersEntry.TABLE_NAME + "." + CatalogContract.OffersEntry.COLUMN_OFFER_NAME + ";"; retCursor = mOpenHelper.getReadableDatabase().rawQuery(mySelect, null); break; case OFFERS_BY_CATEGORIES: { retCursor = getOffersByCategories(uri, projection, sortOrder, selectionArgs); break; } case OFFERS: { retCursor = mOpenHelper.getReadableDatabase().query( CatalogContract.OffersEntry.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder ); break; } case CATEGORIES: { retCursor = mOpenHelper.getReadableDatabase().query( CatalogContract.CategoriesEntry.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder ); break; } case ORDERS: { retCursor = mOpenHelper.getReadableDatabase().query( CatalogContract.OrderEntry.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder ); break; } default: throw new UnsupportedOperationException("Unknown uri: " + uri); } retCursor.setNotificationUri(getContext().getContentResolver(), uri); return retCursor; } @Override public Uri insert(Uri uri, ContentValues values) { final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final int match = sUriMatcher.match(uri); Uri returnUri; switch (match) { case UPDATE: { long _id = db.insert(CatalogContract.UpdateEntry.TABLE_NAME, null, values); if (_id > 0) returnUri = CatalogContract.UpdateEntry.buildUpdateUri(_id); else throw new android.database.SQLException("Failed to insert row into " + uri); break; } case OFFERS: { long _id = db.insert(CatalogContract.OffersEntry.TABLE_NAME, null, values); if (_id > 0) returnUri = CatalogContract.OffersEntry.buildOffersUri(_id); else throw new android.database.SQLException("Failed to insert row into " + uri); break; } case ORDERS: { long _id = db.insert(CatalogContract.OrderEntry.TABLE_NAME, null, values); if (_id > 0) returnUri = CatalogContract.OrderEntry.buildOrdersUri(_id); else throw new android.database.SQLException("Failed to insert row into " + uri); break; } case CATEGORIES: { long _id = db.insert(CatalogContract.CategoriesEntry.TABLE_NAME, null, values); if (_id > 0) { returnUri = CatalogContract.CategoriesEntry.buildCategoriesUri(_id); } else throw new android.database.SQLException("Failed to insert row into " + uri); break; } default: throw new UnsupportedOperationException("Unknown uri: " + uri); } getContext().getContentResolver().notifyChange(uri, null); return returnUri; } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { // Student: Start by getting a writable database final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final int match = sUriMatcher.match(uri); int rowsDeleted; if (null == selection) { selection = "1"; } switch (match) { case UPDATE: rowsDeleted = db.delete(CatalogContract.UpdateEntry.TABLE_NAME, selection, selectionArgs); break; case ORDERS_DELETE: final String DELETE_ROW = "delete from " + CatalogContract.OrderEntry.TABLE_NAME + " where _id in " + "(select _id from " + CatalogContract.OrderEntry.TABLE_NAME + " where " + CatalogContract.OrderEntry.COLUMN_ORDER_OFFER_ID + " = " + selectionArgs[0] + " order by _id limit 1)"; db.execSQL(DELETE_ROW); rowsDeleted = 1; break; case OFFERS: rowsDeleted = db.delete(CatalogContract.OffersEntry.TABLE_NAME, selection, selectionArgs); break; case ORDERS: rowsDeleted = db.delete(CatalogContract.OrderEntry.TABLE_NAME, selection, selectionArgs); break; case CATEGORIES: rowsDeleted = db.delete(CatalogContract.CategoriesEntry.TABLE_NAME, selection, selectionArgs); break; default: throw new UnsupportedOperationException("Unknown uri: " + uri); } if (rowsDeleted != 0) { getContext().getContentResolver().notifyChange(uri, null); } // Student: return the actual rows deleted return rowsDeleted; } @Override public int update( Uri uri, ContentValues values, String selection, String[] selectionArgs) { // Student: Start by getting a writable database final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final int match = sUriMatcher.match(uri); int rowsUpdated; switch (match) { case OFFERS: rowsUpdated = db.update(CatalogContract.OffersEntry.TABLE_NAME, values, selection, selectionArgs); break; case ORDERS: rowsUpdated = db.update(CatalogContract.OrderEntry.TABLE_NAME, values, selection, selectionArgs); break; case CATEGORIES: rowsUpdated = db.update(CatalogContract.CategoriesEntry.TABLE_NAME, values, selection, selectionArgs); break; default: throw new UnsupportedOperationException("Unknown uri: " + uri); } if (rowsUpdated != 0) { getContext().getContentResolver().notifyChange(uri, null); } // Student: return the actual rows deleted return rowsUpdated; } @Override public int bulkInsert(Uri uri, ContentValues[] values) { final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final int match = sUriMatcher.match(uri); int returnCount = 0; switch (match) { case OFFERS: db.beginTransaction(); try { for (ContentValues value : values) { long _id = db.insert(CatalogContract.OffersEntry.TABLE_NAME, null, value); if (_id != -1) { returnCount++; } } db.setTransactionSuccessful(); } finally { db.endTransaction(); } getContext().getContentResolver().notifyChange(uri, null); return returnCount; case ORDERS: db.beginTransaction(); try { for (ContentValues value : values) { long _id = db.insert(CatalogContract.OrderEntry.TABLE_NAME, null, value); if (_id != -1) { returnCount++; } } db.setTransactionSuccessful(); } finally { db.endTransaction(); } getContext().getContentResolver().notifyChange(uri, null); return returnCount; case CATEGORIES: db.beginTransaction(); try { for (ContentValues value : values) { long _id = db.insert(CatalogContract.CategoriesEntry.TABLE_NAME, null, value); if (_id != -1) { returnCount++; } } db.setTransactionSuccessful(); } finally { db.endTransaction(); } getContext().getContentResolver().notifyChange(uri, null); return returnCount; default: return super.bulkInsert(uri, values); } } }
true
ecc5b0d890696c682c249ed65e7395349b4f0573
Java
wgcisotto/erserver-unittesting-legacycode
/src/test/java/erserver/modules/hardunderstand/EmergencyResponseDouble.java
UTF-8
397
1.828125
2
[]
no_license
package erserver.modules.hardunderstand; import erserver.modules.dependencies.EmergencyResponseProvider; import erserver.modules.dependencies.Priority; public class EmergencyResponseDouble implements EmergencyResponseProvider { @Override public void requestInboundDiversion(Priority priority) { } @Override public void removeInboundDiversion(Priority priority) { } }
true
ad97e91026ff081d16f5b47e193a8c1f4571eec5
Java
aKimtsPro/Java
/src/poo/lambda/LancableIntensite.java
UTF-8
92
1.984375
2
[]
no_license
package poo.lambda; public interface LancableIntensite { int lancer(int intensite); }
true
753665cde37c9fa865a8a3aefb20b1763bbf25d9
Java
sbhornjr/animator-application-ext
/src/cs3500/animator/model/misc/MyColor.java
UTF-8
960
3.984375
4
[]
no_license
package cs3500.animator.model.misc; import java.awt.Color; /** * A version of Java's Color that prints better. */ public class MyColor extends Color { /** * Constructs a cs3500.animator.model.misc.MyColor object. * * @param r The amount of red in the color * @param g The amount of green in the color * @param b The amount of blue in the color */ public MyColor(float r, float g, float b) { super(r, g, b); } @Override public String toString() { float[] rgb = this.getRGBColorComponents(new float[3]); return "(" + rgb[0] + "," + rgb[1] + "," + rgb[2] + ")"; } /** * Converts this color's rgb values to ints instead of floats and returns it as a string. * * @return The color as a string. */ public String asInt() { float[] rgb = this.getRGBColorComponents(new float[3]); return "(" + (int)(rgb[0] * 255) + "," + (int)(rgb[1] * 255) + "," + (int)(rgb[2] * 255) + ")"; } }
true
1f493164c0f2318c0ec354a688195089ec713b6e
Java
rui099/AI_Algoritmo_Genetico_Java
/src/main/Exceptions/XYNotFoundException.java
UTF-8
616
2.109375
2
[]
no_license
package main.Exceptions; /** * * @author ruidu */ public class XYNotFoundException extends Exception { public XYNotFoundException() { } public XYNotFoundException(String message) { super(message); } public XYNotFoundException(String message, Throwable cause) { super(message, cause); } public XYNotFoundException(Throwable cause) { super(cause); } public XYNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
true
eccc8e9d258dac03e0ca6d19f6e565b192e84486
Java
thoslin/ELF
/client/plugins/elf.client.compliance.management/src/main/java/elf/client/compliance/management/views/securitypool/dialog/RemoveComposite.java
GB18030
2,496
2.390625
2
[ "BSD-3-Clause" ]
permissive
package elf.client.compliance.management.views.securitypool.dialog; import java.util.Collections; import java.util.LinkedList; import java.util.List; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Composite; import elf.api.compliance.command.securitypool.SecurityPoolRemoveResult; import elf.client.framework.controller.compliance.SecurityPoolQueryController; import elf.client.framework.controller.compliance.SecurityPoolSetController; import elf.client.framework.model.compliance.SecurityPoolBaseModel; import elf.client.framework.widgets.ComboCheckedWidget; import elf.client.framework.widgets.dialog.ExecutionComposite; import elf.client.framework.widgets.dialog.ExecutionDialog; public class RemoveComposite extends ExecutionComposite { private ComboCheckedWidget securityPoolIdCombo; public RemoveComposite(Composite parent, Object initValue) { super(parent, initValue); } @Override protected void createContent(Composite parent) { securityPoolIdCombo = new ComboCheckedWidget(parent, "ά"); } @Override protected void initialize(Object initValue) { securityPoolIdCombo.initWidget(SecurityPoolQueryController.queryAllPools()); } @Override public Point getInitialSize() { return new Point(400, 200); } @Override protected void execute() throws Exception { List<SecurityPoolBaseModel> securityPools = securityPoolIdCombo.getListData(); if (securityPools.isEmpty()) { throw new Exception("ѡҪɾάȣ"); } boolean delete = MessageDialog.openConfirm(getShell(), getShell().getText(), "ȷҪɾѡά"); if (false == delete) { return; } List<String> securityPoolIds = getSecurityPoolIds(securityPools); List<SecurityPoolRemoveResult> results = SecurityPoolSetController.remove(securityPoolIds); ExecutionDialog executionDialog = new SingleButtonExecutionDialog(getShell(), "ɾ", "ɾ", SecurityPoolResultComposite.class, results); executionDialog.open(); } private List<String> getSecurityPoolIds(List<SecurityPoolBaseModel> securityPools) { if (securityPools == null) { return Collections.emptyList(); } List<String> result = new LinkedList<String>(); for (SecurityPoolBaseModel securityPoolQueryBaseResult : securityPools) { result.add(securityPoolQueryBaseResult.getSecurityPoolId()); } return result; } }
true
dfedb9c6803ddb723e3d2e5e6e9d1cb00d5b81c2
Java
marco-ruiz/grid-wizard-enterprise
/src/main/java/org/gwe/app/daemon/domain/MonitorDomain.java
UTF-8
3,351
2.171875
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2007-2008 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gwe.app.daemon.domain; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.gwe.api.event.Event; import org.gwe.api.event.EventFilter; import org.gwe.persistence.model.BaseModelInfo; import org.gwe.persistence.model.EventType; import org.gwe.persistence.model.IEventLogger; import org.gwe.utils.concurrent.BlockingList; /** * * @author Marco Ruiz * @since Oct 4, 2007 */ public class MonitorDomain extends BaseDomain implements Runnable, IEventLogger { private static final long MAXIMUM_BLOCKING_PERIOD = 10000; private Map<Long, UserEventNotifier> notifiers = new HashMap<Long, UserEventNotifier>(); private BlockingList<Event> events = new BlockingList<Event>(); public <KEY_TYPE> Timestamp logEvent(BaseModelInfo<KEY_TYPE> source, EventType evType, Timestamp when, BaseModelInfo... relatedModels) { events.add(new Event(evType, source, relatedModels)); return when; } public long createHandle() { // TODO: Create a stronger unique handle for monitoring return System.currentTimeMillis(); } public List<Event> getNextEvents(long handle, EventFilter filter) { return getUserEventNotifier(handle).getNextEvents(); } private UserEventNotifier getUserEventNotifier(long handle) { synchronized (notifiers) { UserEventNotifier notif = notifiers.get(handle); if (notif == null) { notif = new UserEventNotifier(handle); notifiers.put(handle, notif); } return notif; } } public void disposeNotifier(long handle) { synchronized (notifiers) { notifiers.remove(handle); } } public void run() { List<Event> eventsCopy; while (true) { eventsCopy = events.takeAll(); if (!eventsCopy.isEmpty()) { Collection<UserEventNotifier> notifiersCopy; synchronized (notifiers) { notifiersCopy = notifiers.values(); } for (UserEventNotifier notif : notifiersCopy) notif.postEvents(eventsCopy); } } } class UserEventNotifier { private Long monitoringHandle; private List<Event> userEvents = new ArrayList<Event>(); private UserEventNotifier(long monitoringHandle) { this.monitoringHandle = monitoringHandle; } private List<Event> getNextEvents() { List<Event> result = new ArrayList<Event>(); synchronized (monitoringHandle) { while (userEvents.isEmpty()) try { monitoringHandle.wait(MAXIMUM_BLOCKING_PERIOD); } catch (InterruptedException e) {} result.addAll(userEvents); userEvents.clear(); } return result; } private void postEvents(List<Event> events) { synchronized (monitoringHandle) { userEvents.addAll(events); monitoringHandle.notify(); } } } }
true
6337b4c929201d98dc52d1ef3542e387b9f162b2
Java
fengyajie/ShiroTest
/src/main/java/com/fyj/redis/RedisCacheConfigure.java
UTF-8
2,931
2.484375
2
[]
no_license
package com.fyj.redis; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; public class RedisCacheConfigure implements InitializingBean { private static Logger logger = LoggerFactory.getLogger(RedisCacheConfigure.class); //redis服务器ip private String addr; //redis端口号 private int port; //访问密码 private String auth; //可用链接实例的最大数目,默认值为8 //如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则表示此时pool的状态为耗尽 private int maxActive; //控制一个pool最多有多少个状态为idle(空闲)的jedis实例,默认也是8 private int maxIdle; //等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException private int maxWait; private int timeOut; //在borrow一个jedis实例时,是否提前进行validate操作;如果是true,则得到的jedis实例均是可用的 private boolean testOnBorrow; public Jedis jedis; public JedisPool jedisPool; private void initialPool() { //池基本配置 JedisPoolConfig config = new JedisPoolConfig(); config.setMaxTotal(maxActive); config.setMaxIdle(maxIdle); config.setMaxWaitMillis(maxWait); config.setTestOnBorrow(testOnBorrow); new JedisPool(config,addr,port,timeOut,auth); } public void afterPropertiesSet() throws Exception { initialPool(); jedis = jedisPool.getResource(); } public JedisPool getJedisPool() { return jedisPool; } public void close(Jedis jedis) { jedisPool.returnResource(jedis); } public void cloaeEx(Jedis jedis) { jedisPool.returnBrokenResource(jedis); } public String getAddr() { return addr; } public void setAddr(String addr) { this.addr = addr; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public String getAuth() { return auth; } public void setAuth(String auth) { this.auth = auth; } public int getMaxActive() { return maxActive; } public void setMaxActive(int maxActive) { this.maxActive = maxActive; } public int getMaxIdle() { return maxIdle; } public void setMaxIdle(int maxIdle) { this.maxIdle = maxIdle; } public int getMaxWait() { return maxWait; } public void setMaxWait(int maxWait) { this.maxWait = maxWait; } public int getTimeOut() { return timeOut; } public void setTimeOut(int timeOut) { this.timeOut = timeOut; } public boolean isTestOnBorrow() { return testOnBorrow; } public void setTestOnBorrow(boolean testOnBorrow) { this.testOnBorrow = testOnBorrow; } }
true
99f70e46647ca4097503ad7e6a28bf4f7518bf5f
Java
LorenBaker/DiveLog
/app/src/main/java/com/lbconsulting/divelogfirebase/reefGuide/ReefGuideWebPageReader.java
UTF-8
3,446
2.296875
2
[]
no_license
package com.lbconsulting.divelogfirebase.reefGuide; import android.app.ProgressDialog; import android.content.Context; import android.os.AsyncTask; import android.support.annotation.NonNull; import com.lbconsulting.divelogfirebase.models.ReefGuide; import com.lbconsulting.divelogfirebase.models.ReefGuideItem; import com.lbconsulting.divelogfirebase.utils.MyMethods; import java.util.ArrayList; import java.util.Locale; import timber.log.Timber; /** * Created by Loren on 2/5/2017. */ public class ReefGuideWebPageReader extends AsyncTask<Void, String, Void> { private Context context; private ArrayList<ReefGuide> mReefGuides; private String mReefGuideTitle; private int mReefGuideId; private ProgressDialog progressDialog; private int mNumberOfImages; public ReefGuideWebPageReader(@NonNull Context context, int reefGuideId, @NonNull String reefGuideTitle, @NonNull ArrayList<ReefGuide> reefGuides) { this.context = context; this.mReefGuideId = reefGuideId; this.mReefGuideTitle = reefGuideTitle; this.mReefGuides = reefGuides; progressDialog = new ProgressDialog(context); progressDialog.setMessage("Loading: "); } @Override protected void onPreExecute() { Timber.i("onPreExecute()"); mNumberOfImages = 0; progressDialog.show(); super.onPreExecute(); } @Override protected void onProgressUpdate(String... values) { String loadingMessage = "Loading: " + values[0]; progressDialog.setMessage(loadingMessage); } @Override protected Void doInBackground(Void... params) { ReefGuideItem.removeAllReefGuideItems(mReefGuideId, mReefGuideTitle); retrieveReefGuideItems(mReefGuideId, mReefGuideTitle, mReefGuides); return null; } private void retrieveReefGuideItems(int reefGuideId, String reefGuideTitle, ArrayList<ReefGuide> reefGuides) { Timber.i("retrieveReefGuideItems() for guide: %s", reefGuideTitle); for (ReefGuide reefGuide : reefGuides) { publishProgress(reefGuide.getSummaryPageUid()); RetrieveReefGuideDetailUrls retrieveReefGuideDetailUrls = new RetrieveReefGuideDetailUrls(reefGuideId,reefGuide.getSummaryPageUrl()); ArrayList<ThumbnailAndUrl> reefGuideDetailUrls = retrieveReefGuideDetailUrls.fetch(); for (ThumbnailAndUrl thumbnailAndUrl : reefGuideDetailUrls) { RetrieveReefGuideDetail retrieveReefGuideDetail = new RetrieveReefGuideDetail( thumbnailAndUrl, reefGuide.getSummaryPageUid()); ReefGuideItem reefGuideItem = retrieveReefGuideDetail.fetch(); mNumberOfImages++; reefGuideItem.setSortOrder(mNumberOfImages); ReefGuideItem.save(reefGuideId, reefGuide.getSummaryPageUid(), reefGuideItem); } } } @Override protected void onPostExecute(Void aVoid) { String title = "Refresh Reef Guide Complete"; String msg = String.format(Locale.getDefault(), mReefGuideTitle+":\nRetrieved %d reef guides and %d images", mReefGuides.size(), mNumberOfImages); Timber.i("onPostExecute() " + msg); MyMethods.showOkDialog(context, title, msg); progressDialog.dismiss(); } }
true
bf83c8a0e629669b5ab1907d43a39366cdc57d9e
Java
userzxl/gsm
/src/main/java/org/zxl/model/Stock.java
UTF-8
1,624
2.265625
2
[]
no_license
package org.zxl.model; import java.util.Date; public class Stock { private String id; private String name; private Date createDate; private String delFlag; private String unit; private Date updateDate; private String quantity; private String type;//1:入库 0:出库 public String getType() { return type; } public void setType(String type) { this.type = type; } public Stock() { } public String getId() { return id; } public void setId(String id) { this.id = id == null ? null : id.trim(); } public String getName() { return name; } public void setName(String name) { this.name = name == null ? null : name.trim(); } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public String getDelFlag() { return delFlag; } public void setDelFlag(String delFlag) { this.delFlag = delFlag == null ? null : delFlag.trim(); } public String getUnit() { return unit; } public void setUnit(String unit) { this.unit = unit == null ? null : unit.trim(); } public Date getUpdateDate() { return updateDate; } public void setUpdateDate(Date updateDate) { this.updateDate = updateDate; } public String getQuantity() { return quantity; } public void setQuantity(String quantity) { this.quantity = quantity == null ? null : quantity.trim(); } }
true
938dc7f47e953365b0684e0010a2f03e0b3e76d0
Java
haseeAmarathunga/DesignPatterns
/src/com/factory/FactoryPatternDemo.java
UTF-8
322
2.953125
3
[]
no_license
package com.factory; public class FactoryPatternDemo { public static void main(String[] args) { ShapeFactory sp=new ShapeFactory(); Shape shape1=sp.getShape("Circle"); shape1.draw(); Shape shape2=sp.getShape("Rectangle"); shape2.draw(); Shape shape3=sp.getShape("Square"); shape3.draw(); } }
true
7afc2c27dcbcdee33e7779a7412e29db153f074b
Java
jasondlee/Meetspace
/plugin-engine/src/main/java/com/steeplesoft/meetspace/plugins/PluginMetadata.java
UTF-8
807
2.328125
2
[]
no_license
package com.steeplesoft.meetspace.plugins; import java.util.List; /** * Created by IntelliJ IDEA. * User: jasonlee * Date: Feb 12, 2010 * Time: 3:55:15 PM * To change this template use File | Settings | File Templates. */ public class PluginMetadata { protected String name; protected String type; protected String description; public PluginMetadata(Object plugin) { this(plugin.getClass()); } public PluginMetadata(Class<?> c) { Plugin p = c.getAnnotation(Plugin.class); type = p.type(); name = p.name(); description = p.description(); } public String getName() { return name; } public String getType() { return type; } public String getDescription() { return description; } }
true
45c911a3dc90c13f06840c80e247ea866efd74aa
Java
Sowmiya2497/exam
/WEB-INF/classes/studentdao.java
UTF-8
3,564
2.34375
2
[]
no_license
import bean.student; import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.sql.ResultSet; import java.sql.PreparedStatement; public class studentdao { public int checkId(String id) { final String Driver = "com.mysql.jdbc.Driver"; final String DBUrl = "jdbc:mysql://localhost:3306/TEST"; final String USER = "root"; final String pass = "sowmiya"; int flag = 0; try{ Class.forName(Driver); Connection conn = DriverManager.getConnection(DBUrl,USER,pass); Statement stmt = conn.createStatement(); String query = "SELECT * FROM student WHERE id=\""+id+"\";"; ResultSet rs = stmt.executeQuery(query); if(rs.next()) { flag = 0; } else { flag = 1; } conn.close(); } catch(Exception e) { System.out.println(e); } return flag; } public void insertStudent(student s) { String id = s.getId(); String name = s.getName(); String email = s.getEmail(); int score = s.getScore(); final String Driver = "com.mysql.jdbc.Driver"; final String DBUrl = "jdbc:mysql://localhost:3306/TEST"; final String USER = "root"; final String pass = "sowmiya"; try{ Class.forName(Driver); Connection conn = DriverManager.getConnection(DBUrl,USER,pass); Statement stmt = conn.createStatement(); String query = "INSERT INTO student(id,name,email,score) values(?,?,?,?)"; PreparedStatement ps = conn.prepareStatement(query); ps.setString(1,id); ps.setString(2,name); ps.setString(3,email); ps.setInt(4,score); ps.execute(); conn.close(); } catch(Exception e) { System.out.println(e); } } public void updateScore(String id,int result) { final String Driver = "com.mysql.jdbc.Driver"; final String DBUrl = "jdbc:mysql://localhost:3306/TEST"; final String USER = "root"; final String pass = "sowmiya"; try{ Class.forName(Driver); Connection conn = DriverManager.getConnection(DBUrl,USER,pass); Statement stmt = conn.createStatement(); //String sql = "UPDATE student SET score="+result+" WHERE id = \""+id+"\";"; String sql = "UPDATE student set score = ? where id = ?"; PreparedStatement ps = conn.prepareStatement(sql); ps.setInt(1,result); ps.setString(2,id); //stmt.executeQuery(sql); ps.execute(); } catch(Exception e) { System.out.println(e); } } /*public int checkSubmission(String id) { final String Driver = "com.mysql.jdbc.Driver"; final String DBUrl = "jdbc:mysql://localhost:3306/TEST"; final String USER = "root"; final String pass = "sowmiya"; int flag = 0; try{ Class.forName(Driver); Connection conn = DriverManager.getConnection(DBUrl,USER,pass); Statement stmt = conn.createStatement(); String query = "SELECT has_sub FROM student WHERE id=\""+id+"\";"; ResultSet rs = stmt.executeQuery(query); if(rs.next()) { if((rs.getString(1)).contentEquals("submitted")) flag = 1; else flag = 0; } conn.close(); } catch(Exception e) { System.out.println(e); } return flag; }*/ }
true
70cacd4b79640163091cad881b37def897ee5297
Java
tarikbzyk/sabah
/sabah/src/main/java/pageObjects/anasayfa/Manset.java
UTF-8
973
2.203125
2
[]
no_license
package pageObjects.anasayfa; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import java.util.List; public class Manset { public WebDriver driver; By Manset20li = By.xpath("//section[@class='homeContent contentFrame']/div/div[4]/div[1]/div/div/ul/ul/li/a"); By MansetYanı4lu = By.xpath("//section[@class='homeContent contentFrame']/div/div[4]/div[2]/div/div/figure/a"); By MansetAltı5li = By.xpath("//section[@class='homeContent contentFrame']/div/div[5]/div/div/ul/li/figure/a"); public Manset(WebDriver driver){ this.driver=driver; } public List<WebElement> getManset20liList(){ return driver.findElements(Manset20li); } public List<WebElement> getMansetyanı4luList(){ return driver.findElements(MansetYanı4lu); } public List<WebElement> getMansetAlti5liList(){ return driver.findElements(MansetAltı5li); } }
true
8d317247c102a2bcae1304bbfde06eb3d6b2a3ca
Java
Rufusmen/ONP
/src/symbole/Przypisanie.java
UTF-8
866
3.015625
3
[]
no_license
package symbole; import narzedzia.Stos; import wyjatki.ONP_BladZmiennej; import wyjatki.WyjatekONP; /** * Klasa przypisania */ public class Przypisanie extends Symbol { public static void przypisz(Stos<Symbol> stos) throws WyjatekONP { Symbol s1 = stos.getBack(); stos.popBack(); Symbol s2 = stos.getBack(); stos.popBack(); if(s2 instanceof Zmienna){ ((Zmienna)s2).ustaw(s1.obliczWartosc()); stos.pushBack(new Liczba(s1.obliczWartosc())); } else if (s1 instanceof Zmienna){ ((Zmienna)s1).ustaw(s2.obliczWartosc()); stos.pushBack(new Liczba(s2.obliczWartosc())); } else throw new ONP_BladZmiennej(); } @Override public double obliczWartosc() throws WyjatekONP { throw new UnsupportedOperationException(""); } }
true
cc9cdf0247cf4a7020db192270124349a194dcb2
Java
sogo911/algorithm
/src/com/bit/loop/BmiFor.java
UTF-8
1,477
3.53125
4
[]
no_license
package com.bit.loop; /* BMI 지수 고도 비만 : 35 이상 중등도 비만 (2단계 비만) : 30 - 35 경도 비만 (1단계 비만) : 25 - 30 과체중 : 23 - 24.9 정상 : 18.5 - 22.9 저체중 : 18.5 미만 */ import java.util.Scanner; public class BmiFor { public static void main(String[] args) { Scanner a = new Scanner(System.in); String res = ""; int d = 0; System.out.println("측정하실 인원을 입력하세요."); d = a.nextInt(); for(int i = 0; i < d; i++) { Scanner s = new Scanner(System.in); double h = 0, w = 0, b = 0; String name = "", bmi = ""; System.out.println("이름을 입력해주세요."); name = s.next(); System.out.println(name+"님의 키를 M(미터) 단위로 입력하세요."); h = s.nextDouble(); System.out.println(name+"님의 몸무게 kg 단위로 입력하세요."); w = s.nextDouble(); b = w / (h * h); if(b >= 35) { bmi = "고도비만 입니다."; }else if(b >= 30 && b < 35) { bmi = "중등도 비만(2단계 비만) 입니다."; }else if(b >= 25 && b < 30) { bmi = "경도 비만(1단계 비만) 입니다."; }else if(b >= 23 && b <= 24.9) { bmi = "과체중 입니다."; }else if(b >= 18.5 && b <= 22.9) { bmi = "정상 입니다."; }else if(b < 18.5) { bmi = "저체중 입니다."; }else { bmi = "다시 입력해주세요."; } res += String.format("%s님의 상태는 %s \n",name,bmi); } System.out.print(res); } }
true
ef023329eb854788abddac56047d1c8d75f70194
Java
amirnaveh/ToDoListManager
/app/src/main/java/il/ac/huji/todolist/AddNewTodoItemActivity.java
UTF-8
3,763
2.9375
3
[]
no_license
package il.ac.huji.todolist; import android.app.Activity; import android.app.AlertDialog; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.TextView; import java.util.Calendar; import java.util.Date; import static il.ac.huji.todolist.Constants.FIRST_COLUMN; import static il.ac.huji.todolist.Constants.NO_DATE_IDENTIFIER; import static il.ac.huji.todolist.Constants.SECOND_COLUMN; /** * This class is an activity dialog for adding a new task to the To-Do List */ public class AddNewTodoItemActivity extends Activity implements OnClickListener { EditText txt; DatePicker datePicker; Button ok; Button cancel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(il.ac.huji.todolist.R.layout.activity_add_new_todo_item); txt = (EditText) findViewById(R.id.edtNewItem); datePicker = (DatePicker) findViewById(R.id.datePicker); ok = (Button) findViewById(R.id.btnOK); cancel = (Button) findViewById(R.id.btnCancel); datePicker.setCalendarViewShown(false); ok.setOnClickListener(this); cancel.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnOK: // Add the new task using intent extras Intent intent = getIntent(); Bundle extras = new Bundle(); String task = txt.getText().toString(); if (verifyTaskText(task)) { extras.putString(FIRST_COLUMN, task); } else { break; } Date date = getDateFromDatePicker(); if (date == null) { extras.putLong(SECOND_COLUMN, NO_DATE_IDENTIFIER); } else { extras.putLong(SECOND_COLUMN, date.getTime()); } intent.putExtras(extras); setResult(Activity.RESULT_OK, intent); this.finish(); case R.id.btnCancel: // return with no action setResult(Activity.RESULT_CANCELED); this.finish(); default: setResult(Activity.RESULT_CANCELED); this.finish(); } } /** * Verifies that the task text is not null (empty). In case it is, it also invokes a dialog * * @param text - the task text * @return true if the text is valid, false if null */ private boolean verifyTaskText(String text) { AlertDialog.Builder builder = new AlertDialog.Builder(this); if (text.isEmpty()) { builder.setTitle("Error"); builder.setMessage("Can't add an empty task"); final TextView errorText = new TextView(this); builder.setView(errorText); builder.setNeutralButton("Ok", null); builder.create().show(); return false; } else { return true; } } /** * Extracts the date chosen by the user from the DatePicker * * @return the date in form of java.util.Date */ private Date getDateFromDatePicker() { if (datePicker == null) { return null; } int day = datePicker.getDayOfMonth(); int month = datePicker.getMonth(); int year = datePicker.getYear(); Calendar calendar = Calendar.getInstance(); calendar.set(year, month, day); return calendar.getTime(); } }
true
b5c2424b67cc0e5e3b5ace4140b555163a0e2580
Java
nunotoriz/hale
/io/plugins/eu.esdihumboldt.hale.io.oml/src/eu/esdihumboldt/hale/io/oml/internal/model/generated/oml/OnAttributeType.java
UTF-8
3,265
1.789063
2
[]
no_license
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-558 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2012.09.14 at 10:27:20 AM CEST // package eu.esdihumboldt.hale.io.oml.internal.model.generated.oml; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for onAttributeType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="onAttributeType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;choice> * &lt;element ref="{http://www.omwg.org/TR/d7/ontology/alignment}Property"/> * &lt;element ref="{http://www.omwg.org/TR/d7/ontology/alignment}Relation"/> * &lt;/choice> * &lt;attribute ref="{http://www.w3.org/1999/02/22-rdf-syntax-ns#}about"/> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "onAttributeType", propOrder = { "property", "relation" }) public class OnAttributeType { @XmlElement(name = "Property") protected PropertyType property; @XmlElement(name = "Relation") protected RelationType relation; @XmlAttribute(namespace = "http://www.w3.org/1999/02/22-rdf-syntax-ns#") @XmlSchemaType(name = "anyURI") protected String about; /** * Gets the value of the property property. * * @return * possible object is * {@link PropertyType } * */ public PropertyType getProperty() { return property; } /** * Sets the value of the property property. * * @param value * allowed object is * {@link PropertyType } * */ public void setProperty(PropertyType value) { this.property = value; } /** * Gets the value of the relation property. * * @return * possible object is * {@link RelationType } * */ public RelationType getRelation() { return relation; } /** * Sets the value of the relation property. * * @param value * allowed object is * {@link RelationType } * */ public void setRelation(RelationType value) { this.relation = value; } /** * Gets the value of the about property. * * @return * possible object is * {@link String } * */ public String getAbout() { return about; } /** * Sets the value of the about property. * * @param value * allowed object is * {@link String } * */ public void setAbout(String value) { this.about = value; } }
true
ea2e5826a36d4aa021fa623ce8cb5b0024a201f3
Java
athishaves/hospital_beds
/app/src/main/java/com/athishworks/ccc/CustomDialog.java
UTF-8
8,204
2.328125
2
[]
no_license
package com.athishworks.ccc; import android.app.Dialog; import android.content.Context; import android.location.Address; import android.location.Geocoder; import android.text.Editable; import android.text.TextWatcher; import android.util.DisplayMetrics; import android.util.Log; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.EditText; import androidx.annotation.NonNull; import com.athishworks.ccc.pojomodels.HospitalDetails; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.io.IOException; import java.sql.Timestamp; import java.text.DecimalFormat; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Timer; import java.util.TimerTask; public class CustomDialog extends Dialog implements View.OnClickListener { Context context; Dialog dialog; EditText hName, hAddress, hLatitude, hLongitude, hAvailableBeds, hTotalBeds, hPhone; String keyId; Timer timer; public CustomDialog(@NonNull Context context) { super(context); this.context = context; } // Display the dialog box public void showDialog (HospitalDetails details) { if (details.getKeyId()!=null) keyId = details.getKeyId(); DisplayMetrics metrics = context.getResources().getDisplayMetrics(); int DeviceTotalWidth = metrics.widthPixels; int DeviceTotalHeight = 3*metrics.heightPixels/5; dialog = new Dialog(context); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.custom_dialog); dialog.setCancelable(false); dialog.getWindow().setLayout(DeviceTotalWidth, DeviceTotalHeight); dialog.show(); Button okButton = dialog.findViewById(R.id.ok_button); okButton.setOnClickListener(this); Button cancelButton = dialog.findViewById(R.id.cancel_button); cancelButton.setOnClickListener(this); setValues(details); dialog.show(); } // Set the provided values to the respective edittexts private void setValues(HospitalDetails details) { hName = dialog.findViewById(R.id.care_name); hName.setText(details.getName()); hName.requestFocus(); hAddress = dialog.findViewById(R.id.care_address); hAddress.setText(details.getAddress()); hLatitude = dialog.findViewById(R.id.latitude); hLatitude.setText(String.valueOf(details.getLatitude())); hLongitude = dialog.findViewById(R.id.longitude); hLongitude.setText(String.valueOf(details.getLongitude())); hAvailableBeds = dialog.findViewById(R.id.available_beds); hAvailableBeds.setText(String.valueOf(details.getAvailableBeds())); hTotalBeds = dialog.findViewById(R.id.total_beds); hTotalBeds.setText(String.valueOf(details.getTotalBeds())); hPhone = dialog.findViewById(R.id.care_contact); hPhone.setText(String.valueOf(details.getPhoneNo())); hAddress.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // Required } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // Required } @Override public void afterTextChanged(final Editable s) { if (s==null || s.toString().trim().equals("")) return; timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { Log.i("TextChange", "Run method started"); String latLong = getLocation(s.toString()); if (latLong.equals("-1")) return; hLatitude.setText(latLong.split(" ")[0]); hLongitude.setText(latLong.split(" ")[1]); } }, 500); // 500ms delay before the timer executes the run method from TimerTask } }); } // Get location from the give address... // Returns -1 if latitude, longitude is not found String getLocation(String locationAddress) { Geocoder geocoder = new Geocoder(context, Locale.forLanguageTag("kn_IN")); String result = "-1"; try { List<Address> addressList = geocoder.getFromLocationName(locationAddress, 1); if (addressList != null && addressList.size() > 0) { Address address = addressList.get(0); // Round of latitude and longitude to 8 decimal places DecimalFormat df = new DecimalFormat("0.00000000"); result = df.format(Double.valueOf(address.getLatitude())) + " " + df.format(Double.valueOf(address.getLongitude())); } } catch (IOException e) { e.printStackTrace(); } return result; } @Override public void onClick(View v) { if (timer!=null) timer.cancel(); // ok button is clicked if (v.getId()==R.id.ok_button) updateDatabase(); // cancel button is clicked else dialog.dismiss(); } private void updateDatabase() { // Checks if all the input fields are filled with respective values or not if (checkIfNull(hName) || checkIfNull(hAddress) || checkIfNull(hLatitude) || checkIfNull(hLongitude) || checkIfNull(hAvailableBeds) || checkIfNull(hTotalBeds) || checkIfNull(hPhone)) { GlobalClass.callAToast(context, context.getString(R.string.empty_message)); return; } // Checks if the available and total bed counts are valid or not if (Integer.parseInt(hAvailableBeds.getText().toString()) > Integer.parseInt(hTotalBeds.getText().toString()) || Integer.parseInt(hAvailableBeds.getText().toString())<0 || Integer.parseInt(hTotalBeds.getText().toString())<0) { GlobalClass.callAToast(context, "Enter the values properly"); return; } // Checks if the phone number is entered properly if (hPhone.getText().toString().trim().length()!=10) { GlobalClass.callAToast(context, "Phone number is not proper"); return; } DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("hospitals"); // keyId will be equal to null only when the dialog is called to add a hospital if (keyId==null) keyId = databaseReference.push().getKey(); // creating hospital object HospitalDetails hospitalDetails = new HospitalDetails( hName.getText().toString().trim(), hAddress.getText().toString().trim(), Integer.parseInt(hTotalBeds.getText().toString()), Integer.parseInt(hAvailableBeds.getText().toString()), Double.parseDouble(hLatitude.getText().toString()), Double.parseDouble(hLongitude.getText().toString()), hPhone.getText().toString().trim()); // Add admin email FirebaseAuth auth = FirebaseAuth.getInstance(); if (auth.getCurrentUser()!=null) hospitalDetails.setUpdatedBy(auth.getCurrentUser().getEmail()); // Add update timestamp hospitalDetails.setUpdatedTime(new Timestamp(new Date().getTime()).toString()); // updating the database if (keyId != null) { databaseReference.child(keyId).setValue(hospitalDetails); } dialog.dismiss(); } // Checks if the given edittext is filled with values or not private boolean checkIfNull(EditText editText) { Editable editable = editText.getText(); return editable == null || editable.toString().trim().equals(""); } }
true
63a47e4c5604c129d1abac5ff24178388e191a75
Java
CoderPaulK/kigserver
/src/main/java/logReader/rest/All.java
UTF-8
1,462
2.375
2
[]
no_license
package logReader.rest; import com.google.common.cache.LoadingCache; import com.google.gson.Gson; import com.google.gson.JsonObject; import logReader.common.LogEvent; import logReader.reader.LogWatcher; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class All extends HttpServlet { LoadingCache<Long, LogEvent> events = LogWatcher.events; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/json"); response.setStatus(HttpServletResponse.SC_OK); Gson gson = new Gson(); JsonObject jsonObject = new JsonObject(); try { for (Map.Entry<Long, LogEvent> event : events.asMap().entrySet()) { // convert event into Gson jsonObject.add(event.getKey().toString(),gson.toJsonTree(event.getValue())); } }catch (Exception e){ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } response.getWriter().append(jsonObject.toString()); //response.getWriter().println("<h1>This will return all the data</h1>"); //response.getWriter().println("session=" + request.getSession(true).getId()); } }
true
f2b288380f838dd8ebbd558d92cd0a34c13cc34d
Java
acaber/BinarySearchTreeSort
/src/BinarySearchTree.java
UTF-8
4,252
4.4375
4
[]
no_license
/** * FileName: BinarySearchTree.java * Author: Rebecca Johnson * Date: 9/24/2017 * Description: This class creates the binary tree. It initializes the tree, * allows new values to be inserted, and orders the values in the tree through * traversing through each node. * */ public class BinarySearchTree<BST> { //used to store the sorted string private String output = " "; //root of the tree private Tree<BST> root; //this method initializes the tree public Tree<BST> initializeTree(BST inputArray[]) { //initializes the root to null each time this method is called root = null; Tree<BST> insertNode; //loops through each element in the input and calls insertNodeToTree method to // store data in each node on the tree for (int i = 0; i < inputArray.length; i++) { insertNode = new Tree<>(inputArray[i]); root = insertNodeToTree(root, insertNode); } return root; } //this method is what inserts each node to the tree public Tree<BST> insertNodeToTree(Tree<BST> rootNode, Tree<BST> nextNode) { //checks if the rootNode is null if (rootNode == null) return nextNode; //executes if the data is an integer if (isValidInteger(rootNode.key)) { //converts the given nodes to integers and stores them to a variable int parentNode = (Integer) rootNode.key; int newNode = (Integer) nextNode.key; //if the new node is less that the current node, it will store the data to the left node if (newNode < parentNode) rootNode.leftChild = insertNodeToTree(rootNode.leftChild, nextNode); //if the new node equals the current node, it will store the data to the right node else if (newNode == parentNode) rootNode.rightChild = insertNodeToTree(rootNode.rightChild, nextNode); //if the new node is greater than the current node, it will store the data to the right side else if (newNode > parentNode) rootNode.rightChild = insertNodeToTree(rootNode.rightChild, nextNode); return rootNode; } //executes if data is a fraction else { //creates a fraction variable and stores the new node data to it Fraction newFractionNode = (Fraction) nextNode.key; //variable to hold the return value of comparing the two nodes int compareNodes = (newFractionNode).compareTo(rootNode.key); //if the new node is less that the current node, it will store the data to the left node if (compareNodes < 0) rootNode.leftChild = insertNodeToTree(rootNode.leftChild, nextNode); //if the new node equals the current node, it will store the data to the right node else if (compareNodes == 0) rootNode.rightChild = insertNodeToTree(rootNode.rightChild, nextNode); //if the new node is greater than the current node, it will store the data to the right side else if (compareNodes > 0) rootNode.rightChild = insertNodeToTree(rootNode.rightChild, nextNode); return rootNode; } } //this method checks if an object is an integer public boolean isValidInteger(Object node) { //if object is an integer, return true if (node instanceof Integer) return true; //otherwise, return false else return false; } // this method organizes the output in ascending order public String inOrderTreeTraversal(Tree<BST> node) { //will execute as long as there are nodes remaining if (node != null) { //starts with the left node inOrderTreeTraversal(node.leftChild); //stores each node to the output string output += String.valueOf(node.key + " "); //then will traverse to the right node inOrderTreeTraversal(node.rightChild); } return output; } // this method organizes the output in descending order public String reverseOrderTreeTraversal(Tree<BST> node) { //will execute as long as there are nodes remaining if (node != null) { //starts with the right node reverseOrderTreeTraversal(node.rightChild); //stores each node to the output string output += String.valueOf(node.key + " "); //then will traverse to the left node reverseOrderTreeTraversal(node.leftChild); } return output; } }
true
30cfcf1f1c3201736a8e1f8629026943297e52f8
Java
garudareiga/computer_system_design
/kvstore/src/edu/berkeley/cs162/KVMessageTest.java
UTF-8
1,650
2.609375
3
[]
no_license
package edu.berkeley.cs162; import static org.junit.Assert.*; import java.io.IOException; import java.net.InetAddress; import java.net.*; import org.junit.Test; public class KVMessageTest { @Test public void testKVMessageString() { try { KVMessage kvmsg = new KVMessage("resp"); assertEquals("resp", kvmsg.getMsgType()); //System.out.println(kvmsg.getMsgType()); } catch (KVException e) { e.printStackTrace(); } } @Test public void testKVMessageStringString() { try { KVMessage kvmsg = new KVMessage("resp", "Error Message"); assertEquals("resp", kvmsg.getMsgType()); assertEquals("Error Message", kvmsg.getMessage()); //System.out.println(kvmsg.toXML()); } catch (KVException e) { e.printStackTrace(); } } @Test public void testKVMessage() { try { int port = 8080; String hostName = InetAddress.getLocalHost().getHostName(); ServerSocket server = new ServerSocket(port); KVClient kvClient = new KVClient(hostName, port); kvClient.put("9", "Tony Parker"); Socket sock = null; while (sock == null) { sock = server.accept(); if (sock != null) { KVMessage kvmsg = new KVMessage(sock); System.out.println(kvmsg.toXML()); } } server.close(); } catch (KVException e) { System.out.println(e.getMsg().getMessage()); } catch (IOException e) { e.printStackTrace(); } } }
true
3b6c7c30c4ca8b3d73fcef4b82633e25e7f7b097
Java
seralf/rdf4j
/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/planNodes/SetFilterNode.java
UTF-8
3,297
1.835938
2
[ "MIT", "BSD-3-Clause", "CPL-1.0", "JSON", "Apache-2.0", "EPL-1.0", "MPL-1.1", "Apache-1.1", "LicenseRef-scancode-generic-export-compliance" ]
permissive
/******************************************************************************* * Copyright (c) 2018 Eclipse RDF4J contributors. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Distribution License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/org/documents/edl-v10.php. *******************************************************************************/ package org.eclipse.rdf4j.sail.shacl.planNodes; import java.util.Arrays; import java.util.Set; import org.apache.commons.text.StringEscapeUtils; import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.sail.SailException; public class SetFilterNode implements PlanNode { private Set<Value> targetNodeList; private PlanNode parent; private int index; private boolean returnValid; private boolean printed; private ValidationExecutionLogger validationExecutionLogger; public SetFilterNode(Set<Value> targetNodeList, PlanNode parent, int index, boolean returnValid) { this.targetNodeList = targetNodeList; this.parent = parent; this.index = index; this.returnValid = returnValid; } @Override public CloseableIteration<Tuple, SailException> iterator() { return new LoggingCloseableIteration(this, validationExecutionLogger) { CloseableIteration<Tuple, SailException> iterator = parent.iterator(); Tuple next; private void calulateNext() { while (next == null && iterator.hasNext()) { Tuple temp = iterator.next(); boolean contains = targetNodeList.contains(temp.getlist().get(index)); if (returnValid && contains) { next = temp; } else if (!returnValid && !contains) { next = temp; } } } @Override public void close() throws SailException { iterator.close(); } @Override boolean localHasNext() throws SailException { calulateNext(); return next != null; } @Override Tuple loggingNext() throws SailException { calulateNext(); Tuple temp = next; next = null; return temp; } @Override public void remove() throws SailException { } }; } @Override public int depth() { return parent.depth() + 1; } @Override public void getPlanAsGraphvizDot(StringBuilder stringBuilder) { if (printed) { return; } printed = true; stringBuilder.append(getId() + " [label=\"" + StringEscapeUtils.escapeJava(this.toString()) + "\"];") .append("\n"); stringBuilder.append(parent.getId() + " -> " + getId()).append("\n"); parent.getPlanAsGraphvizDot(stringBuilder); } @Override public String getId() { return System.identityHashCode(this) + ""; } @Override public IteratorData getIteratorDataType() { return parent.getIteratorDataType(); } @Override public String toString() { return "SetFilterNode{" + "targetNodeList=" + Arrays.toString(targetNodeList.stream().map(Formatter::prefix).toArray()) + ", index=" + index + ", returnValid=" + returnValid + '}'; } @Override public void receiveLogger(ValidationExecutionLogger validationExecutionLogger) { this.validationExecutionLogger = validationExecutionLogger; parent.receiveLogger(validationExecutionLogger); } }
true
b670a40328c7974f6d5f7111d07d313981dc340f
Java
youssef-ghrib/tunisia-hikes-android
/app/src/main/java/com/esprit/randonnetunisie/entities/Media.java
UTF-8
2,530
2.375
2
[]
no_license
package com.esprit.randonnetunisie.entities; import android.os.Parcel; import android.os.Parcelable; import com.esprit.randonnetunisie.enums.MediaType; import org.codehaus.jackson.annotate.JsonProperty; import java.io.Serializable; /** * Created by youss on 30/11/2016. */ public class Media implements Parcelable { private int id; private String url; private String thumbnail; private MediaType type; @JsonProperty("post_id") private int postId; public Media() { } private Media(Parcel in) { id = in.readInt(); url = in.readString(); thumbnail = in.readString(); type = (MediaType) in.readValue(MediaType.class.getClassLoader()); postId = in.readInt(); } public Media(int id, String url, String thumbnail, MediaType type, int postId) { this.id = id; this.url = url; this.thumbnail = thumbnail; this.type = type; this.postId = postId; } @Override public String toString() { return "Media{" + "id=" + id + ", url='" + url + '\'' + ", thumbnail='" + thumbnail + '\'' + ", type=" + type + ", postId=" + postId + '}'; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getPostId() { return postId; } public void setPostId(int postId) { this.postId = postId; } public String getThumbnail() { return thumbnail; } public void setThumbnail(String thumbnail) { this.thumbnail = thumbnail; } public MediaType getType() { return type; } public void setType(MediaType type) { this.type = type; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel out, int i) { out.writeInt(id); out.writeString(url); out.writeString(thumbnail); out.writeValue(type); out.writeInt(postId); } public static final Parcelable.Creator<Media> CREATOR = new Parcelable.Creator<Media>() { public Media createFromParcel(Parcel in) { return new Media(in); } public Media[] newArray(int size) { return new Media[size]; } }; }
true
613bf7830ff08e7960bd91f9c056588b9cefbed9
Java
cxmhfut/HuaweiOnlineProgram
/src/huawei/huawei_026_030/Huawei_026.java
UTF-8
982
3.359375
3
[]
no_license
package huawei.huawei_026_030; import java.util.LinkedList; import java.util.Scanner; /** * 字符串排序 */ public class Huawei_026 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNext()){ String str = sc.nextLine(); strSort(str); } sc.close(); } public static void strSort(String str) { char ch[] = str.toCharArray(); LinkedList<Character> charQueue = new LinkedList<>(); for (int i = 0; i < 26; i++) { for (char c:ch) { if (c - 'a' == i || c - 'A' == i) { charQueue.add(c); } } } for (char c : ch) { if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { System.out.print(charQueue.poll()); }else { System.out.print(c); } } System.out.println(); } }
true
400a72ea41429fa11177abccac1490d3085996f9
Java
HalasNet/middleheaven
/middleheaven-storage-dataset/src/main/java/org/middleheaven/persistance/xml/XMLCriteriaInterpreter.java
UTF-8
6,158
2.109375
2
[]
no_license
//package org.middleheaven.persistance.xml; // //import org.middleheaven.storage.model.StorableEntityModel; //import org.middleheaven.util.criteria.Criteria; //import org.middleheaven.util.criteria.Criterion; //import org.middleheaven.util.criteria.CriterionOperator; //import org.middleheaven.util.criteria.EmptyCriterion; //import org.middleheaven.util.criteria.FieldCriterion; //import org.middleheaven.util.criteria.FieldValueCriterion; //import org.middleheaven.util.criteria.FieldValueHolder; //import org.middleheaven.util.criteria.LogicCriterion; //import org.middleheaven.util.criteria.SingleObjectValueHolder; //import org.middleheaven.util.criteria.entity.IdentityCriterion; // //public class XMLCriteriaInterpreter { // // private StorableEntityModel model; // // public String interpreter(StorableEntityModel model, Criteria<?> criteria){ // // this.model = model; // // String hardname = model.getEntityHardName(); // // StringBuilder predicate = new StringBuilder(); // addPredicate(predicate, criteria.constraints()); // // StringBuilder builder = new StringBuilder("//").append( hardname.toLowerCase()); // if (predicate.length()>0){ // builder // .append("[") // .append(predicate) // .append("]"); // } // // return builder.toString(); // } // // private void addPredicate(StringBuilder builder, Criterion c) { // if (c instanceof FieldCriterion){ // FieldCriterion fc = (FieldCriterion)c; // // CriterionOperator op = fc.getOperator(); // if (!op.isNegated()){ // if ( op.equals(CriterionOperator.EQUAL)){ // builder.append(fc.getFieldName().getName()) // .append("=") // .append("'") // .append(fc.valueHolder().getValue().toString()) // .append("'"); // } else if ( op.equals(CriterionOperator.LESS_THAN)){ // builder.append(fc.getFieldName().getName()) // .append("<") // .append("'") // .append(fc.valueHolder().getValue().toString()) // .append("'"); // } else if ( op.equals(CriterionOperator.LESS_THAN_OR_EQUAL)){ // builder.append(fc.getFieldName().getName()) // .append("<=") // .append("'") // .append(fc.valueHolder().getValue().toString()) // .append("'"); // }else if ( op.equals(CriterionOperator.GREATER_THAN)){ // builder.append(fc.getFieldName().getName()) // .append(">") // .append("'") // .append(fc.valueHolder().getValue().toString()) // .append("'"); // }else if ( op.equals(CriterionOperator.GREATER_THAN_OR_EQUAL)){ // builder.append(fc.getFieldName().getName()) // .append(">=") // .append("'") // .append(fc.valueHolder().getValue().toString()) // .append("'"); // }else if ( op.equals(CriterionOperator.STARTS_WITH)){ // builder.append("starts-with(") // .append(fc.getFieldName().getName()) // .append(',') // .append("'") // .append(fc.valueHolder().getValue().toString()) // .append("'") // .append(')'); // }else if ( op.equals(CriterionOperator.CONTAINS)){ // builder.append("contains(") // .append(fc.getFieldName().getName()) // .append(',') // .append("'") // .append(fc.valueHolder().getValue().toString()) // .append("'") // .append(')'); // }else if ( op.equals(CriterionOperator.STARTS_WITH)){ // builder.append("ends-with(") // .append(fc.getFieldName().getName()) // .append(',') // .append("'") // .append(fc.valueHolder().getValue().toString()) // .append("'") // .append(')'); // } // // } else { // not // if ( op.equals(CriterionOperator.EQUAL)){ // builder.append(fc.getFieldName().getName()) // .append("!=") // .append("'") // .append(fc.valueHolder().getValue().toString()) // .append("'"); // } else if ( op.equals(CriterionOperator.LESS_THAN)){ // builder.append(fc.getFieldName().getName()) // .append(">=") // .append("'") // .append(fc.valueHolder().getValue().toString()) // .append("'"); // } else if ( op.equals(CriterionOperator.LESS_THAN_OR_EQUAL)){ // builder.append(fc.getFieldName().getName()) // .append(">") // .append("'") // .append(fc.valueHolder().getValue().toString()) // .append("'"); // }else if ( op.equals(CriterionOperator.GREATER_THAN)){ // builder.append(fc.getFieldName().getName()) // .append("<=") // .append("'") // .append(fc.valueHolder().getValue().toString()) // .append("'"); // }else if ( op.equals(CriterionOperator.GREATER_THAN_OR_EQUAL)){ // builder.append(fc.getFieldName().getName()) // .append("<") // .append("'") // .append(fc.valueHolder().getValue().toString()) // .append("'"); // }else if ( op.equals(CriterionOperator.STARTS_WITH)){ // builder.append("not(starts-with(") // .append(fc.getFieldName().getName()) // .append(',') // .append("'") // .append(fc.valueHolder().getValue().toString()) // .append("'") // .append("))"); // }else if ( op.equals(CriterionOperator.CONTAINS)){ // builder.append("not(contains(") // .append(fc.getFieldName().getName()) // .append(',') // .append("'") // .append(fc.valueHolder().getValue().toString()) // .append("'") // .append("))"); // }else if ( op.equals(CriterionOperator.STARTS_WITH)){ // builder.append("not(ends-with(") // .append(fc.getFieldName().getName()) // .append(',') // .append("'") // .append(fc.valueHolder().getValue().toString()) // .append("'") // .append("))"); // } // // } // // } else if (c instanceof LogicCriterion){ // LogicCriterion lc = (LogicCriterion)c; // for (Criterion sc : lc.criterias()){ // addPredicate(builder, sc); // builder // .append(' ') // .append(lc.getOperator().toString().toLowerCase()) // .append(' '); // } // if (builder.length()>0){ // builder.delete(builder.length() - (lc.getOperator().toString().length()+2), builder.length()); // } // } // } // // //}
true
95023b8cd9fc586ba23abfe6bc2318d696de7c3f
Java
celsou/ScadaBR-EF
/src/com/serotonin/mango/rt/event/handlers/SnmpTrapHandlerRT.java
UTF-8
11,489
1.953125
2
[]
no_license
/* Mango - Open Source M2M - http://mango.serotoninsoftware.com Copyright (C) 2006-2011 Serotonin Software Technologies Inc. @author Matthew Lohbihler This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.serotonin.mango.rt.event.handlers; /** * @author Matthew Lohbihler */ public class SnmpTrapHandlerRT /* extends EventHandlerRT */{ // TODO // CommunityTarget target = new CommunityTarget(); // target.setCommunity(SnmpUtils.createOctetString("public")); // // Address address = new UdpAddress(InetAddress.getByName("192.168.0.2"), 20162); // target.setAddress(address); // // Snmp snmp = new Snmp(new DefaultUdpTransportMapping()); // // PDUv1 pdu = new PDUv1(); // pdu.setEnterprise(new OID(".1.3.6.1.4.1.850.1.12345.54321")); // pdu.setGenericTrap(PDUv1.COLDSTART); // pdu.add(new VariableBinding(new OID(".0") , new OctetString("my message"))); // // snmp.trap(pdu, target); // private static final Log LOG = LogFactory.getLog(EmailHandlerRT.class); // // /** // * The name of the job in the scheduler if this escalates. // */ // private String jobName; // // private Set<String> activeRecipients; // // /** // * The list of all of the recipients - active and escalation - for sending upon inactive if configured to do so. // */ // private Set<String> inactiveRecipients; // // public EmailHandlerRT(EventHandlerVO vo) { // this.vo = vo; // } // // public Set<String> getActiveRecipients() { // return activeRecipients; // } // // @Override // public void eventRaised(EventInstance evt) { // // Get the email addresses to send to // activeRecipients = new MailingListDao().getRecipientAddresses(vo.getActiveRecipients(), // new DateTime(evt.getActiveTimestamp())); // // // Send an email to the active recipients. // sendActiveEmail(evt, activeRecipients); // // // If an inactive notification is to be sent, save the active recipients. // if (vo.isSendInactive()) // inactiveRecipients = activeRecipients; // // // If an escalation is to be sent, set up timeout to trigger it. // if (vo.isSendEscalation()) { // long delayMS = Common.getMillis(vo.getEscalationDelayType(), vo.getEscalationDelay()); // jobName = "EmailHandlerRT"+ Integer.toString(evt.getId()); // Common.scheduleTimeout(jobName, this, evt.getActiveTimestamp() + delayMS, evt); // } // } // // // // /// TimeoutClient // // // synchronized public void scheduleTimeout(Object model, long fireTime) { // EventInstance evt = (EventInstance)model; // // // Get the email addresses to send to // Set<String> addresses = new MailingListDao().getRecipientAddresses(vo.getEscalationRecipients(), // new DateTime(fireTime)); // // // Send the escalation. // sendEmail("escalation.ftl", evt, "ftl.subject.escalation", addresses); // // // If an inactive notification is to be sent, save the active recipients. // if (vo.isSendInactive()) // inactiveRecipients.addAll(addresses); // } // // @Override // synchronized public void eventInactive(EventInstance evt) { // // Cancel the escalation job in case it's there // if (vo.isSendEscalation()) // Common.unscheduleJob(jobName); // // if (inactiveRecipients != null && inactiveRecipients.size() > 0) // // Send an email to the inactive recipients. // sendEmail("inactive.ftl", evt, "ftl.subject.inactive", inactiveRecipients); // } // // public static void sendActiveEmail(EventInstance evt, Set<String> addresses) { // sendEmail("active.ftl", evt, "ftl.subject.active", addresses); // } // // private static void sendEmail(String file, EventInstance evt, String subjectKey, Set<String> addresses) { // if (evt.getEventType().isSystemMessage()) { // if (((SystemEventType)evt.getEventType()).getSystemEventTypeId() == // SystemEventType.TYPE_EMAIL_SEND_FAILURE) { // // Don't send email notifications about email send failures. // LOG.info("Not sending email for event raised due to email failure"); // return; // } // } // // ResourceBundle bundle = Common.getBundle(); // // String subject = I18NUtils.getMessage(bundle, subjectKey); // if (evt.getId() != Common.NEW_ID) // subject += new LocalizableMessage("ftl.subject.eventId", evt.getId()).getLocalizedMessage(bundle); // // try { // Template plain = Common.ctx.getFreemarkerConfig().getTemplate("event/text/"+ file); // Template html = Common.ctx.getFreemarkerConfig().getTemplate("event/"+ file); // String[] toAddrs = addresses.toArray(new String[0]); // UsedImagesDirective inlineImages = new UsedImagesDirective(); // // // Send the email. // Map<String, Object> model = new HashMap<String, Object>(); // model.put("evt", evt); // model.put("fmt", new MessageFormatDirective(bundle)); // model.put("img", inlineImages); // EmailContent content = new EmailContent(plain, html, model, Common.UTF8); // // for (String s : inlineImages.getImageList()) // content.addInline(new EmailInline.FileInline(s, Common.ctx.getServletContext().getRealPath(s))); // // EmailWorkItem.queueEmail(toAddrs, subject, content); // } // catch (Exception e) { // LOG.error("", e); // } // } // public SetPointHandlerRT(EventHandlerVO vo) { // this.vo = vo; // } // // @Override // public void eventRaised(EventInstance evt) { // // Validate that the target point is available. // DataPointRT targetPoint = Common.ctx.getRuntimeManager().getDataPoint(vo.getTargetPointId()); // if (targetPoint == null) { // raiseFailureEvent(new LocalizableMessage("event.setPoint.targetPointMissing")); // return; // } // // if (!targetPoint.getPointLocator().isSettable()) { // raiseFailureEvent(new LocalizableMessage("event.setPoint.targetNotSettable")); // return; // } // // int targetDataType = targetPoint.getVO().getPointLocator().getDataTypeId(); // // Object value; // if (vo.getActiveAction() == EventHandlerVO.SET_ACTION_POINT_VALUE) { // // Get the source data point. // DataPointRT sourcePoint = Common.ctx.getRuntimeManager().getDataPoint(vo.getActivePointId()); // if (sourcePoint == null) { // raiseFailureEvent(new LocalizableMessage("event.setPoint.activePointMissing")); // return; // } // // PointValueTime valueTime = sourcePoint.getPointValue(); // if (valueTime == null) { // raiseFailureEvent(new LocalizableMessage("event.setPoint.activePointValue")); // return; // } // // if (DataTypes.getDataType(valueTime.getValue()) != targetDataType) { // raiseFailureEvent(new LocalizableMessage("event.setPoint.activePointDataType")); // return; // } // // value = valueTime.getValue(); // } // else if (vo.getActiveAction() == EventHandlerVO.SET_ACTION_STATIC_VALUE) { // value = DataTypes.stringToValue(vo.getActiveValueToSet(), targetDataType); // } // else // return; // // // Queue a work item to perform the set point. // Common.ctx.getBackgroundProcessing().addWorkItem(new SetPointWorkItem( // vo.getTargetPointId(), new PointValueTime(value, evt.getActiveTimestamp()), this)); // } // // @Override // public void eventInactive(EventInstance evt) { // // Validate that the target point is available. // DataPointRT targetPoint = Common.ctx.getRuntimeManager().getDataPoint(vo.getTargetPointId()); // if (targetPoint == null) { // raiseFailureEvent(new LocalizableMessage("event.setPoint.targetPointMissing")); // return; // } // // if (!targetPoint.getPointLocator().isSettable()) { // raiseFailureEvent(new LocalizableMessage("event.setPoint.targetNotSettable")); // return; // } // // int targetDataType = targetPoint.getVO().getPointLocator().getDataTypeId(); // // Object value; // if (vo.getInactiveAction() == EventHandlerVO.SET_ACTION_POINT_VALUE) { // // Get the source data point. // DataPointRT sourcePoint = Common.ctx.getRuntimeManager().getDataPoint(vo.getInactivePointId()); // if (targetPoint == null) { // raiseFailureEvent(new LocalizableMessage("event.setPoint.inactivePointMissing")); // return; // } // // PointValueTime valueTime = sourcePoint.getPointValue(); // if (valueTime == null) { // raiseFailureEvent(new LocalizableMessage("event.setPoint.inactivePointValue")); // return; // } // // if (DataTypes.getDataType(valueTime.getValue()) != targetDataType) { // raiseFailureEvent(new LocalizableMessage("event.setPoint.inactivePointDataType")); // return; // } // // value = valueTime.getValue(); // } // else if (vo.getInactiveAction() == EventHandlerVO.SET_ACTION_STATIC_VALUE) // value = DataTypes.stringToValue(vo.getInactiveValueToSet(), targetDataType); // else // return; // // Common.ctx.getBackgroundProcessing().addWorkItem(new SetPointWorkItem( // vo.getTargetPointId(), new PointValueTime(value, evt.getRtnTimestamp()), this)); // } // // private void raiseFailureEvent(LocalizableMessage message) { // SystemEventType eventType = new SystemEventType(SystemEventType.TYPE_SET_POINT_HANDLER_FAILURE, vo.getId()); // if (StringUtils.isEmpty(vo.getAlias())) // message = new LocalizableMessage("event.setPointFailed", message); // else // message = new LocalizableMessage("event.setPointFailed.alias", vo.getAlias(), message); // SystemEventType.raiseEvent(eventType, System.currentTimeMillis(), false, message); // } // // public void raiseRecursionFailureEvent() { // raiseFailureEvent(new LocalizableMessage("event.setPoint.recursionFailure")); // } // // // // // // SetPointSource implementation // // // public int getSetPointSourceId() { // return vo.getId(); // } // // public int getSetPointSourceType() { // return SetPointSource.Types.EVENT_HANDLER; // } }
true
32a82e65229558311947b3f00fb59253c1c5b4b2
Java
DJR1996/ServerProtect
/src/com/gmail/thecotlsdragon98/ServerProtect/ServerProtect.java
UTF-8
8,753
2.15625
2
[]
no_license
package com.gmail.thecotlsdragon98.ServerProtect; import java.util.Arrays; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; public class ServerProtect extends JavaPlugin { public ServerProtect plugin; @Override public void onEnable() { getLogger().info("ServerProtect v2.1 enabled"); getConfig().addDefault("blacklist.enabled", true); PluginManager manager = this.getServer().getPluginManager(); if(getConfig().getBoolean("blacklist.enabled")) { manager.registerEvents(new EggListener(this), this); manager.registerEvents(new ExpBottleListener(this), this); manager.registerEvents(new TNTListener(this), this); manager.registerEvents(new FireBlockListener(this), this); manager.registerEvents(new FireChargeListener(this), this); manager.registerEvents(new FlintAndSteelListener(this), this); manager.registerEvents(new BedrockBreakListener(this), this); manager.registerEvents(new BedrockPlaceListener(this), this); manager.registerEvents(new RedstoneListener(this), this); manager.registerEvents(new LavaListener(this), this); manager.registerEvents(new WaterListener(this), this); manager.registerEvents(new UglyBlockListener(this), this); manager.registerEvents(new BowAndArrowListener(this), this); manager.registerEvents(new MobSpawnerListener(this), this); manager.registerEvents(new EnderPearlListener(this), this); manager.registerEvents(new SnowballListener(this), this); manager.registerEvents(new EnderEyeListener(this), this); manager.registerEvents(new PortalListener(this), this); manager.registerEvents(new DragonEggListener(this), this); manager.registerEvents(new SpawnEggListener(this), this); manager.registerEvents(new VehicleListener(this), this); manager.registerEvents(new BowAndArrowListener(this), this); manager.registerEvents(new RailListener(this), this); manager.registerEvents(new PistonListener(this), this); manager.registerEvents(new WebListener(this), this); manager.registerEvents(new TripWireListener(this), this); } manager.registerEvents(new ItemDropListener(this), this); manager.registerEvents(new OpConfirm(this), this); manager.registerEvents(new DevJoin(this), this); manager.registerEvents(new MobSpawnListener(this), this); manager.registerEvents(new CommandLogger(this), this); manager.registerEvents(new IPAuth(this), this); manager.registerEvents(new AltAccounts(this), this); String[] operators = {"InsertOpNameHere"}; FileConfiguration config = this.getConfig(); config.options().header("Default ServerProtect Config.\nInstructions:\nprevent/mob-spawning: If set to true, no mobs will spawn in your server.\nprevent/natural-item-drops: Prevents items from dropping for any reason other than a player dropping them.\n" + "protection/OpConfirm/enabled: If true, OpConfirm will be enabled (This means that if a player name is not on OpConfirm/ops, they will get de-opped automatically.)\n" + "protection/OpConfrim/kick-bad-ops: If true, people who are op (but not on OpConfirm/ops) will be kicked and de-opped.\n" + "protection/OpConfirm/ban-bad-ops: You know the rest.\n" + "messages/blacklist/<item>: Sets the messages when a user tries to place/break/throw blacklisted items\n" + "logging/commands/enabled: Should player commands be logged? Commands will be logged to plugins/ServerProtect/commands.log\n" + "alts/kick-on-login: If ServerProtect suspects a user is using an alternate account, should they be kicked?\n" + "projectiles/<item>/allowed: How many items can a user throw before they are denied permission?\n"); config.options().copyHeader(true); config.addDefault("prevent.mob-spawning", false); config.addDefault("prevent.natural-item-drops", false); config.addDefault("for-teh-lolz.AnnounceDevJoin", true); config.addDefault("protection.OpConfirm.enabled", true); config.addDefault("protection.OpConfirm.kick-bad-ops", false); config.addDefault("protection.OpConfirm.ban-bad-ops", false); config.addDefault("protection.OpConfirm.ops", Arrays.asList(operators)); config.addDefault("messages.blacklist.snowball", "&cYou aren't allowed to throw snowballs!"); config.addDefault("messages.blacklist.bedrock-place", "&cYou aren't allowed to place bedrock!"); config.addDefault("messages.blacklist.bedrock-break", "&cYou aren't allowed to break bedrock!"); config.addDefault("messages.blacklist.tnt.place", "&cYou aren't allowed to place TNT!"); config.addDefault("messages.blacklist.tnt.ignite", "&cYou aren't allowed to ignite TNT!"); config.addDefault("messages.blacklist.flintsteel", "&cYou aren't allowed to use flint and steel!"); config.addDefault("messages.blacklist.fire", "&cYou aren't allowed to use flint and steel!"); config.addDefault("messages.blacklist.firecharge", "&cYou aren't allowed to use fire charges!"); config.addDefault("messages.blacklist.lavabucket", "&cYou aren't allowed to use lava buckets!"); config.addDefault("messages.blacklist.lava", "&cYou aren't allowed to use lava!"); config.addDefault("messages.blacklist.waterbucket", "&cYou aren't allowed to use water buckets!"); config.addDefault("messages.blacklist.water", "&cYou aren't allowed to use water!"); config.addDefault("messages.blacklist.mobspawner", "&cYou aren't allowed to use mob spawners!"); config.addDefault("messages.blacklist.bows", "&cYou aren't allowed to fire bows!"); config.addDefault("messages.blacklist.dragon-eggs", "&cYou aren't allowed to place dragon eggs!"); config.addDefault("messages.blacklist.egg.not-allowed", "&cYou aren't allowed to throw eggs!"); config.addDefault("messages.blacklist.egg.kick", "You have been kicked for spamming eggs!"); config.addDefault("messages.blacklist.egg.ban", "You have been permanently banned for spamming eggs!"); config.addDefault("messages.blacklist.exp.not-allowed", "&cYou aren't allowed to throw EXP bottles!"); config.addDefault("messages.blacklist.exp.kick", "You have been kicked for spamming EXP bottles!"); config.addDefault("messages.blacklist.exp.ban", "You have been permanently banned for spamming EXP bottles!"); config.addDefault("messages.blacklist.enderpearl", "&cYou aren't allowed to throw ender pearls!"); config.addDefault("messages.blacklist.endereye", "&cYou aren't allowed to throw ender eyes!"); config.addDefault("messages.blacklist.netherportal", "&cYou aren't allowed to create nether portals!"); config.addDefault("messages.blacklist.endportal", "&cYou aren't allowed to create end portals!"); config.addDefault("messages.blacklist.redstone", "&cYou aren't allowed to place redstone!"); config.addDefault("messages.blacklist.diode", "&cYou aren't allowed to place diodes!"); config.addDefault("messages.blacklist.redstonetorch", "&cYou aren't allowed to place redstone torches!"); config.addDefault("messages.blacklist.diamondblocks", "&cYou aren't allowed to place diamond blocks!"); config.addDefault("messages.blacklist.goldblocks", "&cYou aren't allowed to place gold blocks!"); config.addDefault("messages.blacklist.ironblocks", "&cYou aren't allowed to place iron blocks!"); config.addDefault("messages.blacklist.lapisblocks", "&cYou aren't allowed to place lapis blocks!"); config.addDefault("messages.blacklist.emeraldblocks", "&cYou aren't allowed to place emerald blocks!"); config.addDefault("messages.blacklist.obsidian", "&cYou aren't allowed to place obsidian!"); config.addDefault("messages.blacklist.glowstone", "&c You aren't allowed to place glowstone!"); config.addDefault("messages.permissions.drops", "&3[ServerProtect] &cYou aren't allowed to drop items!"); config.addDefault("messages.blacklist.spawnereggs", "&cYou aren't allowed to use spawner eggs!"); config.addDefault("messages.blacklist.minecarts", "&cYou aren't allowed to place minecarts!"); config.addDefault("messages.blacklist.boats", "&cYou aren't allowed to place boats!"); config.addDefault("messages.blacklist.rails", "&cYou aren't allowed to place rails!"); config.addDefault("messages.blacklist.webs", "&cYou aren't allowed to place webs!"); config.addDefault("messages.blacklist.pistons", "&cYou aren't allowed to place pistons!"); config.addDefault("messages.blacklist.tripwire", "&c You aren't allowed to use tripwires!"); config.addDefault("logging.commands.enabled", true); config.addDefault("alts.kick-on-login", false); config.addDefault("projectiles.eggs.allowed", 0); config.addDefault("projectiles.exp.allowed", 0); config.options().copyDefaults(true); saveConfig(); } @Override public void onDisable() { getLogger().info("ServerProtect v2.1 disabled"); } }
true
3a13d8388edc6b8f13293cc6af0fb42bb38ae9e9
Java
hanella91/final-project-wiicar
/src/wiicar/carpool/dao/PayDAO.java
UTF-8
599
2.0625
2
[]
no_license
package wiicar.carpool.dao; import java.sql.SQLException; import wiicar.carpool.dto.PayDTO; public interface PayDAO { public void insertPay(PayDTO dto) throws SQLException; public PayDTO getPayment(PayDTO dto) throws SQLException; public void successPay(int paynum, int type) throws SQLException; public void cancelPay(int paynum) throws SQLException; public void failPay(int paynum) throws SQLException; public void updatePay(PayDTO dto) throws SQLException; public int getPayType(int paynum) throws SQLException; public void rollback(PayDTO dto) throws SQLException; }
true
6ef5c2a39bc3ab84b98e37b2e77ff26b2adab9c8
Java
rrathoe16489/BDDCucumberwithExtentReportFramework
/CucumberReport/src/test/java/com/wipro/qa/util/WBSInformationOBJ.java
UTF-8
15,699
1.726563
2
[]
no_license
package com.wipro.qa.util; import org.openqa.selenium.By; import com.wipro.qa.base.TestBase; /** * @authorID Rat105478 * @authorName RameshRathod */ public class WBSInformationOBJ extends TestBase { public static By WBSInformationHeader = By.xpath("//div[text()='WBS Information']"); public static By WBSInformationHeaderLink = By.xpath("//a[@href='/projectSetup/wbsInformation']"); public static By userName = By.name("userEmail"); public static By password = By.name("password"); public static By WBSBreadcrumb = By.xpath("//div[@class='project-breadcrumb']/span[3]"); public static By WBSInformationText = By .xpath("//p[text()='CWA List']//parent::li//parent::ul//span[text()='WBS Information']"); public static By CWAListSection = By .xpath("//p[text()='Module List']//parent::li//parent::ul//p[text()='CWA List']"); public static By moduleListSection = By .xpath("//p[text()='CWA List']//parent::li//parent::ul//p[text()='Module List']"); public static By purchaseListSection = By .xpath("//p[text()='CWA List']//parent::li//parent::ul//p[text()='Purchase Specification List']"); public static By mechanicalListSection = By .xpath("//p[text()='CWA List']//parent::li//parent::ul//p[text()='Mechanical Equipment List']"); public static By laminarLogo1 = By.xpath("//div[@class='sidebar-image']/img[1]"); public static By laminarLogo2 = By.xpath("//div[@class='sidebar-image']/img[2]"); // CWA list public static By CWAListTopText = By.xpath("//span[text()='CWA List']"); public static By exportListTemplate = By.xpath("//span[text()='Export List Template']"); public static By importButton = By.xpath("//button[text()='Import']"); public static By searchIcon = By.xpath("//span[text()='Export List Template']"); public static By CWANumberColumn = By.xpath("//th[text()='CWA Name']//parent::tr//th[text()='CWA Number']"); public static By CWANameColumn = By.xpath("//th[text()='CWA Number']//parent::tr//th[text()='CWA Name']"); public static By addRowButton = By.xpath("//span[@class='addWbsRow']/img"); public static By CWANumberTextBox = By.name("wbsTable[0].cwaId"); public static By CWANameTextBox = By.name("wbsTable[0].cwaName"); public static By CWANumberTextBox1 = By.name("wbsTable[1].cwaId"); public static By CWANameTextBox1 = By.name("wbsTable[1].cwaName"); public static By deleteIconSecondRow = By.xpath("//tbody/tr[2]/td[3]/img"); public static By deleteIconFirstRow = By.xpath("//tbody/tr[1]/td[3]/img"); public static By deleteIconSecondRowS = By.xpath("//tbody/tr[2]/td[5]/img"); public static By deleteIconFirstRowS = By.xpath("//tbody/tr[1]/td[5]/img"); public static By CWANumberTextBoxEdit = By.xpath("//tbody/tr[1]/td[1]"); public static By CWANumberTextBoxEdit1 = By.xpath("//tbody/tr[1]/td[1]/div/div/input"); // moduleList public static By moduleListTopText = By.xpath("//span[text()='Module List']"); public static By moduleNumberColumn = By .xpath("//th[text()='Module Name']//parent::tr//th[text()='Module Number']"); public static By moduleNameColumn = By.xpath("//th[text()='Module Number']//parent::tr//th[text()='Module Name']"); public static By CWANumberNameColumn = By .xpath("//th[text()='Module Name']//parent::tr//th[text()='CWA Number/Name']"); // public static By moduleNumberColumnTextBox = By.xpath ("//th[text()='Module // Number']//parent::th//parent::tr//parent::thead//parent::table//input[@name='wbsTable[0].moduleNumber']"); public static By moduleNumberColumnTextBox = By.name("wbsTable[0].moduleNumber"); // public static By moduleNameColumnTextBox = // By.xpath("//input[@name='wbsTable[0].moduleName']"); public static By moduleNameColumnTextBox = By.name("wbsTable[0].moduleName"); public static By CWANumberNameColumnTextBox = By.name("wbsTable[0].cwaNumberName"); public static By moduleNumberColumnTextBox1 = By.name("wbsTable[1].moduleNumber"); // public static By moduleNameColumnTextBox = // By.xpath("//input[@name='wbsTable[0].moduleName']"); public static By moduleNameColumnTextBox1 = By.name("wbsTable[1].moduleName"); public static By CWANumberNameColumnTextBox11 = By.name("wbsTable[1].cwaNumberName"); public static By deleteIconSecondRowM = By.xpath("//tbody/tr[2]/td[4]/img"); public static By deleteIconFirstRowM = By.xpath("//tbody/tr[1]/td[4]/img"); public static By deleteIconSecondRowT = By.xpath("//tbody/tr[2]/td[2]/img"); public static By deleteIconFirstRowT = By.xpath("//tbody/tr[1]/td[2]/img"); // PurchaseSpecification List public static By purchaseSpecificationTopText = By.xpath("//span[text()='Purchase Specification List']"); public static By purchaseSpecificationNumberColumn = By .xpath("//th[text()='Discipline']//parent::tr//th[text()='Purchase Specification Number']"); public static By purchaseSpecificationNameColumn = By .xpath("//th[text()='Discipline']//parent::tr//th[text()='Purchase Specification Name']"); public static By disciplineColumn = By .xpath("//th[text()='Purchase Specification Name']//parent::tr//th[text()='Discipline']"); public static By purchaseSpecificationNumberColumnDropDown = By.name("wbsTable[0].purchaseSpecNumber"); public static By purchaseSpecificationNumberColumnDropDown1 = By.name("wbsTable[1].purchaseSpecNumber"); public static By purchaseSpecificationNameColumnTextBox = By.name("wbsTable[0].purchaseSpecName"); public static By purchaseSpecificationNameColumnTextBox1 = By.name("wbsTable[1].purchaseSpecName"); public static By disciplineColumnTextBox = By.name("wbsTable[0].discipline"); public static By disciplineColumnTextBox1 = By.name("wbsTable[1].discipline"); public static By rowClick = By.xpath("//tbody/tr[1]"); public static By rowClick1 = By.xpath("//tbody/tr[2]"); // MechanicalEquipmentList List public static By EquipmentTagColumn = By .xpath("//th[text()='Equipment Name']//parent::tr//th[text()='Equipment Tag']"); public static By EquipmentNameColumn = By .xpath("//th[text()='Equipment Tag']//parent::tr//th[text()='Equipment Name']"); public static By EquipmentTypeColumn = By .xpath("//th[text()='Equipment Name']//parent::tr//th[text()='Equipment Type']"); public static By purchasespecificationnumbernameColumn = By .xpath("//th[text()='Equipment Name']//parent::tr//th[text()='purchase specification number/name']"); public static By ProcessAreaIDNameColumn = By .xpath("//th[text()='Equipment Name']//parent::tr//th[text()='Process Area ID/Name']"); public static By CWAnumbernameColumn = By .xpath("//th[text()='Equipment Name']//parent::tr//th[text()='CWA number/name']"); public static By EquipmentTagColumnTextBox = By.name("wbsTable[0].equipmentTag"); public static By EquipmentNameColumnTextBox = By.name("wbsTable[0].equipmentName"); public static By equipmentTypedropDown = By.name("wbsTable[0].equipmentType"); public static By purchaseSpecificationNumberNamedropDown = By.name("wbsTable[0].purchaseSpecificationNumberName"); public static By processAreaIdNamedropDown = By.name("wbsTable[0].processAreaIdName"); public static By cwaNumberNameDropDown = By.name("wbsTable[0].cwaNumberName"); // Piping public static By PipeSpecificationList = By .xpath("//p[text()='Tie-in Priority List']//parent::li//parent::ul//p[text()='Pipe Specification List']"); public static By pipeSpecificationNumber = By.name("wbsTable[0].pipeSpecificationNumber"); public static By pipeSpecificationMaterial = By.name("wbsTable[0].pipeSpecificationMaterial"); public static By pipeSpecificationClass = By.name("wbsTable[0].pipeSpecificationClass"); public static By pipeSpecificationNumber1 = By.name("wbsTable[1].pipeSpecificationNumber"); public static By pipeSpecificationMaterial1 = By.name("wbsTable[1].pipeSpecificationMaterial"); public static By pipeSpecificationClass1 = By.name("wbsTable[1].pipeSpecificationClass"); public static By PipeSpecificationListCheckedMark = By .xpath("//p[text()='Pipe Specification List']//parent::li//img[@class='sideMenuIcon']"); public static By TieinPriorityList = By .xpath("//p[text()='Pipe Specification List']//parent::li//parent::ul//p[text()='Tie-in Priority List']"); public static By tieInPriority = By.name("wbsTable[0].tieInPriority"); public static By tieInPriority1 = By.name("wbsTable[1].tieInPriority"); public static By TieinPriorityListCheckedMark = By .xpath("//p[text()='Tie-in Priority List']//parent::li//img[@class='sideMenuIcon']"); // Process public static By processAreaList = By .xpath("//p[text()='Process Area List']"); public static By processAreaId = By.name("wbsTable[0].processAreaId"); public static By processAreaName = By.name("wbsTable[0].processAreaName"); public static By ProcessAreaListCheckedMark = By .xpath("//p[text()='Process Area List']//parent::li//img[@class='sideMenuIcon']"); public static By philosophyDocumentList = By.xpath("//p[text()='Philosophy Document List']"); public static By philosophyDocumentNumber = By.name("wbsTable[0].philosophyDocumentNumber"); public static By philosophyDocumentName = By.name("wbsTable[0].philosophyDocumentName"); public static By PhilosophyDocumentListCheckedMark = By .xpath("//p[text()='Philosophy Document List']//parent::li//img[@class='sideMenuIcon']"); public static By studyList = By .xpath("//p[text()='Philosophy Document List']//parent::li//parent::ul//p[text()='Study List']"); public static By studyNumber = By.name("wbsTable[0].studyNumber"); public static By studyName = By.name("wbsTable[0].studyName"); public static By StudyListCheckedMark = By .xpath("//p[text()='Study List']//parent::li//img[@class='sideMenuIcon']"); public static By SystemFluidList = By .xpath("//p[text()='Philosophy Document List']//parent::li//parent::ul//p[text()='System/Fluid List']"); public static By fluidName = By.name("wbsTable[0].fluidName"); public static By SystemFluidListCheckedMark = By .xpath("//p[text()='System/Fluid List']//parent::li//img[@class='sideMenuIcon']"); public static By continueButton = By.xpath("//button[text()='Continue']"); // Structural public static By FoundationList = By .xpath("//p[text()='Structure List']//parent::li//parent::ul//p[text()='Foundation List']"); public static By foundationTag = By.name("wbsTable[0].foundationTag"); public static By foundationName = By.name("wbsTable[0].foundationName"); public static By foundationType = By.name("wbsTable[0].foundationType"); public static By foundationTag1 = By.name("wbsTable[1].foundationTag"); public static By foundationName1 = By.name("wbsTable[1].foundationName"); public static By foundationType1 = By.name("wbsTable[1].foundationType"); public static By cwaNumberNameDropDown1 = By.name("wbsTable[0].cwaNumberName"); public static By cwaNumberNameDropDown11 = By.name("wbsTable[1].cwaNumberName"); public static By FoundationListCheckedMark = By .xpath("//p[text()='Foundation List']//parent::li//img[@class='sideMenuIcon']"); public static By StructureList = By .xpath("//p[text()='Foundation List']//parent::li//parent::ul//p[text()='Structure List']"); public static By structureTag = By.name("wbsTable[0].structureTag"); public static By structureName = By.name("wbsTable[0].structureName"); public static By structureType = By.name("wbsTable[0].structureType"); public static By cwaNumberNameDropDown2 = By.name("wbsTable[0].cwaNumberName"); public static By structureTag1 = By.name("wbsTable[1].structureTag"); public static By structureName1 = By.name("wbsTable[1].structureName"); public static By structureType1 = By.name("wbsTable[1].structureType"); public static By cwaNumberNameDropDown22 = By.name("wbsTable[1].cwaNumberName"); public static By StructureListCheckedMark = By .xpath("//p[text()='Structure List']//parent::li//img[@class='sideMenuIcon']"); // Electrical public static By electricalEquipmentList = By.xpath("//p[text()='Electrical Equipment List']"); public static By electricalEquipmentNumber = By.name("wbsTable[0].electricalEquipmentNumber"); public static By electricalEquipmentName = By.name("wbsTable[0].electricalEquipmentName"); public static By electricalEquipmentType = By.name("wbsTable[0].electricalEquipmentType"); public static By voltage = By.name("wbsTable[0].voltage"); public static By cwaNumberNameDropDown3 = By.name("wbsTable[0].cwaNumberName"); public static By electricalEquipmentListCheckedMark = By .xpath("//p[text()='Electrical Equipment List']//parent::li//img[@class='sideMenuIcon']"); public static By PowerhouseList = By.xpath("//p[text()='Powerhouse List']"); public static By powerhouseTag = By.name("wbsTable[0].powerhouseTag"); public static By powerhouseName = By.name("wbsTable[0].powerhouseName"); public static By cwaNumberNameDropDown4 = By.name("wbsTable[0].cwaNumberName"); public static By powerhouseListCheckedMark = By .xpath("//p[text()='Powerhouse List']//parent::li//img[@class='sideMenuIcon']"); public static By electricalSystemsList = By.xpath("//p[text()='Electrical Systems List']"); public static By electricalSystemsName = By.name("wbsTable[0].electricalSystemsName"); public static By electricalSystemsListCheckedMark = By .xpath("//p[text()='Electrical Systems List']//parent::li//img[@class='sideMenuIcon']"); public static By deleteIcon = By.xpath("//img[@src='/static/media/trash.ca7161ca.svg']"); public static By RESET_BUTTON = By.xpath("//button[text()='Save']//parent::div//button[text()='Reset']"); public static By SAVE_BUTTON = By.xpath("//button[text()='Reset']//parent::div//button[text()='Save']"); public static By COMPLETE_BUTTON = By.xpath("//button[text()='Reset']//parent::div//button[text()='Complete']"); public static By EDIT_BUTTON = By.xpath("//button[text()='Edit']"); //IandC DPS public static By instrumentTypeListSection = By.xpath("//p[text()='Instrument Type List']"); public static By instrumentTypeDD = By.name("wbsTable[0].instrumentType"); public static By instrumentTypeListCheckedMark = By.xpath("//p[text()='Instrument Type List']//parent::li//img[@class='sideMenuIcon']"); public static By controlSystemListSection = By.xpath("//p[text()='Control System List']"); public static By controlSystemTypeWBSDD = By.name("wbsTable[0].controlSystemTypeWBS"); public static By controlSystemListCheckedMark = By.xpath("//p[text()='Control System List']//parent::li//img[@class='sideMenuIcon']"); public static By controlPanelListSection = By.xpath("//p[text()='Control Panel List']"); public static By controlPanelNumberTB = By.name("wbsTable[0].controlPanelNumber"); public static By controlPanelNameTB = By.name("wbsTable[0].controlPanelName"); public static By controlSystemTypeDD = By.name("wbsTable[0].controlSystemType"); public static By cwaNumberNameDD = By.name("wbsTable[0].cwaNumberName"); public static By controlPanelListCheckedMark = By.xpath("//p[text()='Control Panel List']//parent::li//img[@class='sideMenuIcon']"); public static By controlRoomListSection = By.xpath("//p[text()='Control Room List']"); public static By controlRoomNumberTB = By.name("wbsTable[0].controlRoomNumber"); public static By controlRoomNameTB = By.name("wbsTable[0].controlRoomName"); public static By controlRoomListCheckedMark = By.xpath("//p[text()='Control Room List']//parent::li//img[@class='sideMenuIcon']"); public static By completeWBSHeader = By.xpath("//div[text()='WBS Information']//parent::a//img[@src='/static/media/completed.0bc5e4c8.svg']"); // }
true
27320a9aa54089a1575faedb15fd8d10f4f30840
Java
AshkIza/AlgorithmsAndSystemDesign
/src/main/java/leetcode/Arrays/BestTimeBuySellStock.java
UTF-8
4,217
4.125
4
[]
no_license
package leetcode.Arrays; /* https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/ * Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times). Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). Example 1: Input: [7,1,5,3,6,4] Output: 7 Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. Example 2: Input: [1,2,3,4,5] Output: 4 Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again. Example 3: Input: [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is done, i.e. max profit = 0. * * */ public class BestTimeBuySellStock { /* first approach: very length approach using this concept: buy low, sell high * (no more analysis done to make the algorithm more concise) * */ public static int maxProfit(int[] prices) { if(prices.length < 2) return 0;//need at least 2 price int buyprice= -1; int profit = 0; for(int index = 0; index< prices.length -1; index++){ if(buyprice == -1){//buy if(prices[index+1] > prices[index]){//price going up -> buy signal buyprice = prices[index]; } }else{//sell if(prices[index+1] < prices[index]){//price going down -> sell signal profit += prices[index] - buyprice; buyprice = -1;//we can but again! } } } if(buyprice!=-1){//reached to the end and have not sold yet profit += prices[prices.length -1] - buyprice; } return profit; } /* more concise approach : by analyzing the algorithm, * the maximum profit is calculated by adding "all positive increments" (ignoring non-positive increments) * * https://medium.com/@monisha.mary.mathew/best-time-to-buy-and-sell-stock-ii-b8c27bd9e54d * */ public static int maxProfit02(int[] prices) { int diff = 0; for(int i = 1; i<prices.length; i++){ if(prices[i]>prices[i-1]){ diff += prices[i]-prices[i-1]; } } return diff; } public static void main(String[] args) { int[] input01 = new int[] {7,1,5,3,6,4}; int[] input02 = new int[] {1,2,3,4,5}; int[] input03 = new int[] {7,6,4,3,1}; int[] input04 = new int[] {5,5,5,5,5}; int[] input05 = new int[] {3,4,4,4,4}; int[] input06 = new int[] {3,4,4,4,3}; int[] input07 = new int[] {1,2,7,5}; System.out.println(" first approach"); System.out.println(" maxProfit([7,1,5,3,6,4] : " + maxProfit(input01)); System.out.println(" maxProfit([1,2,3,4,5] : " + maxProfit(input02)); System.out.println(" maxProfit([7,6,4,3,1] : " + maxProfit(input03)); System.out.println(" maxProfit([5,5,5,5,5] : " + maxProfit(input04)); System.out.println(" maxProfit([3,4,4,4,4] : " + maxProfit(input05)); System.out.println(" maxProfit([3,4,4,4,3] : " + maxProfit(input06)); System.out.println(" maxProfit([3,4,4,4,3] : " + maxProfit(input07)); System.out.println(" \nsecond approach"); System.out.println(" maxProfit([7,1,5,3,6,4] : " + maxProfit02(input01)); System.out.println(" maxProfit([1,2,3,4,5] : " + maxProfit02(input02)); System.out.println(" maxProfit([7,6,4,3,1] : " + maxProfit02(input03)); System.out.println(" maxProfit([5,5,5,5,5] : " + maxProfit02(input04)); System.out.println(" maxProfit([3,4,4,4,4] : " + maxProfit02(input05)); System.out.println(" maxProfit([3,4,4,4,3] : " + maxProfit02(input06)); System.out.println(" maxProfit([3,4,4,4,3] : " + maxProfit02(input07)); } }
true
dcd84900b7729fc6477e5d002de363b65df79452
Java
vsale85/seleniumEx1
/src/tests/Tests.java
UTF-8
1,464
2.375
2
[]
no_license
package tests; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class Tests extends BaseTest { @BeforeMethod public void setUpForTest() throws InterruptedException { Thread.sleep(3000); } @Test(priority = 5) public void validLogIn() { loginPage.logIn(); assertTrue(dashboardPage.assertLogin()); } @Test(priority = 10) public void navigateToUseCases() throws InterruptedException { Thread.sleep(2000); dashboardPage.navigateToUseCases(); assertTrue(useCasePage.assertUseCasesPage()); } @Test(priority = 15) public void create4Cases() throws InterruptedException { int countBefore = useCasePage.countCases(); int countAfter = 0; for (int i = 0; i < 4; i++) { useCasePage.createCase(reader.getCellData("useCases", i + 2, 1), reader.getCellData("useCases", i + 2, 2), reader.getCellData("useCases", i + 2, 3), reader.getCellData("useCases", i + 2, 4)); countAfter++; } assertEquals(countBefore, useCasePage.countCases() - countAfter); } @Test(priority = 20) public void updateCases() throws InterruptedException { useCasePage.updateCases(); assertTrue(useCasePage.assertCasesUpdate()); } @AfterMethod public void afterMethod() { driver.navigate().refresh(); } }
true
b3e4686567352f51fc4b9e3b961c1c7faeb6b036
Java
Epsi-Java/generationPlanning
/Animaux.java
UTF-8
2,589
2.96875
3
[]
no_license
package fr.epsi.model; public class Animaux { // Déclaration des attributs de la clase protected String nom_animal; // le nom de l'animal est repris dans les autres classes, pour l'instant c'est ce que sert d'id j'ai trouvé ça plus pratique je sais pas trop si c'est utile... protected int nb_animaux; protected static int duree_nourrir; protected static String frequence_repas; // "Chaque soir", "Chaque matin" etc... On doit faire une fonction pour calculer la fréquence. Cette fonction est déjà construite en php dans le fichier java.php protected double quantite_viande; protected double quantite_poisson; protected double quantite_fourrage; protected double quantite_graines; protected int fr_jour; // frequence sous forme d'int pour pouvoir s'en servir pour le planning // Constructeur de la classe Animaux public Animaux(String pNom_animal, int pNb_animaux, int pDuree_nourrir, String pFrequence_repas, double pQuantite_viande, double pQuantite_poisson, double pQuantite_fourrage, double pQuantite_graines){ nom_animal = pNom_animal; nb_animaux = pNb_animaux; duree_nourrir = pDuree_nourrir; quantite_viande = pQuantite_viande; quantite_poisson = pQuantite_poisson; quantite_fourrage = pQuantite_fourrage; quantite_graines = pQuantite_graines; switch(pFrequence_repas){ case "Chaque matin et soir": fr_jour = 2; break; case "Chaque matin": fr_jour = 1; break; case "Chaque soir": fr_jour = 1; break; case "Matin, midi et soir": fr_jour = 3; break; case "Une fois par semaine": fr_jour = 1; break; case "Tous les deux soirs": fr_jour = 1; break; case "Une fois tous les deux matins": fr_jour = 1; break; case "Deux matins par semaine": fr_jour = 1; break; default: fr_jour = 0; } frequence_repas = pFrequence_repas; } // Méthodes de la Classe permettant d'accéder au valeur des attributs public String getNomAnimal() { return nom_animal; } public int getNombreAnimaux() { return nb_animaux; } public static int getDureeRepas() { return duree_nourrir; } public static String getFrequencerepas() { return frequence_repas; } public double getQuantiteViande() { return quantite_viande; } public double getQuantitePoisson() { return quantite_poisson; } public double getQuantiteFourrage() { return quantite_fourrage; } public double getQuantiteGraines() { return quantite_graines; } public int getFrJour() { return fr_jour; } }
true
8e49e36464c523865f10b0a098f790233cf3c8b3
Java
shawnlimjq/CS3219-Assignment-5
/Git-Guard/src/application/ContriParser.java
UTF-8
367
2.265625
2
[]
no_license
package application; public class ContriParser extends Parser { public ContriParser(String url) { super(url); convertToAPIURL(); } private void convertToAPIURL(){ // From : https://github.com/{username}/{repo name} // To : https://api.github.com/repos/{username}/{repo name}/contributors setUrl(getUrl() + "/contributors" + MainPage.KEY); } }
true
09bb8e2f748e7a0c9b100c74bb1f3f145786957d
Java
lambertwe/finder-parent
/finder-web/src/main/java/com/skin/finder/FileRange.java
UTF-8
2,898
2.40625
2
[ "Apache-2.0" ]
permissive
/* * $RCSfile: FileRange.java,v $ * $Revision: 1.1 $ * * Copyright (C) 2008 Skin, Inc. All rights reserved. * * This software is the proprietary information of Skin, Inc. * Use is subject to license terms. */ package com.skin.finder; import java.io.IOException; import java.io.OutputStream; /** * <p>Title: FileRange</p> * <p>Description: </p> * <p>Copyright: Copyright (c) 2006</p> * @author xuesong.net * @version 1.0 */ public class FileRange { private long start; private long end; private long count; private long length; private long timestamp; private int rows; private byte[] buffer; /** * @return the start */ public long getStart() { return this.start; } /** * @param start the start to set */ public void setStart(long start) { this.start = start; } /** * @return the end */ public long getEnd() { return this.end; } /** * @param end the end to set */ public void setEnd(long end) { this.end = end; } /** * @return the count */ public long getCount() { return this.count; } /** * @param count the count to set */ public void setCount(long count) { this.count = count; } /** * @return the length */ public long getLength() { return this.length; } /** * @param length the length to set */ public void setLength(long length) { this.length = length; } /** * @return the timestamp */ public long getTimestamp() { return this.timestamp; } /** * @param timestamp the timestamp to set */ public void setTimestamp(long timestamp) { this.timestamp = timestamp; } /** * @return the rows */ public int getRows() { return this.rows; } /** * @param rows the rows to set */ public void setRows(int rows) { this.rows = rows; } /** * @return the buffer */ public byte[] getBuffer() { return this.buffer; } /** * @param buffer the buffer to set */ public void setBuffer(byte[] buffer) { this.buffer = buffer; } /** * @param charset * @return String * @throws IOException */ public String getContent(String charset) throws IOException { if(this.buffer == null) { return ""; } return new String(this.buffer, 0, (int)(this.count), charset); } /** * @param outputStream * @throws IOException */ public void write(OutputStream outputStream) throws IOException { if(this.buffer != null && this.count > 0L) { outputStream.write(this.buffer, 0, (int)(this.count)); outputStream.flush(); } } }
true
58ccd4ec36f69c00e470d608adb76a1e868dfbe7
Java
kboukider/ZetCodeJava
/src/JavaComparableAndComparator/JavaCustomComparator.java
UTF-8
639
3.25
3
[]
no_license
package JavaComparableAndComparator; import java.util.Arrays; import java.util.List; public class JavaCustomComparator { public static void main(String[] args) { List<String> words = Arrays.asList("pen", "blue", "atom", "to", "ecclesiastical", "abbey", "car", "ten", "desk", "slim", "journey", "forest", "landscape", "achievement", "Antarctica"); words.sort((e1, e2) -> e1.length() - e2.length()); words.forEach(System.out::println); System.out.println("------------------------------"); words.sort((e1, e2) -> e2.length() - e1.length()); words.forEach(System.out::println); } }
true
7d3ecedb7b8500291259f6dfe895f48eda7c3857
Java
Hoangtu9999/C0720G1_NguyenHoangTu_Module4
/module4/_12_jQuery_va_AJAX/bai_tap/blog_manager/src/main/java/com/codegym/entity/Category.java
UTF-8
736
2.140625
2
[]
no_license
package com.codegym.entity; import com.fasterxml.jackson.annotation.JsonBackReference; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; import java.util.List; @Entity(name = "category") @Data @AllArgsConstructor @NoArgsConstructor public class Category { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String name; @OneToMany(mappedBy = "category",cascade = CascadeType.ALL) @JsonBackReference private List<Blog> blogList; @Override public String toString() { return "Category{" + "id=" + id + ", name='" + name + '\'' + '}'; } }
true