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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
d92f5d2d1af856d608057ca7578759449c011f57 | Java | Szabat195727/ZaawansowanaJava2017 | /generics_collections/src/main/java/pl/com/tt/GenericListItem.java | UTF-8 | 472 | 2.828125 | 3 | [] | no_license | package pl.com.tt;
public class GenericListItem<T> {
private T value;
private GenericListItem<T> nextElement;
public GenericListItem(T value) {
super();
this.value = value;
}
public T getValue() {
return this.value;
}
public void setValue(T value) {
this.value = value;
}
public GenericListItem<T> getNextElement() {
return nextElement;
}
public void setNextElement(GenericListItem<T> nextElement) {
this.nextElement = nextElement;
}
}
| true |
57e0f141aa9faf98f7fdda1f014541db435a2c95 | Java | ryank231231/jp.co.penet.gekidanprince | /com/squareup/picasso/MemoryPolicy.java | UTF-8 | 824 | 2.53125 | 3 | [] | no_license | package com.squareup.picasso;
public enum MemoryPolicy {
NO_CACHE(1),
NO_STORE(2);
final int index;
static {
$VALUES = new MemoryPolicy[] { NO_CACHE, NO_STORE };
}
MemoryPolicy(int paramInt1) {
this.index = paramInt1;
}
static boolean shouldReadFromMemoryCache(int paramInt) {
boolean bool;
if ((paramInt & NO_CACHE.index) == 0) {
bool = true;
} else {
bool = false;
}
return bool;
}
static boolean shouldWriteToMemoryCache(int paramInt) {
boolean bool;
if ((paramInt & NO_STORE.index) == 0) {
bool = true;
} else {
bool = false;
}
return bool;
}
}
/* Location: Y:\classes2-dex2jar.jar!\com\squareup\picasso\MemoryPolicy.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/ | true |
5923890cfbbe5c4ed654e4fabebe744b969e145c | Java | Drake1804/DemoCode | /app/src/main/java/com/drake1804/f1feedler/model/SocialModel.java | UTF-8 | 1,228 | 2.015625 | 2 | [] | no_license | package com.drake1804.f1feedler.model;
import com.google.gson.annotations.SerializedName;
import io.realm.RealmObject;
/**
* Created by Pavel.Shkaran on 5/26/2016.
*/
public class SocialModel extends RealmObject {
@SerializedName("views")
private int views;
@SerializedName("voting_plus")
private int likes;
@SerializedName("voting_minus")
private int dislikes;
@SerializedName("favorites")
private int favorites;
@SerializedName("comments")
private int comments;
public int getViews() {
return views;
}
public int getLikes() {
return likes;
}
public int getDislikes() {
return dislikes;
}
public int getFavorites() {
return favorites;
}
public int getComments() {
return comments;
}
public void setViews(int views) {
this.views = views;
}
public void setLikes(int likes) {
this.likes = likes;
}
public void setDislikes(int dislikes) {
this.dislikes = dislikes;
}
public void setFavorites(int favorites) {
this.favorites = favorites;
}
public void setComments(int comments) {
this.comments = comments;
}
}
| true |
f7a5415865ceb5a910f6088477216daadca05a0a | Java | yishu4geek/code-challenge-master- | /src/models/Image.java | UTF-8 | 2,471 | 2.671875 | 3 | [] | no_license | package models;
import java.util.Date;
public class Image {
/**
* Mandatory fields
*/
private String image_id;
private String verb;
private Date event_time;
private String customer_id;
/**
* Optional fields
*/
private String camera_make;
private String camera_model;
/**
* Constructor takes mandatory fields
*
* @param image_id
* @param verb
* @param event_time
* @param customer_id
*/
public Image(String image_id, String verb, Date event_time, String customer_id) {
this.image_id = image_id;
this.verb = verb;
this.event_time = event_time;
this.customer_id = customer_id;
}
public Image() {
}
/**
* Constructor takes all fiedls
*
* @param image_id
* @param verb
* @param event_time
* @param customer_id
* @param camera_make
* @param camera_model
*/
public Image(String image_id, String verb, Date event_time, String customer_id, String camera_make, String camera_model) {
this.image_id = image_id;
this.verb = verb;
this.event_time = event_time;
this.customer_id = customer_id;
this.camera_make = camera_make;
this.camera_model = camera_model;
}
/**
* Functions
*/
/**
* Function to do the upload photo work
*
* @return true if upload successfully
*/
public boolean upload() {
return false;
}
public String getImage_id() {
return image_id;
}
public void setImage_id(String image_id) {
this.image_id = image_id;
}
public String getVerb() {
return verb;
}
public void setVerb(String verb) {
this.verb = verb;
}
public Date getEvent_time() {
return event_time;
}
public void setEvent_time(Date event_time) {
this.event_time = event_time;
}
public String getCustomer_id() {
return customer_id;
}
public void setCustomer_id(String customer_id) {
this.customer_id = customer_id;
}
public String getCamera_make() {
return camera_make;
}
public void setCamera_make(String camera_make) {
this.camera_make = camera_make;
}
public String getCamera_model() {
return camera_model;
}
public void setCamera_model(String camera_model) {
this.camera_model = camera_model;
}
} | true |
5ad0d8f5f4295da90d9822adb982d7fcd2c0e0a7 | Java | dveyarangi/temple-defense | /src/main/java/yarangi/game/harmonium/temple/weapons/MinigunBurstLook.java | UTF-8 | 1,753 | 2.125 | 2 | [] | no_license | package yarangi.game.harmonium.temple.weapons;
import javax.media.opengl.GL;
import javax.media.opengl.GL2;
import yar.quadraturin.IRenderingContext;
import yar.quadraturin.IVeil;
import yar.quadraturin.graphics.colors.Color;
import yar.quadraturin.graphics.veils.BlurVeil;
import yar.quadraturin.objects.ILook;
import yarangi.game.harmonium.environment.resources.Port;
public class MinigunBurstLook implements ILook <Projectile>
{
// static float UGLY = 0.0f;
static float dir = 1;
private final Color color;
// private static GLU glu = new GLU();
private IVeil veil;
public MinigunBurstLook(Port port, WeaponProperties weapon)
{
double resourcePercent = port.get( weapon.getResourceType() ).getAmount() / port.getCapacity( weapon.getResourceType() );
this.color = new Color( 0.3f, 1.0f, (float)resourcePercent,1);
// this.color = new Color( (float)((1-resourcePercent)+resourcePercent*0.1), (float)(resourcePercent*0.5), (float)(resourcePercent),1);
}
@Override
public void render(Projectile prj, IRenderingContext ctx)
{
GL2 gl = ctx.gl();
color.apply( gl );
gl.glPushAttrib( GL2.GL_ENABLE_BIT );
gl.glEnable(GL.GL_BLEND);
gl.glBegin(GL.GL_LINE_STRIP);
gl.glVertex2f(1.2f, 0.1f);
gl.glVertex2f(-1.2f, -0.1f);
gl.glEnd();
gl.glPopAttrib();
}
@Override
public void init(IRenderingContext ctx) {
veil = ctx.getPlugin( BlurVeil.NAME );
}
@Override
public void destroy(IRenderingContext ctx) {
}
@Override
public boolean isCastsShadow() {
return false;
}
@Override
public float getPriority() { return 0; }
@Override
public IVeil getVeil() { return veil; }
@Override
public boolean isOriented() { return true; }
}
| true |
ab5ca2361b1c52b2604810dffe3690256ade726b | Java | abhiyankgoyal/Java | /OOPs/src/inheritance/multilevelInheritance.java | UTF-8 | 955 | 4.09375 | 4 | [] | no_license | package inheritance;
class A{
private int height;
A(int height){
this.height = height;
}
public int getHeight() {
return this.height;
}
}
class B extends A{
private int weight;
B(int height, int weight){
super(height);
this.weight = weight;
}
public int getWeight() {
return this.weight;
}
}
class C extends B{
private int width;
C(int height, int weight, int width){
super(height, weight); // here first class A constructor is called then B and then C
this.width = width;
}
public int getWidth() {
return this.width;
}
}
public class multilevelInheritance {
public static void main(String[] args) {
// TODO Auto-generated method stub
C obj = new C(180, 100, 40);
System.out.println(obj.getHeight());
System.out.println(obj.getWeight());
System.out.println(obj.getWidth());
B obj2 = new B(170, 80);
System.out.println(obj2.getHeight());
System.out.println(obj2.getWeight());
}
}
| true |
04c65c060d220397cfe50be2b31978d54a3d8624 | Java | ofaruk84/fxreportmanagement | /FxReportManagement/src/fxreportmanagement/Report1/REquipmentController.java | UTF-8 | 8,051 | 1.90625 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package fxreportmanagement.Report1;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXRadioButton;
import com.jfoenix.controls.JFXTextField;
import fxreportmanagement.DatabaseOperations.DatabaseEntitates.REquipment;
import fxreportmanagement.HelperClasses.ExcelExporterAsposeReport1;
import fxreportmanagement.Report1.Entitates.REquipmentTab;
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.ToggleGroup;
/**
* FXML Controller class
*
* @author Faruk
*
* Ömer Faruk Korkmaz
* 170503014
*/
public class REquipmentController implements Initializable {
@FXML
private Label lblEquipment;
@FXML
private JFXTextField txtUsedDevice;
private JFXRadioButton rbRi192;
@FXML
private JFXRadioButton rbXRay;
@FXML
private JFXRadioButton rbSe75;
@FXML
private JFXTextField txtExposureTime;
@FXML
private JFXTextField txtFilmFocusDistance;
@FXML
private JFXTextField txtFilters;
@FXML
private JFXTextField txtHeatTreatment;
@FXML
private JFXTextField txtPbScenes;
@FXML
private JFXTextField txtFilmBrand;
@FXML
private JFXRadioButton rbD4;
@FXML
private JFXRadioButton rbD7;
@FXML
private JFXRadioButton rbD5;
@FXML
private JFXRadioButton rbEn;
@FXML
private JFXRadioButton rbAstm;
@FXML
private JFXRadioButton rbFilmSide;
@FXML
private JFXRadioButton rbSourceSide;
@FXML
private JFXRadioButton rbAutomatic;
@FXML
private JFXRadioButton rbManual;
@FXML
private Label lblTemperature;
@FXML
private JFXTextField txtX12;
@FXML
private JFXTextField txtX16;
@FXML
private JFXTextField txtX24;
@FXML
private JFXTextField txtX48;
@FXML
private JFXTextField txtX40;
@FXML
private JFXTextField txtSuitibleFilm;
@FXML
private JFXTextField txtRepairFilm;
@FXML
private JFXButton btnSubmit;
@FXML
private JFXTextField txtX36;
private static REquipmentController instance; // Create Instance
@FXML
private JFXTextField txtFocalSpotsize;
@FXML
private JFXRadioButton rbIr192;
@FXML
private ToggleGroup deviceEnergy;
@FXML
private ToggleGroup IQITech1;
@FXML
private ToggleGroup filmProcessingTech;
@FXML
private ToggleGroup filmType;
@FXML
private ToggleGroup IQITech;
//Constructor
public REquipmentController() {
instance = this;
}
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
fill();
}
//Get Instance
public static REquipmentController getInstance() {
return instance;
}
//Equipment Page Submit Button
@FXML
private void handleBtnSubmitAction(ActionEvent event) {
ExcelExporterAsposeReport1.setEquipment(getRequipment());
System.out.println("R1 Equipment Setted");
}
//Get Equipment Informations From GUI
private REquipmentTab getRequipment() {
String equipment = lblEquipment.getText();
String usedDevice = txtUsedDevice.getText();
String ir192 = getIr192();
String se75 = getSe75();
String xRay = getXray();
String focalSpotSize = txtFocalSpotsize.getText();
String pbScenes = txtPbScenes.getText();
String exposureTime = txtExposureTime.getText();
String filmFocusDistance = txtFilmFocusDistance.getText();
String filters = txtFilters.getText();
String heatTreatment = txtHeatTreatment.getText();
String filmBrand = txtFilmBrand.getText();
String d4 = getD4();
String d5 = getD5();
String d7 = getD7();
String en = getEn();
String astm = getAstm();
String sourceSide = getSourceSide();
String filmSide = getFilmSide();
String automatic = getAutomatic();
String manual = getManuel();
String temperature = lblTemperature.getText();
String x12 = txtX12.getText();
String x16 = txtX16.getText();
String x24 = txtX24.getText();
String x36 = txtX36.getText();
String x48 = txtX48.getText();
String x40 = txtX40.getText();
String suitibleFilm = txtSuitibleFilm.getText();
String repairFilm = txtRepairFilm.getText();
return new REquipmentTab(equipment, usedDevice, ir192, se75, xRay, focalSpotSize,
pbScenes, exposureTime, filmFocusDistance, filters, heatTreatment, filmBrand,
d4, d5, d7, en, astm, sourceSide, filmSide, automatic, manual, temperature,
x12, x16, x24, x36, x48, x40, suitibleFilm, repairFilm);
}
//Set Equipment Type/Name (From Home Page)
public void setEquipmentType(String value) {
lblEquipment.setText(value);
}
//Set Equipment(From Home Page)
public void setEquipment(REquipment equipment) {
txtUsedDevice.setText(equipment.getUsedDevice());
txtFocalSpotsize.setText(equipment.getFocalSpotSize());
txtExposureTime.setText(equipment.getExposureTime());
txtFilmFocusDistance.setText(equipment.getFilmFocusDistance());
txtPbScenes.setText(equipment.getPbScenes());
}
private void fill() {
// lblTemperature.setText("val");
// txtHeatTreatment.setText("val");
// txtFilters.setText("filters");
// txtX12.setText("12");
// txtX16.setText("12");
// txtX24.setText("12");
// txtX36.setText("12");
// txtX48.setText("12");
// txtX40.setText("12");
// txtSuitibleFilm.setText("Value");
// txtRepairFilm.setText("value");
// txtFilmBrand.setText("Kodak");
}
private String getIr192() {
String res = "0";
if (rbIr192.isSelected()) {
res = "1";
}
return res;
}
private String getSe75() {
String res = "0";
if (rbSe75.isSelected()) {
res = "1";
}
return res;
}
private String getXray() {
String res = "0";
if (rbXRay.isSelected()) {
res = "1";
}
return res;
}
private String getEn() {
String res = "0";
if (rbEn.isSelected()) {
res = "1";
}
return res;
}
private String getAstm() {
String res = "0";
if (rbAstm.isSelected()) {
res = "1";
}
return res;
}
private String getD4() {
String res = "0";
if (rbD4.isSelected()) {
res = "1";
}
return res;
}
private String getD5() {
String res = "0";
if(rbD5.isSelected()){
res = "1";
}
return res;
}
private String getD7() {
String res = "0";
if(rbD7.isSelected()){
res = "1";
}
return res;
}
private String getSourceSide() {
String res = "0";
if(rbSourceSide.isSelected()){
res = "1";
}
return res;
}
private String getFilmSide() {
String res = "0";
if(rbFilmSide.isSelected()){
res = "1";
}
return res;
}
private String getAutomatic() {
String res = "0";
if(rbAutomatic.isSelected()){
res = "1";
}
return res;
}
private String getManuel() {
String res = "0";
if(rbManual.isSelected()){
res = "1";
}
return res;
}
}
| true |
6774820c37a008678016ead265d25808e18aab63 | Java | valenkim/jjn | /src/mapping/GsonView.java | WINDOWS-1252 | 1,905 | 2.453125 | 2 | [] | no_license | package mapping;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import mapping.GsonUtil;
import mappingInfo.*;
import com.google.gson.Gson;
import entity.CompanyInfo;
public class GsonView {
public Item changeAddress(String add){
try{
String url = "http://apis.daum.net/local/geo/addr2coord";
String apiKey = "70406acff0e6212666f566f68392c9e0fd72ffa0";
String address = URLEncoder.encode(add, "utf-8");
String json = GsonUtil.readUrl(url+"?apikey="+apiKey+"&q="+address+"&output=json");
Gson gson = new Gson();
Page page = gson.fromJson(json, Page.class);
Item k = null;
int index =0;
for (Item i : page.channel.item){
System.out.println(i.lat);
System.out.println(i.lng);
System.out.println(i.title);
k = page.channel.item.get(index);
}
return k;
}catch(Exception e){
e.printStackTrace();
}
return null;
}
public CompanyInfo distance(String id, String address, String title, String type, double lat1, double lng1, double lat2, double lng2){
CompanyInfo company = new CompanyInfo();
final double R = 6371;
final double TO_RADIAN = Math.PI/180.0;
double dLat = (lat2-lat1)*TO_RADIAN;
double dLng = (lng2-lng1)*TO_RADIAN;
double a = Math.sin(dLat/2)*Math.sin(dLat/2)+
Math.sin(dLng/2)*Math.sin(dLng/2)*Math.cos(lat2)*Math.cos(lat2);
double c = 2*Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double d = R * c;
if( d < 5){//ݰ 5km
System.out.println(d);
company.id = id;
company.address = address;
company.title = title;
company.type = type;
return company;
}else{
return null;
}
}
}
| true |
0fd9c8270a0e7d5226e6a22ce65a0094e77b4e38 | Java | ezAuton/ezAuton | /Visualizer/src/main/java/com/github/ezauton/visualizer/Main.java | UTF-8 | 145 | 1.695313 | 2 | [
"MIT"
] | permissive | package com.github.ezauton.visualizer;
public class Main {
public static void main(String[] args) {
Visualizer.main(args);
}
}
| true |
becf044f6f4e203f61c30ac7994ddd7bc42a38ff | Java | limaofeng/jfantasy | /website/JavaSource/com.fantasy.website/bean/Template.java | UTF-8 | 3,400 | 2.1875 | 2 | [
"MIT"
] | permissive | package org.jfantasy.website.bean;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.hibernate.annotations.GenericGenerator;
import org.jfantasy.framework.dao.BaseBusEntity;
import org.jfantasy.system.bean.Website;
import org.jfantasy.website.bean.enums.PageType;
import java.util.List;
/**
* 模板
* <p/>
* 用于生成静态页面时的thml模板配置
*
* @author 李茂峰
* @version 1.0
* @since 2013-12-25 上午9:21:05
*/
@Entity
@Table(name = "SWP_TEMPLATE", uniqueConstraints = {@UniqueConstraint(name = "UNIQUE_TEMPLATE", columnNames = {"PATH", "WEBSITE_ID"})})
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler", "dataInferfaces", "webSite"})
public class Template extends BaseBusEntity {
private static final long serialVersionUID = 6516821318292532274L;
@Id
@Column(name = "ID", nullable = false, insertable = true, updatable = false, precision = 22, scale = 0)
@GeneratedValue(generator = "fantasy-sequence")
@GenericGenerator(name = "fantasy-sequence", strategy = "fantasy-sequence")
private Long id;
/**
* 模板名称
*/
@Column(name = "NAME")
private String name;
/**
* 描述
*/
@Column(name = "DESCRIPTION")
private String description;
/**
* 站点
*/
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "WEBSITE_ID")
private Website webSite;
/**
* 模板文件存放的位置
*/
@Lob
@Column(name = "CONTENT")
private String content;
/**
* 数据接口定义
*/
@OneToMany(mappedBy = "template", fetch = FetchType.LAZY)
@OrderBy(value = "id desc")
private List<DataInferface> dataInferfaces;
/**
* 模版路径
*/
@Column(name = "PATH", nullable = false)
private String path;
/**
* 页面类型
*/
@Enumerated(EnumType.STRING)
@Column(name = "PAGE_TYPE")
private PageType pageType;
/**
* Key
*/
@Column(name = "DATA_KEY")
private String dataKey;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<DataInferface> getDataInferfaces() {
return dataInferfaces;
}
public void setDataInferfaces(List<DataInferface> dataInferfaces) {
this.dataInferfaces = dataInferfaces;
}
public Website getWebSite() {
return webSite;
}
public void setWebSite(Website webSite) {
this.webSite = webSite;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public PageType getPageType() {
return pageType;
}
public void setPageType(PageType pageType) {
this.pageType = pageType;
}
public String getDataKey() {
return dataKey;
}
public void setDataKey(String dataKey) {
this.dataKey = dataKey;
}
} | true |
f59d20564d710a7e05b7460de7a0c225aba5e08b | Java | moutainhigh/xcdv2 | /bms-buyer-market-api/src/main/java/com/bms/bymt/validator/TerminalMarketTargetAddValidator.java | UTF-8 | 1,566 | 2.15625 | 2 | [] | no_license | package com.bms.bymt.validator;
import com.bms.bymt.bean.param.TerminalMarketTargetRsParam;
import com.framework.validator.DefaultCustomValidator;
import org.apache.commons.collections.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
/**
* Created by tao_zhifa on 2016/12/15.
*/
public class TerminalMarketTargetAddValidator extends DefaultCustomValidator<ArrayList<TerminalMarketTargetRsParam>> {
@Override
public void validator(ArrayList<TerminalMarketTargetRsParam> marketTargetRsParams) {
if (!CollectionUtils.isEmpty(marketTargetRsParams)) {
List<TerminalMarketTargetRsParam> paramList = marketTargetRsParams;
for (int i = 0, size = paramList.size(); i < size; i++) {
this.validatorMaxLength(i + 1, "BYMT.L00019", paramList.get(i).getTermMarketId(), true, 36);
this.validatorMaxLength(i + 1, "BYMT.L00014", paramList.get(i).getBuyerName(), true, 16);
this.validatorMaxLength(i + 1, "BYMT.L00015", paramList.get(i).getProName(), true, 16);
if (paramList.get(i).getBuyerNum() != null) {
this.validatorInteger(i + 1, "BYMT.L00016", paramList.get(i).getBuyerNum(), true, 2147483647, 0, 5);
}
if (paramList.get(i).getTradeAmount() != null) {
this.validatorDecimal(i + 1, "BYMT.L00017", paramList.get(i).getTradeAmount(), true, 15, 2, 5);
}
}
} else {
this.validatorRequired("error.20002", null);
}
}
}
| true |
635cf4e2037d212d70e79b257ce5c51775e818e9 | Java | stevenmcc/MGS | /src/com/bruno/persist/AddressPersist.java | UTF-8 | 2,737 | 2.640625 | 3 | [] | no_license | package com.bruno.persist;
import com.bruno.pojo.Address;
import com.google.appengine.api.datastore.*;
import java.util.ArrayList;
/**
* Created with IntelliJ IDEA.
* Address: bruno
* Date: 15/06/13
* Time: 14:17
* To change this template use File | Settings | File Templates.
*/
public class AddressPersist {
public static Key putAddress(Address address, Key company){
Address add = getAddress(address.getLine1());
if(add==null){
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
return datastore.put(makeEntity(address, company));
}
else{
return null;
}
}
public static Address getAddress(String addressname){
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Query.Filter addressFilter = new Query.FilterPredicate("addressname",Query.FilterOperator.EQUAL,addressname);
Query q = new Query("Address").setFilter(addressFilter);
PreparedQuery pq = datastore.prepare(q);
for (Entity result : pq.asIterable()) {
return makeAddress(result);
}
return null;
}
public static ArrayList<Address> getAllCompanyAddresss(Key companyname){
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Query q = new Query("Address").setAncestor(companyname).addSort("city", Query.SortDirection.DESCENDING);;
PreparedQuery pq = datastore.prepare(q);
ArrayList<Address> addresses = new ArrayList<Address>();
Address address = null;
for (Entity result : pq.asIterable()) {
address = makeAddress(result);
addresses.add(address);
}
return addresses;
}
private static Entity makeEntity(Address address, Key company){
Entity inaddress = new Entity("Address", company);
inaddress.setProperty("addressname", address.getName());
inaddress.setProperty("line1", address.getLine1());
inaddress.setProperty("line2", address.getLine2());
inaddress.setProperty("city", address.getCity());
inaddress.setProperty("postcode", address.getPostcode());
return inaddress;
}
private static Address makeAddress(Entity entity){
String fname = (String) entity.getProperty("line1");
String lname = (String) entity.getProperty("line2");
String phone = (String) entity.getProperty("city");
String email = (String) entity.getProperty("postcode");
String addressname = (String) entity.getProperty("addressname");
Address address = new Address(fname,lname,phone,email,addressname);
return address;
}
}
| true |
0e5acbcc3e19f0390067ddd493a706c98226609e | Java | LighterFighterNB/KibanaWatcher | /WatcherTest/src/main/java/Client/Client.java | UTF-8 | 3,675 | 2.21875 | 2 | [] | no_license | package Client;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.json.JSONObject;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class Client
{
private Credentials cred;
private RestClient restClient;
private Response response;
private HashMap<String, Object> buildData;
private Map<String, String> params = Collections.emptyMap();
public Client(String hostname, String region, int port, String scheme, String username, String password) throws IOException
{
buildData = new HashMap<>();
buildData.put("hostname", hostname);
buildData.put("region", region);
buildData.put("port", port);
buildData.put("scheme", scheme);
cred = new Credentials(username, password);
RestClientBuilder restClientBuilder = getRestClientBuilder(hostname, region, port, scheme);
restClient = restClientBuilder.build();
response = null;
System.out.println(cred.authorise(this));
}
protected Client(String hostname, String region, int port, String scheme, Credentials cred) throws IOException
{
buildData = new HashMap<>();
buildData.put("hostname", hostname);
buildData.put("region", region);
buildData.put("port", port);
buildData.put("scheme", scheme);
this.cred = cred;
RestClientBuilder restClientBuilder = getRestClientBuilder(hostname, region, port, scheme);
restClient = restClientBuilder.build();
response = null;
System.out.println(this.cred.authorise(this));
}
public void close() throws IOException
{
restClient.close();
}
private RestClientBuilder getRestClientBuilder(String hostname, String region, int port, String scheme)
{
return RestClient.builder(new HttpHost(hostname + "." + region + ".aws.found.io", port, scheme))
.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(cred.getCredentials()));
}
public HashMap<String, Object> getBuildData()
{
HashMap<String, Object> buildDataExCred = new HashMap<>();
buildDataExCred.put("hostname", buildData.get("hostname"));
buildDataExCred.put("region", buildData.get("region"));
buildDataExCred.put("port", buildData.get("port"));
buildDataExCred.put("scheme", buildData.get("scheme"));
return buildDataExCred;
}
public JSONObject preformRequest(String method, String endpoint) throws IOException
{
response = restClient.performRequest(method, endpoint);
return new JSONObject(EntityUtils.toString(response.getEntity()));
}
public JSONObject preformParmRequest(String method, String endpoint, HttpEntity entity) throws IOException
{
response = restClient.performRequest(method, endpoint, params, entity);
return new JSONObject(EntityUtils.toString(response.getEntity()));
}
protected String getHostname()
{
return buildData.get("hostname").toString();
}
protected String getRegion()
{
return buildData.get("region").toString();
}
protected int getPort()
{
return (int)buildData.get("port");
}
protected String getScheme()
{
return buildData.get("scheme").toString();
}
protected Credentials getCred()
{
return cred;
}
}
| true |
4407edce9da85a86c8b96fe259de030a6da90610 | Java | bekiristek/java-coding-samples | /src/com/bekiristek/rea/FindIndex.java | UTF-8 | 901 | 3.65625 | 4 | [] | no_license | package com.bekiristek.rea;
/*
@Author= bekir istek
@Date= 15.07.2021
Question-3 ==> You are given an array of integers.
Your job is to take that array and find an index, n, where the sum of the integers to the left of n is equal to the sum of the integers to the right of n.
If there is no such index that would make this happen, return -1.
*/
public class FindIndex {
public static int findEvenIndex(int arr[]) {
int [] prefixSum = new int[arr.length];
prefixSum[0] = arr[0];
for (int i = 1; i <arr.length ; i++)
prefixSum[i] = prefixSum[i - 1] + arr[i];
int[] suffixSum = new int[arr.length];
suffixSum[arr.length - 1] = arr[arr.length - 1];
for (int i = arr.length - 2; i >= 0; i--)
suffixSum[i] = suffixSum[i + 1] + arr[i];
for (int i = 1; i < arr.length - 1; i++) {
if (prefixSum[i] == suffixSum[i]) {
return i;
}
}
return -1;
}
}
| true |
db65fe9f8cc63ef5ce688fdff6221dcd1b7b4d35 | Java | robertwatkins/playground-kathleen | /src/tictactoe.java | UTF-8 | 4,120 | 3.59375 | 4 | [] | no_license | import java.util.Scanner;
class tictactoe {
static String[][] gameBoard = new String[3][3];
static boolean debug = true;
static Scanner in = new Scanner(System.in);
static String currentPlayer = "";
private static void initializeGameBoard() {
// set 2d array to sequence of numbers.
// these numbers will be used to enter values in the
// console for each player.
int tempInt = 0;
for (int i=0;i<3;i++){
for (int j=0;j<3;j++){
tempInt = (j+1)+(i*3);
gameBoard[j][i] = String.valueOf(tempInt);
}
}
}
private static void printGameBoard() {
// output the current state of the board to the console.
for (int i=0;i<3;i++){
for (int j=0;j<3;j++){
System.out.print(" "+gameBoard[j][i]+" ");
if (j<2) {
System.out.print("|");
}
}
System.out.println();
if (i<2) {
System.out.println("---+---+---");
}
}
}
private static boolean isAWinner () {
//This is where we will write code to determine if there is a winner
return false;
}
private static boolean isADraw () {
//assume the game is a draw, if any square is not an 'X' or an 'O', then it is not over
//This method assumes no winner is found
boolean result=true;
for (int i=0;i<3;i++){
for (int j=0;j<3;j++){
if ((!gameBoard[j][i].equals("X") ) && (!gameBoard[j][i].equals("O"))){
result=false;
}
if (debug) {
System.out.print(", ("+j+"," + i + ")="+gameBoard[j][i]+":"+result);
}
}
}
if (debug){
System.out.println();
}
return result;
}
private static void takeTurn(String player){
//read input from the console and convert it to an integer
//replace the corresponding square of the board with the player's mark
//don't let a user put there mark where someone else already has one (that would be cheating) :)
System.out.print("Enter a number player "+player+": ");
String locationString="0";
//the program will crash here if a user presses 'enter' without a value.
//TODO-fix crashing bug :)
locationString = in.nextLine();
if (locationString.length()==0){
takeTurn(player);
}
if (debug) {System.out.println("read: "+locationString+ ", size: "+ locationString.length()); }
int location = Integer.parseInt(locationString);
if (debug) { System.out.println("user selected :"+location); }
if (location <1 || location >9 ){
System.out.println("That is not a valid number, please try again.5");
takeTurn(player);
}
else if ((gameBoard[(location-1) % 3][(location-1) / 3].equals("X")) || (gameBoard[(location-1) % 3][(location-1) / 3].equals("O"))){
System.out.println("That space is taken, please enter a value that is not alreay taken");
takeTurn(player);
return;
} else {
gameBoard[(location-1) % 3][(location-1) / 3] = player;
return;
}
}
private static String getWinner() {
//when we have a winner, find that winner
//TODO: need to write code. This is just a stub
return "-";
}
private static String switchPlayer(String player) {
//given the mark of the current player, return the mark of the other player.
if (player=="X") {
player = "O";
} else {
player ="X";
}
return player;
}
private static void printInstructions() {
//These could be longer :)
System.out.println("Select the number of the square you want to play and press [ENTER]");
return;
}
private static void cleanUp(){
//stop listening for input from the console.
in.close();
}
public static void main(String[] args) {
initializeGameBoard();
printInstructions();
printGameBoard();
String currentPlayer="X";
while (!isAWinner() && !isADraw()){
currentPlayer = switchPlayer(currentPlayer);
takeTurn(currentPlayer);
printGameBoard();
}
if (isAWinner()){
System.out.println("Winner:"+getWinner());
} else {
System.out.println("The game is a draw");
}
cleanUp();
}
}
| true |
a6c20506ca86acedad486adf51cd7dc18674c3b1 | Java | zeezov/mavenprojectz | /src/test/java/com/cybertek/tests/TestingPDFDemo.java | UTF-8 | 647 | 2.53125 | 3 | [] | no_license | package com.cybertek.tests;
import com.codeborne.pdftest.PDF;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.io.File;
public class TestingPDFDemo {
// for this test we have new dependency
@Test
public void pdfTest() {
File file = new File("/Users/nshaazizov/Documents/About Stacks.pdf");
// PDF file represents our pdf file, it is created using the file object
PDF pdf = new PDF(file);
System.out.println(pdf.title);
System.out.println(pdf.numberOfPages);
System.out.println(pdf.text);
Assert.assertTrue(pdf.text.contains("the"));
}
}
| true |
bf01ce2489825e8e71b95845b92da4e737b6b1cd | Java | zhongxingyu/Seer | /Diff-Raw-Data/2/2_12f608b697269a6313e074d2aa4ec15ccdd8c468/OracleEnvironment/2_12f608b697269a6313e074d2aa4ec15ccdd8c468_OracleEnvironment_s.java | UTF-8 | 13,356 | 2.3125 | 2 | [] | no_license | package dbfit.environment;
import java.math.BigDecimal;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import oracle.jdbc.driver.OracleTypes;
import oracle.jdbc.rowset.OracleCachedRowSet;
import dbfit.api.AbstractDbEnvironment;
import dbfit.util.*;
public class OracleEnvironment extends AbstractDbEnvironment {
private static String SKIP_ORACLE_SYNONYMS="SKIPORACLESYNONYMS";
public static class OracleTimestampParser{
public static Object parse(String s) throws Exception{
return new oracle.sql.TIMESTAMP((java.sql.Timestamp)SqlTimestampParseDelegate.parse(s));
}
}
public static class OracleTimestampNormaliser implements TypeNormaliser{
public Object normalise(Object o) throws SQLException {
if (o ==null) return null;
if (! (o instanceof oracle.sql.TIMESTAMP)){
throw new UnsupportedOperationException("OracleTimestampNormaliser cannot work with " + o.getClass());
}
oracle.sql.TIMESTAMP ts=(oracle.sql.TIMESTAMP) o;
return ts.timestampValue();
}
}
public static class OracleDateNormaliser implements TypeNormaliser{
public Object normalise(Object o) throws SQLException {
if (o ==null) return null;
if (! (o instanceof oracle.sql.DATE)){
throw new UnsupportedOperationException("OracleDateNormaliser cannot work with " + o.getClass());
}
oracle.sql.DATE ts=(oracle.sql.DATE) o;
return ts.timestampValue();
}
}
// transparently convert outcoming sql date into sql timestamps
public static class SqlDateNormaliser implements TypeNormaliser{
public Object normalise(Object o) throws SQLException {
if (o ==null) return null;
if (! (o instanceof java.sql.Date)){
throw new UnsupportedOperationException("SqlDateNormaliser cannot work with " + o.getClass());
}
java.sql.Date ts=(java.sql.Date) o;
return new java.sql.Timestamp(ts.getTime());
}
}
public static class OracleClobNormaliser implements TypeNormaliser{
private static final int MAX_CLOB_LENGTH=10000;
public Object normalise(Object o) throws SQLException {
if (o ==null) return null;
if (! (o instanceof oracle.sql.CLOB)){
throw new UnsupportedOperationException("OracleClobNormaliser cannot work with " + o.getClass());
}
oracle.sql.CLOB clob=(oracle.sql.CLOB) o;
if (clob.length()>MAX_CLOB_LENGTH) throw new UnsupportedOperationException("Clobs larger than "+MAX_CLOB_LENGTH+"bytes are not supported by DBFIT");
char[] buffer=new char[MAX_CLOB_LENGTH];
int total=clob.getChars(1, MAX_CLOB_LENGTH, buffer);
return String.valueOf(buffer, 0,total);
}
}
public static class OracleRefNormaliser implements TypeNormaliser{
public Object normalise(Object o) throws SQLException{
if (o==null) return null;
if (!(o instanceof ResultSet))
throw new UnsupportedOperationException("OracleRefNormaliser cannot work on "+o.getClass());
ResultSet rs=(ResultSet) o;
OracleCachedRowSet ocrs=new OracleCachedRowSet();
ocrs.populate(rs);
return ocrs;
}
}
public OracleEnvironment(){
//TypeAdapter.registerParseDelegate(oracle.sql.TIMESTAMP.class, OracleTimestampParser.class);
TypeNormaliserFactory.setNormaliser(oracle.sql.TIMESTAMP.class,new OracleTimestampNormaliser());
TypeNormaliserFactory.setNormaliser(oracle.sql.DATE.class,new OracleDateNormaliser());
TypeNormaliserFactory.setNormaliser(oracle.sql.CLOB.class,new OracleClobNormaliser());
TypeNormaliserFactory.setNormaliser(java.sql.Date.class,new SqlDateNormaliser());
try{
TypeNormaliserFactory.setNormaliser(Class.forName("oracle.jdbc.driver.OracleResultSetImpl"),new OracleRefNormaliser());
}
catch (Exception e){
throw new Error("Cannot initialise oracle rowset",e);
}
}
public boolean supportsOuputOnInsert(){
return true;
}
protected String getDriverClassName() {
return "oracle.jdbc.OracleDriver";
}
protected String getConnectionString(String dataSource)
{
return "jdbc:oracle:thin:@"+dataSource;
}
// for oracle, data source has to be host:port
protected String getConnectionString(String dataSource, String databaseName)
{
if (dataSource.indexOf(":")==-1) throw new UnsupportedOperationException("data source should be in host:port format - "+dataSource +" specified");
return "jdbc:oracle:thin:@"+dataSource+":"+databaseName;
}
private static Pattern paramsNames = Pattern.compile(":([A-Za-z0-9_]+)");
public Pattern getParameterPattern(){
return paramsNames;
}
public Map<String, DbParameterAccessor> getAllProcedureParameters(String procName) throws SQLException
{
String[] qualifiers = NameNormaliser.normaliseName(procName).split("\\.");
String cols=" argument_name, data_type, data_length, IN_OUT, sequence ";
String qry = "select "+ cols+" from all_arguments where data_level=0 and ";
if (qualifiers.length== 3) {
qry += " owner=? and package_name=? and object_name=? ";
} else if (qualifiers.length== 2) {
qry +=
" ((owner=? and package_name is null and object_name=?) or "+
" (owner=user and package_name=? and object_name=?))";
} else {
qry += " (owner=user and package_name is null and object_name=?)";
}
// map to public synonyms also
if (qualifiers.length<3 && (!Options.is(SKIP_ORACLE_SYNONYMS))){
qry+=" union all "+
" select " + cols +" from all_arguments, all_synonyms "+
" where data_level=0 and all_synonyms.owner='PUBLIC' and all_arguments.owner=table_owner and ";
if (qualifiers.length==2){ // package
qry+=" package_name=table_name and synonym_name=? and object_name=? ";
}
else {
qry+=" package_name is null and object_name=table_name and synonym_name=? ";
}
}
qry+=" order by sequence ";
if (qualifiers.length==2){
String[] newQualifiers=new String[6];
newQualifiers[0]=qualifiers[0];
newQualifiers[1]=qualifiers[1];
newQualifiers[2]=qualifiers[0];
newQualifiers[3]=qualifiers[1];
newQualifiers[4]=qualifiers[0];
newQualifiers[5]=qualifiers[1];
qualifiers=newQualifiers;
}
else if (qualifiers.length==1){
String[] newQualifiers=new String[2];
newQualifiers[0]=qualifiers[0];
newQualifiers[1]=qualifiers[0];
qualifiers=newQualifiers;
}
return readIntoParams(qualifiers, qry);
}
public Map<String, DbParameterAccessor> getAllColumns(String tableOrViewName) throws SQLException
{
String[] qualifiers = NameNormaliser.normaliseName(tableOrViewName).split("\\.");
String qry = " select column_name, data_type, data_length, " +
" 'IN' as direction, column_id from all_tab_columns where ";
if (qualifiers.length == 2) {
qry += " owner=? and table_name=? ";
} else {
qry += " (owner=user and table_name=?)";
}
qry+=" order by column_id ";
return readIntoParams(qualifiers, qry);
}
private Map<String, DbParameterAccessor> readIntoParams(String[] queryParameters, String query)
throws SQLException{
Log.log("preparing call "+query ,queryParameters);
CallableStatement dc=currentConnection.prepareCall(query);
Log.log("setting parameters");
for (int i = 0; i < queryParameters.length; i++) {
dc.setString(i+1,queryParameters[i].toUpperCase() );
}
Log.log("executing query");
ResultSet rs=dc.executeQuery();
Map<String, DbParameterAccessor>
allParams = new HashMap<String, DbParameterAccessor>();
int position=0;
Log.log("reading out");
while (rs.next()) {
String paramName=rs.getString(1);
if (paramName==null) paramName="";
String dataType = rs.getString(2);
// int length = rs.getInt(3);
String direction = rs.getString(4);
int paramDirection;
if (paramName.trim().length()==0)
paramDirection=DbParameterAccessor.RETURN_VALUE;
else
paramDirection=getParameterDirection(direction);
// Class javaType=getJavaClass(dataType);
Log.log("read out "+paramName+" of "+ dataType);
DbParameterAccessor dbp=new DbParameterAccessor (paramName,paramDirection,
getSqlType(dataType), getJavaClass(dataType),
paramDirection==DbParameterAccessor.RETURN_VALUE?
-1:position++);
allParams.put(NameNormaliser.normaliseName(paramName),
dbp);
}
return allParams;
}
// List interface has sequential search, so using list instead of array to map types
private static List<String> stringTypes = Arrays.asList(new String[] { "VARCHAR", "VARCHAR2", "NVARCHAR2", "CHAR", "NCHAR", "CLOB","ROWID" });
private static List<String> decimalTypes = Arrays.asList(new String[] { "BINARY_INTEGER","NUMBER","FLOAT" });
private static List<String> dateTypes = Arrays.asList(new String[] { });
private static List<String> timestampTypes=Arrays.asList(new String[]{"DATE","TIMESTAMP"});
private static List<String> refCursorTypes = Arrays.asList(new String[] { "REF" });
private static String normaliseTypeName(String dataType) {
dataType = dataType.toUpperCase().trim();
int idx = dataType.indexOf(" ");
if (idx >= 0) dataType = dataType.substring(0, idx);
idx = dataType.indexOf("(");
if (idx >= 0) dataType = dataType.substring(0, idx);
return dataType;
}
private static int getSqlType(String dataType) {
//todo:strip everything from first blank
dataType = normaliseTypeName(dataType);
if (stringTypes.contains(dataType) ) return java.sql.Types.VARCHAR;
if (decimalTypes.contains(dataType) )return java.sql.Types.NUMERIC;
if (dateTypes.contains(dataType) ) return java.sql.Types.DATE;
if (refCursorTypes.contains(dataType) ) return OracleTypes.CURSOR;
if (timestampTypes.contains(dataType)) return java.sql.Types.TIMESTAMP;
throw new UnsupportedOperationException("Type " + dataType + " is not supported");
}
public Class<?> getJavaClass(String dataType) {
dataType = normaliseTypeName(dataType);
if (stringTypes.contains(dataType) ) return String.class;
if (decimalTypes.contains(dataType) )return BigDecimal.class;
if (dateTypes.contains(dataType) ) return java.sql.Date.class;
if (refCursorTypes.contains(dataType) ) return ResultSet.class;
if (timestampTypes.contains(dataType)) return java.sql.Timestamp.class;
throw new UnsupportedOperationException("Type " + dataType + " is not supported");
}
private static int getParameterDirection(String direction) {
if ("IN".equals(direction)) return DbParameterAccessor.INPUT;
if ("OUT".equals(direction)) return DbParameterAccessor.OUTPUT;
if ("IN/OUT".equals(direction)) return DbParameterAccessor.INPUT_OUTPUT;
//todo return val
throw new UnsupportedOperationException("Direction " + direction + " is not supported");
}
public String buildInsertCommand(String tableName, DbParameterAccessor[] accessors)
{
Log.log("buiding insert command for "+tableName);
/* oracle jdbc interface with callablestatement has problems with returning into...
* http://forums.oracle.com/forums/thread.jspa?threadID=438204&tstart=0&messageID=1702717
* so begin/end block has to be built around it
*/
StringBuilder sb = new StringBuilder("begin insert into ");
sb.append(tableName).append("(");
String comma = "";
String retComma = "";
StringBuilder values = new StringBuilder();
StringBuilder retNames = new StringBuilder();
StringBuilder retValues = new StringBuilder();
for (DbParameterAccessor accessor : accessors)
{
if (accessor.getDirection()==DbParameterAccessor.INPUT)
{
sb.append(comma);
values.append(comma);
sb.append(accessor.getName());
//values.append(":").append(accessor.getName());
values.append("?");
comma = ",";
}
else
{
retNames.append(retComma);
retValues.append(retComma);
retNames.append(accessor.getName());
//retValues.append(":").append(accessor.getName());
retValues.append("?");
retComma = ",";
}
}
sb.append(") values (");
sb.append(values);
sb.append(")");
if (retValues.length() > 0)
{
sb.append(" returning ").append(retNames).append(" into ").append(retValues);
}
sb.append("; end;");
Log.log("built "+sb.toString());
return sb.toString();
}
@Override
public DbParameterAccessor createAutogeneratedPrimaryKeyAccessor(
DbParameterAccessor template) {
DbParameterAccessor accessor2=new DbParameterAccessor(template);
accessor2.setDirection(DbParameterAccessor.OUTPUT);
return accessor2;
}
@Override
public PreparedStatement buildInsertPreparedStatement(String tableName,
DbParameterAccessor[] accessors) throws SQLException {
return getConnection().prepareCall(buildInsertCommand(tableName, accessors));
}
}
| true |
e86452727bed747f69c7af6addaf066ab60bd417 | Java | programmatix/txn_client | /src/main/java/com/couchbase/sdkdclient/cluster/actions/RebalanceOutAction.java | UTF-8 | 1,155 | 1.929688 | 2 | [] | no_license | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.couchbase.sdkdclient.cluster.actions;
import com.couchbase.cbadmin.client.RestApiException;
import com.couchbase.sdkdclient.cluster.CBCluster;
import com.couchbase.sdkdclient.cluster.NodeHost;
import com.couchbase.sdkdclient.cluster.NodelistBuilder;
import java.util.Collection;
import java.util.concurrent.Future;
/**
*
* @author mnunberg
*/
public class RebalanceOutAction implements RebalanceAction {
private Collection<NodeHost> removedNodes;
String services;
public RebalanceOutAction(String service) {
this.services = service;
}
@Override
public void setup(NodelistBuilder nlb, RebalanceConfig config) {
removedNodes = nlb.reserveForRemoval(config.getNumNodes(), config.shouldUseEpt(), false, services);
}
@Override
public Future<Boolean> start(CBCluster cluster) throws RestApiException {
return cluster.removeAndRebalance(removedNodes);
}
@Override
public Future<Boolean> undo(CBCluster cluster) throws RestApiException {
return cluster.addAndRebalance(removedNodes, services);
}
} | true |
08007ade3bfd12474b11c63c9a0d2c67dda5df4a | Java | rickydomingos97/alura | /bytebank-composto/exercicios/Empresa.java | UTF-8 | 89 | 1.734375 | 2 | [] | no_license | public class Empresa {
String razaoSocial;
String cnpj;
Endereco endereco;
}
| true |
f8bd1f17a89ad30eeafb2e1ff0d293a89382eb62 | Java | Limtov/course_planner | /SIAUKO_ANDREI/CoursePlanner/API/src/main/java/com/andrei/api/transactionDao/ICourseTransactionDao.java | UTF-8 | 474 | 1.976563 | 2 | [] | no_license | package com.andrei.api.transactionDao;
import java.util.Date;
import java.util.List;
import com.andrei.entity.Course;
public interface ICourseTransactionDao extends ITransactionDao<Course> {
public void cloneCourse(int idCourse);
public List<Course> getCoursesAfterDate(Date date);
public List<Course> getCoursesIntervalInPast(Date startDate, Date endDate);
public List<Course> getActiveCourses();
/* public int getNumberOfStudentsInCourse(int idCourse); */
}
| true |
68a70c8ed3ed1576df53dc7efdf9f3af43a9c8b9 | Java | mdfraz13/workspace | /AlgorithimsProjects/src/com/algorithims/programs/problems/topicwise/Stringbased/ReverseStringWithOutSpecialCharacter.java | UTF-8 | 866 | 3.640625 | 4 | [] | no_license | package com.algorithims.programs.problems.topicwise.Stringbased;
import java.util.Arrays;
public class ReverseStringWithOutSpecialCharacter {
public static void main(String[] args) {
String input1 = "a,b$c"; // c,b$a
String input2 = "a!!!b.c.d,e'f,ghi"; // i!!!hg.f.e.d,...
reverse(input1);
reverse(input2);
}
private static String reverse(String input) {
String reversed = "";
char[] ip1 = input.toCharArray();
int l = 0,r=ip1.length-1;
while(l < r) {
if(!isAlphabet(ip1[l])) {
l++;
}else if(!isAlphabet(ip1[l])) {
r--;
}else {
char tmp = ip1[r];
ip1[r] = ip1[l];
ip1[l] = tmp;
l++;
r--;
}
}
reversed = Arrays.toString(ip1);
System.out.println(reversed);
return reversed;
}
private static boolean isAlphabet(char x) {
return (x >='a' && x <='z') || (x >='A' && x <='Z');
}
}
| true |
b683f5c9019f28d75e35bd63583657e506548a20 | Java | surajraje096/Dev_SuRAj_BDD | /Easyshoppy/qa/TestRunner/TestRunner.java | UTF-8 | 681 | 1.539063 | 2 | [] | no_license | package Com.Easyshoppy.qa.TestRunner;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
@RunWith(Cucumber.class)
@CucumberOptions(
features="D:\\shain\\Class_Lecture_49_CuCumber_BDD_3_BackGround\\src\\test\\java\\Com\\Easyshoppy\\qa\\FeatureFile\\Allfeature.feature",
glue="Com.Easyshoppy.qa.StepDefinition",
plugin={"pretty","html:target/cucumber","json:target/cucumber.json","junit:target/cukes.xml"})
//glue="StepDefinitions",tags="@RegTest",
//monochrome=true,
//plugin={"pretty","html:target/cucumber","json:target/cucumber.json","junit:target/cukes.xml"})
public class TestRunner {
}
| true |
a3844bf6ee56917f7ddc800c5eca0844d76936d4 | Java | haimingzhao1/javaWebBase | /bookmanagerlx/src/com/bm/beans/ReaderInfo.java | UTF-8 | 1,707 | 2.609375 | 3 | [] | no_license | package com.bm.beans;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ReaderInfo {
private Integer readerid;
private String name;
private String sex;
private Date birth;
private String address;
private String phone;
public Integer getReaderid() {
return readerid;
}
public void setReaderid(Integer readerid) {
this.readerid = readerid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirth() {
return birth;
}
public void setBirth(String birth) {
try {
if (birth!=null || !(birth.isEmpty())) {
this.birth = new SimpleDateFormat("yyyy-MM-dd").parse(birth);
}
} catch (ParseException e) {
e.printStackTrace();
}
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public ReaderInfo(Integer readerid, String name, String sex, String birth,
String address, String phone) {
this.readerid = readerid;
this.name = name;
this.sex = sex;
try {
this.birth = new SimpleDateFormat("yyyy-MM-dd").parse(birth);
} catch (ParseException e) {
e.printStackTrace();
}
this.address = address;
this.phone = phone;
}
public ReaderInfo() {
}
@Override
public String toString() {
return "ReaderInfo [readerid=" + readerid + ", name=" + name + ", sex="
+ sex + ", birth=" + birth + ", address=" + address
+ ", phone=" + phone + "]";
}
}
| true |
57e866a60ddaf0d21ee0b0d4cb666fa560f5e842 | Java | RadRedPanda/RTTBFG | /src/com/company/Main.java | UTF-8 | 158 | 1.625 | 2 | [] | no_license | package com.company;
public class Main {
public static void main(String[] args) {
// write your code here
System.out.println("HI");
}
}
| true |
c6348bd881d683e7b0eb56a67d9219599a9dbe1d | Java | Avangarde2225/SeleniumWorks | /src/day6/FindByXPathSolution.java | UTF-8 | 1,440 | 2.8125 | 3 | [] | no_license | package day6;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.List;
public class FindByXPathSolution {
// https://www.seleniumeasy.com/test/input-form-demo.html
// fill in the form using xpath by attribute,
// by contains(),
// by index,
// also by child
public static void main(String[] args) {
System.setProperty( "webdriver.chrome.driver", "C:\\Users\\suler\\Desktop\\Selenium\\chromedriver\\chromedriver.exe" );
WebDriver driver = new ChromeDriver();
driver.get( "https://www.seleniumeasy.com/test/input-form-demo.html" );
WebElement email = driver.findElement( By.xpath( "//*[@placeholder='E-Mail Address']" ) );
email.sendKeys( "s.k.daulet@gmail.com" );
// by contains
List<WebElement> list1 = driver.findElements( By.xpath( "//*[contains(@name,'name')]" ) );
for(WebElement element : list1) {
element.sendKeys( "Name" );
}
// using index
WebElement phone = driver.findElement( By.xpath( "//div[@class='form-group'][4]//input[@type='text']" ) );
phone.sendKeys( "6545132468453135" );
// using child
WebElement address = driver.findElement( By.xpath( "//div[@class='form-group'][5]//child::input" ) );
address.sendKeys( "My Address" );
driver.quit();
}
}
| true |
27beca7e389a983ee6697c23090b0d59635fa02d | Java | bayrktlihn/unit-test-examples | /src/main/java/com/bayrktlihn/courserecord/application/StudentServiceImpl.java | UTF-8 | 2,585 | 2.53125 | 3 | [] | no_license | package com.bayrktlihn.courserecord.application;
import com.bayrktlihn.courserecord.model.Course;
import com.bayrktlihn.courserecord.model.Lecturer;
import com.bayrktlihn.courserecord.model.LecturerCourseRecord;
import com.bayrktlihn.courserecord.model.Semester;
import com.bayrktlihn.courserecord.model.Student;
import com.bayrktlihn.courserecord.model.StudentCourseRecord;
import com.bayrktlihn.courserecord.model.StudentRepository;
import java.math.BigDecimal;
import java.util.Optional;
public class StudentServiceImpl implements StudentService {
private final CourseService courseService;
private final LecturerService lecturerService;
private final StudentRepository studentRepository;
public StudentServiceImpl(CourseService courseService, LecturerService lecturerService, StudentRepository studentRepository) {
this.courseService = courseService;
this.lecturerService = lecturerService;
this.studentRepository = studentRepository;
}
@Override
public void addCourse(String studentId, Course course) {
addCourse(studentId, course, new Semester());
}
@Override
public void addCourse(String studentId, Course course, Semester semester) {
final Student student = studentRepository.findById(studentId)
.orElseThrow(() -> new IllegalArgumentException(String.format("Can't find a student with id<%s>", studentId)));
final Course courseFromRepo = courseService.findCourse(course)
.orElseThrow(() -> new IllegalArgumentException(String.format("Can't find a course with info<%s>", course)));
final Lecturer lecturer = lecturerService.findLecturer(courseFromRepo, semester)
.orElseThrow(() -> new IllegalArgumentException(String.format("Can't find a lecturer with info<%s>", course)));
final LecturerCourseRecord lecturerCourseRecord = lecturer.lecturerCourseRecord(courseFromRepo, semester);
student.addCourse(lecturerCourseRecord);
studentRepository.save(student);
}
@Override
public void dropCourse(String studentId, Course course) {
}
@Override
public void addGrade(String studentId, Course course, StudentCourseRecord.Grade grade) {
}
@Override
public boolean isTakeCourse(String studentId, Course course) {
return false;
}
@Override
public BigDecimal gpa(String studentId) {
return null;
}
@Override
public Optional<Student> findStudent(String studentId) {
return studentRepository.findById(studentId);
}
}
| true |
03b164f0c3609db3ff7774ab6157f6cdf74f9e2b | Java | gcc2ge/ForgE | /editor/src/macbury/forge/editor/undo_redo/actions/CursorChangeable.java | UTF-8 | 995 | 2.125 | 2 | [
"MIT"
] | permissive | package macbury.forge.editor.undo_redo.actions;
import com.badlogic.gdx.math.collision.BoundingBox;
import macbury.forge.blocks.Block;
import macbury.forge.editor.selection.AbstractSelection;
import macbury.forge.editor.selection.SelectType;
import macbury.forge.editor.undo_redo.Changeable;
import macbury.forge.utils.Vector3i;
/**
* Created by macbury on 03.11.14.
*/
public abstract class CursorChangeable extends Changeable {
protected Block.Side alignToSide;
protected SelectType selectType;
protected Vector3i from;
protected Vector3i to;
protected BoundingBox applyBox;
public CursorChangeable(AbstractSelection selection) {
this.from = new Vector3i();
this.to = new Vector3i();
applyBox = new BoundingBox();
this.selectType = selection.getSelectType();
this.from.set(selection.getStartPosition());
this.to.set(selection.getEndPostion());
applyBox.set(selection.getBoundingBox());
this.alignToSide = selection.getAlginSide();
}
}
| true |
3734841f0e6441cc9971c1a807a9b96ad69b10c3 | Java | zgq346712481/macaca-reporter-java-plugin | /src/main/java/com/macacajs/reporter/MacacaTestExecutionListener.java | UTF-8 | 18,754 | 1.90625 | 2 | [
"MIT"
] | permissive | package com.macacajs.reporter;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.macacajs.reporter.models.*;
import lombok.SneakyThrows;
import org.junit.platform.engine.TestExecutionResult;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.TestPlan;
import java.io.*;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;
/**
* @author niaoshuai & shixing
*/
public class MacacaTestExecutionListener implements TestExecutionListener {
MacacaReportModel macacaReportModel;
StatsDataModel planStats;
SuitesDataModel planSuites;
CurrentModle currentModle;
CaseModel caseModel;
List<CaseModel> caseModels;
List<SuitesDataModel> testClassSuitesList ;
SuitesDataModel testClassSuites;
CtxModel testClassCtxModel;
/**
* 测试类对象的列表与对象
*/
List<SuitesDataModel> caseSuitesList ;
SuitesDataModel caseSuites;
/**
* 前置与后置
*/
EachRunnableModel eachRunnable;
/**
* 测试对象
*/
TestsModel tests;
String testPlanId,
parentId,
childId,
planName = getPlanName(),
logo = getLogo();
int passes = 0,
failures = 0,
skipped = 0;
LocalDateTime testStar, testEnd,
caseSuitesStar , caseSuitesEnd;
List<TestsModel> testsModelList;
List<TestsModel> passTestModleList ;
List<TestsModel> failuresTestModleList ;
/**
* 开始执行测试计划
* @param testPlan
*/
@Override
public void testPlanExecutionStarted(TestPlan testPlan) {
//计划开始
planStats = new StatsDataModel();
planSuites = new SuitesDataModel();
currentModle = new CurrentModle();
caseModels = new ArrayList<>();
planStats.setStart(LocalDateTime.now());
Set<TestIdentifier> setRoots = testPlan.getRoots();
for(TestIdentifier ti : setRoots){
testPlanId = ti.getUniqueId();
if(!testPlanId.isEmpty()){
return;
}
}
}
/**
* 用例执行
*
* @param testIdentifier
*/
@Override
public void executionStarted(TestIdentifier testIdentifier) {
String uuqueid = testIdentifier.getUniqueId();
Optional<String> parentOpt = testIdentifier.getParentId();
String pid = null;
if(parentOpt.isPresent()){
pid = parentOpt.get();
}
if (pid == null) {
/*
* 共执行两次 , 开始一次 ,结束一次
* 初始化 测试套件 对象 列表
*/
if(testClassSuitesList==null){
testClassSuitesList = new ArrayList<>();
testClassSuites = new SuitesDataModel();
caseSuitesList = new ArrayList<>();
testClassCtxModel = new CtxModel();
}else {
testClassSuitesList.add(testClassSuites);
String date = new SimpleDateFormat("yyyy_MM_dd").format(new Date());
testClassSuites.setTitle(planName);
testClassSuites.setFile(date+"-"+planName);
testClassSuites.setFullFile(testIdentifier.getLegacyReportingName());
testClassSuites.setParent(parentId);
testClassSuites.setUuid(uuqueid);
}
} else if (testPlanId.equals(pid)) {
/*
* 写入berfor
* 初始化case对象 列表
*/
testsModelList = new ArrayList<>();
passTestModleList = new ArrayList<>();
failuresTestModleList = new ArrayList<>();
caseSuites = new SuitesDataModel();
caseSuitesStar = LocalDateTime.now();
parentId = uuqueid;
//写入berfor
eachRunnable = new EachRunnableModel();
List<EachRunnableModel> eachRunnableList = new ArrayList<>();
eachRunnable.setTitle(testIdentifier.getDisplayName() + testIdentifier.getLegacyReportingName());
eachRunnable.setBody(testIdentifier.getSource().toString());
eachRunnable.setParent(this.getClass().getSimpleName());
eachRunnableList.add(eachRunnable);
//添加测试类的before
eachRunnable.setAsync((long) 0);
eachRunnable.setSync(true);
eachRunnable.setTimeout((long) 2000);
eachRunnable.setSlow((long) 75);
eachRunnable.setEnableTimeouts(true);
eachRunnable.setTimedOut(true);
eachRunnable.setTrace(new Object());
eachRunnable.setRetries((long) -1);
eachRunnable.setCurrentRetry((long) 0);
eachRunnable.setPending(false);
eachRunnable.setType(testIdentifier.getType().name());
eachRunnable.setParent(parentId);
eachRunnable.setCtx(new CtxModel());
eachRunnable.setEvents(new EventsModel());
eachRunnable.setEventsCount((long) 1);
eachRunnable.setTimer(new RunnableTimer());
eachRunnable.setDuration((long) 0);
eachRunnable.setErr(null);
caseSuites.setBeforeAll(new ArrayList<>());
caseSuites.setBeforeEach(eachRunnableList);
CtxModel caseSuitesCtx = new CtxModel();
caseSuitesCtx.setRunnable(eachRunnable);
caseSuitesCtx.setTest(eachRunnable);
caseSuites.setCtx(caseSuitesCtx);
/*
* 初始化测试类的 用例列表
* 填充ctc
*/
testClassCtxModel.setRunnable(new EachRunnableModel());
testClassCtxModel.setTest(new EachRunnableModel());
//填充classSuites
testClassSuites.setCtx(testClassCtxModel);
testClassSuites.setTests(new ArrayList<>());
testClassSuites.setPending(new ArrayList<>());
testClassSuites.setBeforeAll(new ArrayList<>());
testClassSuites.setBeforeEach(new ArrayList<>());
} else if (parentId.equals(pid)) {
//写入case
testStar = LocalDateTime.now();
childId = uuqueid;
tests = new TestsModel();
tests.setTitle(testIdentifier.getDisplayName());
tests.setFullTitle(testIdentifier.getDisplayName());
tests.setUuid(childId);
}
}
/**
* 用例执行完成
*
* @param testIdentifier
*/
@SneakyThrows
@Override
public void executionFinished(TestIdentifier testIdentifier, TestExecutionResult testExecutionResult) {
testEnd = LocalDateTime.now();
String uuqueid = testIdentifier.getUniqueId();
if (testIdentifier.isTest()) {
//case结束
caseModel = new CaseModel();
Duration duration = Duration.between(testStar, testEnd);
tests.setDuration(duration.toMillis());
if ("SUCCESSFUL".equals(testExecutionResult.getStatus().name())) {
tests.setFail(false);
tests.setPass(true);
tests.setSkipped(false);
tests.setPending(false);
tests.setCode("成功");
tests.setState("true");
passes++;
passTestModleList.add(tests);
caseModel.setTitle(testIdentifier.getDisplayName() +"-"+ testIdentifier.getLegacyReportingName());
caseModel.setValue(testExecutionResult.getStatus().name());
} else {
tests.setContext(imageNow(testIdentifier.getDisplayName()));
tests.setPass(false);
tests.setFail(true);
tests.setSkipped(false);
tests.setPending(false);
tests.setState("false");
tests.setCode("失败原因:"+testExecutionResult.getThrowable().get().getMessage());
failures++;
failuresTestModleList.add(tests);
caseModel.setTitle(testIdentifier.getDisplayName() +"-"+ testIdentifier.getLegacyReportingName());
caseModel.setValue(testExecutionResult.getStatus().name());
}
testsModelList.add(tests);
caseModels.add(caseModel);
} else if (uuqueid.equals(parentId)) {
caseSuitesEnd = LocalDateTime.now();
// 测试类结束 写入 after
eachRunnable = new EachRunnableModel();
List<EachRunnableModel> eachRunnableList = new ArrayList<>();
eachRunnable.setTitle(testIdentifier.getDisplayName() + testIdentifier.getLegacyReportingName());
eachRunnable.setBody(testIdentifier.getSource().toString());
eachRunnable.setParent(this.getClass().getSimpleName());
eachRunnableList.add(eachRunnable);
// 添加测试类的before
caseSuites.setAfterAll(new ArrayList<>());
caseSuites.setAfterEach(eachRunnableList);
caseSuites.setTests(testsModelList);
caseSuites.setPasses(passTestModleList);
caseSuites.setFailures(failuresTestModleList);
// caseSuites 数据填充
caseSuites.setTitle(testIdentifier.getDisplayName());
caseSuites.setSuites(new ArrayList<>());
caseSuites.setRoot(false);
caseSuites.setTimeout((long) 3000);
caseSuites.setEnableTimeouts(true);
caseSuites.setSlow((long)75);
caseSuites.setRetries((long) -1);
caseSuites.setDelayed(false);
caseSuites.setParent(testIdentifier.getParentId().get());
caseSuites.setFile(testIdentifier.getLegacyReportingName());
caseSuites.setFullFile(testIdentifier.getLegacyReportingName());
caseSuites.setUuid(testIdentifier.getUniqueId());
caseSuites.setSkipped(new ArrayList<>());
caseSuites.setTotalTests((long)(passTestModleList.size()+failuresTestModleList.size()));
caseSuites.setTotalPasses((long)passTestModleList.size());
caseSuites.setTotalFailures((long)failuresTestModleList.size());
caseSuites.setTotalSkipped((long) 0);
caseSuites.setTotalPending((long) 0);
Duration duration = Duration.between(caseSuitesStar,caseSuitesEnd);
caseSuites.setDuration(duration.toMillis());
caseSuitesList.add(caseSuites);
// testClassSuites 数据填充
testClassSuites.setAfterEach(new ArrayList<>());
testClassSuites.setAfterAll(new ArrayList<>());
testClassSuites.setRoot(false);
testClassSuites.setTimeout((long) 3000);
testClassSuites.setEnableTimeouts(false);
testClassSuites.setSlow((long) 75);
testClassSuites.setRetries((long) -1);
testClassSuites.setDelayed(false);
testClassSuites.setPasses(new ArrayList<>());
testClassSuites.setFailures(new ArrayList<>());
testClassSuites.setSkipped(new ArrayList<>());
testClassSuites.setTotalFailures((long) 0);
testClassSuites.setTotalPasses((long) 0);
testClassSuites.setTotalPending((long) 0);
testClassSuites.setTotalTests((long)0);
testClassSuites.setTotalSkipped((long)0);
testClassSuites.setDuration((long) 0);
// 测试用例 suite集合添加到 testclasssuites
testClassSuites.setSuites(caseSuitesList);
}
}
/**
* 测试计划执行结束
*
* @param testPlan
*/
@Override
public void testPlanExecutionFinished(TestPlan testPlan) {
//填充suties
List<TestsModel> test = new ArrayList<>();
List<EachRunnableModel> runnableModels = new ArrayList<>();
planSuites.setAfterAll(runnableModels);
planSuites.setBeforeAll(runnableModels);
planSuites.setCtx(new CtxModel());
planSuites.setTests(test);
planSuites.setPending(test);
planSuites.setBeforeEach(runnableModels);
planSuites.setAfterEach(runnableModels);
planSuites.setRoot(true);
planSuites.setTimeout((long) 2000);
planSuites.setEnableTimeouts(true);
planSuites.setSlow((long) 100);
planSuites.setRetries((long) -1);
planSuites.setDelayed(false);
planSuites.setEvents(new EventsModel());
planSuites.setEventsCount((long) 1);
planSuites.setUuid(testPlanId);
planSuites.setTitle("");
planSuites.setFile("");
planSuites.setPasses(test);
planSuites.setFailures(test);
planSuites.setSkipped(test);
planSuites.setTotalTests((long) 0);
planSuites.setTotalSkipped((long) 0);
planSuites.setTotalFailures((long) 0);
planSuites.setTotalPending((long) 0);
planSuites.setTotalPasses((long) 0);
planSuites.setTotalTime((long) 0);
planSuites.setSuites(testClassSuitesList);
// planStats
int testCount = failures+passes+skipped;
planStats.setEnd(LocalDateTime.now());
Duration duration = Duration.between(planStats.getStart(), planStats.getEnd());
planStats.setDuration(duration.toMillis());
planStats.setFailures((long)failures);
planStats.setPasses((long)passes);
planStats.setSkipped((long)skipped);
planStats.setSuites((long)planSuites.getSuites().size());
planStats.setHasOther(false);
planStats.setOther((long)0);
planStats.setHasSkipped(false);
planStats.setTests((long)testCount);
planStats.setPassPercent(numberFormat(passes,testCount));
planStats.setPending((long)0);
// 设置logo 面板数据
macacaReportModel = new MacacaReportModel();
macacaReportModel.setStats(planStats);
macacaReportModel.setSuites(planSuites);
if(logo != null){
currentModle.setImage(logo);
currentModle.setList(caseModels);
macacaReportModel.setCurrent(currentModle);
}
String reportJson = "module.exports = " + JSONObject.toJSONString(macacaReportModel, SerializerFeature.DisableCircularReferenceDetect);
try {
writeJs("report.js",reportJson);
} catch (Exception e) {
e.printStackTrace();
}
exec2();
}
/**
* 执行跳过
* @param testIdentifier
*/
@Override
public void executionSkipped(TestIdentifier testIdentifier, String reason) {
skipped++;
}
/*
* ======================================== 一些方法 ==============================================
*/
/**
* 输出 Js
* @param name 文件名
* @param content 内容
* @throws Exception
*/
public static void writeJs(String name, String content) throws IOException {
OutputStreamWriter oStreamWriter = new OutputStreamWriter(new FileOutputStream(name), "utf-8");
System.out.println("正在生成报告:"+content);
oStreamWriter.append(content);
oStreamWriter.close();
}
/**
* 判断是否存在logo
* @return
*/
private static String getLogo(){
String logoUrl = System.getProperty("logo");
if(logoUrl != null){
return logoUrl;
}
return null;
}
/**
* 判断是否这是logo
* @return
*/
private static String getPlanName(){
String planName = System.getProperty("planName");
if(planName != null){
return planName;
}
return "Macaca测试报告";
}
/**
* js生成后 执行cmd生成报告
* @return
*/
public static void exec2(){
String cmd = isWindows() ? "macaca-reporter.cmd -d report.js" : "macaca-reporter -d report.js";
Runtime run = Runtime.getRuntime();
try {
Process p = run.exec(cmd);
BufferedInputStream in = new BufferedInputStream(p.getInputStream());
BufferedReader inBr = new BufferedReader(new InputStreamReader(in));
inBr.close();
in.close();
} catch (Exception var7) {
System.out.println("报告失败了:"+var7.getMessage());
}
}
/**
* 是否windows
* @return
*/
private static boolean isWindows() {
return System.getProperty("os.name").toLowerCase().contains("win");
}
/**
* 图片转码
* @param imgPath
* @return
*/
private static String imageToBase64(String imgPath) {
byte[] data = null;
// 读取图片字节数组
try {
InputStream in = new FileInputStream(imgPath);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
// 返回Base64编码过的字节数组字符串
String base64Image = "data:image/png;base64,"+ Base64.getEncoder().encodeToString(Objects.requireNonNull(data));
return base64Image;
}
/**
* 判断图片路径下是否有该方法的截图生成截图
* @param name
* @return
* @throws IOException
*/
private static String imageNow(String name) throws IOException {
File file = new File(System.getProperty("user.dir")+File.separator+"screenshot");
File[] fileList = file.listFiles();
if(fileList==null){
return "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
}
for (int i = 0; i < fileList.length; i++) {
if (fileList[i].isFile()) {
String filePath = fileList[i].getCanonicalPath();
if(filePath.indexOf(name)>0){
return imageToBase64(filePath);
}
}
}
return null;
}
/**
* 计算
* @param passes
* @param count
* @return
*/
public double numberFormat(int passes ,int count){
if(count==0){
return 0;
}
NumberFormat numberFormat = NumberFormat.getInstance();
numberFormat.setMaximumFractionDigits(2);
String result = numberFormat.format( ((float) passes / (float)count)*100);
double passPercent = Double.valueOf(result);
System.out.println(result);
return passPercent;
}
}
| true |
c5d7bf4bac152bea847486dae18032462f9e0a64 | Java | zhongxingyu/Seer | /Diff-Raw-Data/2/2_08074e82f22e5d3af9ae88cca2ae2d107015ebf0/WumpusWorldTester/2_08074e82f22e5d3af9ae88cca2ae2d107015ebf0_WumpusWorldTester_s.java | UTF-8 | 7,147 | 2.703125 | 3 | [] | no_license | package tests;
import demos.WumpusWorld;
import vitro.*;
import vitro.graph.*;
import vitro.util.*;
import java.util.*;
import org.junit.Test;
import static org.junit.Assert.*;
public class WumpusWorldTester {
@Test
public void testDone() {
WumpusWorld w = new WumpusWorld();
Node node0 = w.createNode();
Node node1 = w.createNode();
node0.actors.add(w.createWumpus());
node1.actors.add(w.createHunter());
assertFalse(w.done());
w.actors.clear();
node0.actors.add(w.createWumpus());
assertTrue(w.done());
w.actors.clear();
node1.actors.add(w.createWumpus());
assertTrue(w.done());
w.actors.clear();
assertTrue(w.done());
}
@Test
public void testAlive() {
WumpusWorld w = new WumpusWorld();
WumpusWorld.Hunter hunter = w.createHunter();
assertFalse(hunter.alive());
w.actors.add(hunter);
assertTrue(hunter.alive());
}
@Test
public void testFlapping() {
WumpusWorld w = new WumpusWorld();
Node node0 = w.createNode();
Node node1 = w.createNode();
Node node2 = w.createNode();
w.createEdge(node0, node1);
w.createEdge(node1, node2);
WumpusWorld.Hunter hunter = w.createHunter();
node0.actors.add(hunter);
node1.actors.add(w.createBat());
assertTrue(hunter.flapping());
node1.actors.clear();
node2.actors.add(w.createBat());
assertFalse(hunter.flapping());
}
@Test
public void testWind() {
WumpusWorld w = new WumpusWorld();
Node node0 = w.createNode();
Node node1 = w.createNode();
Node node2 = w.createNode();
w.createEdge(node0, node1);
w.createEdge(node1, node2);
WumpusWorld.Hunter hunter = w.createHunter();
node0.actors.add(hunter);
node1.actors.add(w.createPit());
assertTrue(hunter.wind());
node1.actors.clear();
node2.actors.add(w.createPit());
assertFalse(hunter.wind());
}
@Test
public void testScent() {
WumpusWorld w = new WumpusWorld();
Node node0 = w.createNode();
Node node1 = w.createNode();
Node node2 = w.createNode();
w.createEdge(node0, node1);
w.createEdge(node1, node2);
WumpusWorld.Hunter hunter = w.createHunter();
node0.actors.add(hunter);
node1.actors.add(w.createWumpus());
assertTrue(hunter.scent());
node1.actors.clear();
node2.actors.add(w.createWumpus());
assertFalse(hunter.scent());
}
@Test
public void testWhistle() {
WumpusWorld w = new WumpusWorld();
Node node0 = w.createNode();
Node node1 = w.createNode();
w.createEdge(node0, node1);
WumpusWorld.Hunter hunter = w.createHunter();
node0.actors.add(hunter);
Action action = Groups.firstOfType(WumpusWorld.ShootAction.class, hunter.actions());
WumpusWorld.ShootAction shoot = (WumpusWorld.ShootAction)action;
assertFalse(shoot == null);
shoot.apply();
assertTrue(hunter.whistle());
}
@Test
public void testWalk() {
WumpusWorld w = new WumpusWorld();
Node node0 = w.createNode();
Node node1 = w.createNode();
Node node2 = w.createNode();
Node node3 = w.createNode();
Edge edge1 = w.createEdge(node0, node1);
Edge edge2 = w.createEdge(node0, node2);
Edge edge3 = w.createEdge(node0, node3);
WumpusWorld.Bat bat = w.createBat();
WumpusWorld.Pit pit = w.createPit();
WumpusWorld.Wumpus wumpus = w.createWumpus();
node1.actors.add(bat);
node2.actors.add(pit);
node3.actors.add(wumpus);
WumpusWorld.Hunter hunter = w.createHunter();
node0.actors.add(hunter);
hunter.arrows = 0;
Set<Action> actions = hunter.actions();
assertTrue(actions.size() == 3);
}
@Test
public void testWalkInToBat() {
WumpusWorld w = new WumpusWorld();
Node node0 = w.createNode();
Node node1 = w.createNode();
Edge edge1 = w.createEdge(node0, node1);
WumpusWorld.Bat bat = w.createBat();
node1.actors.add(bat);
WumpusWorld.Hunter hunter = w.createHunter();
node0.actors.add(hunter);
hunter.arrows = 0;
Set<Action> actions = hunter.actions();
assertTrue(actions.size() == 1);
Action action = Groups.first(actions);
action.apply();
assertTrue(hunter.alive());
}
@Test
public void testWalkInToPit() {
WumpusWorld w = new WumpusWorld();
Node node0 = w.createNode();
Node node1 = w.createNode();
Edge edge1 = w.createEdge(node0, node1);
WumpusWorld.Pit pit = w.createPit();
node1.actors.add(pit);
WumpusWorld.Hunter hunter = w.createHunter();
node0.actors.add(hunter);
hunter.arrows = 0;
Set<Action> actions = hunter.actions();
assertTrue(actions.size() == 1);
Action action = Groups.first(actions);
action.apply();
assertFalse(hunter.alive());
}
@Test
public void testWalkInToWumpus() {
WumpusWorld w = new WumpusWorld();
Node node0 = w.createNode();
Node node1 = w.createNode();
Edge edge1 = w.createEdge(node0, node1);
WumpusWorld.Wumpus wumpus = w.createWumpus();
node1.actors.add(wumpus);
WumpusWorld.Hunter hunter = w.createHunter();
node0.actors.add(hunter);
hunter.arrows = 0;
Set<Action> actions = hunter.actions();
assertTrue(actions.size() == 1);
Action action = Groups.first(actions);
action.apply();
assertFalse(hunter.alive());
}
@Test
public void testShoot() {
WumpusWorld w = new WumpusWorld();
Node node0 = w.createNode();
Node node1 = w.createNode();
w.createEdge(node0, node1);
WumpusWorld.Hunter hunter = w.createHunter();
node0.actors.add(hunter);
{
hunter.arrows = 0;
Action action = Groups.firstOfType(WumpusWorld.ShootAction.class, hunter.actions());
WumpusWorld.ShootAction shoot = (WumpusWorld.ShootAction)action;
assertTrue(shoot == null);
}
{
hunter.arrows = 1;
Action action = Groups.firstOfType(WumpusWorld.ShootAction.class, hunter.actions());
WumpusWorld.ShootAction shoot = (WumpusWorld.ShootAction)action;
assertFalse(shoot == null);
shoot.apply();
Actor actor = Groups.firstOfType(WumpusWorld.Arrow.class, w.actors);
assertFalse(actor == null);
assertTrue(hunter.arrows == 0);
}
}
@Test
public void testShootKillWumpus() {
WumpusWorld w = new WumpusWorld();
Node node0 = w.createNode();
Node node1 = w.createNode();
w.createEdge(node0, node1);
WumpusWorld.Hunter hunter = w.createHunter();
node0.actors.add(hunter);
WumpusWorld.Wumpus wumpus = w.createWumpus();
node1.actors.add(wumpus);
Action action = Groups.firstOfType(WumpusWorld.ShootAction.class, hunter.actions());
WumpusWorld.ShootAction shoot = (WumpusWorld.ShootAction)action;
assertFalse(shoot == null);
shoot.apply();
Actor actor = Groups.firstOfType(WumpusWorld.Arrow.class, w.actors);
assertFalse(actor == null);
WumpusWorld.Arrow arrow = (WumpusWorld.Arrow)actor;
DestroyAction kill = new DestroyAction(w, wumpus, arrow);
assertTrue(arrow.actions().contains(kill));
kill.apply();
assertTrue(w.done());
kill.undo();
assertFalse(w.done());
}
}
| true |
7fff4ca4783a9ee3bf76dc643559ea13559b3bcc | Java | daiqi77777/tensquare_parent | /tensquare_sms/src/main/java/com/tensquare/sms/listener/SmsListener.java | UTF-8 | 707 | 2.09375 | 2 | [] | no_license | package com.tensquare.sms.listener;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import java.util.HashMap;
@Service
@RabbitListener(queues = "sms")
public class SmsListener {
@RabbitHandler
public void executeSms(HashMap<String,String> map){
System.out.println("******************************************");
System.out.println("手机号"+map.get("phone"));
System.out.println("验证码"+map.get("code"));
System.out.println("******************************************");
}
}
| true |
4314492630ed15617120726cf761849bcda5cd85 | Java | PXAV/keyboard-api-spigot | /src/de/pxav/keyboard/listeners/InventoryClickListener.java | UTF-8 | 7,060 | 2.421875 | 2 | [] | no_license | package de.pxav.keyboard.listeners;
// The project SpigotMC.org - KeyboardAPI is developed and updated by PXAV.
// You are not allowed to claim this as your own, give it to
// others or even sell it.
//
// Contact me on:
// YouTube: https://www.youtube.com/channel/UCtXSAGTwurKVeEbwEKMlFog
// Twitter: https://twitter.com/OrigPXAV
//
// (c) 2018 PXAV
import de.pxav.keyboard.KeyboardAPI;
import de.pxav.keyboard.KeyboardPlugin;
import de.pxav.keyboard.events.KeyboardCanceledTypingEvent;
import de.pxav.keyboard.events.KeyboardEnteredResultEvent;
import de.pxav.keyboard.items.KeyboardInventoryBuilder;
import de.pxav.keyboard.keyboard.Keyboard;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
public class InventoryClickListener implements Listener {
@EventHandler
public void onInventoryClick(final InventoryClickEvent event) {
if(event.getWhoClicked() instanceof Player && event.getClickedInventory() != null) {
final Player player = (Player) event.getWhoClicked();
if(KeyboardAPI.getInstance().getKeyboardHandler().playerHasKeyboard(player)) {
final Keyboard keyboard = KeyboardAPI.getInstance().getKeyboardHandler().getMatchingKeyboard(player);
if(KeyboardPlugin.getInstance().getKeyboardUtils().isKeyboardAlphabetInventory(event.getClickedInventory())
|| KeyboardPlugin.getInstance().getKeyboardUtils().isKeyboardAsciiInventory(event.getClickedInventory())
|| KeyboardPlugin.getInstance().getKeyboardUtils().isKeyboardSymbolsInventory(event.getClickedInventory())) {
event.setCancelled(true);
if((event.getCurrentItem().getType() == Material.SKULL_ITEM || event.getCurrentItem().getType() == Material.FLOWER_POT_ITEM)
&& event.getCurrentItem().getItemMeta().getDisplayName().startsWith("§a§l")) {
final String letter = event.getCurrentItem().getItemMeta().getDisplayName().replace("§a§l", "");
keyboard.setTypeResult(keyboard.getTypeResult() + letter);
player.playSound(player.getLocation(), Sound.CLICK, 3, 1);
KeyboardPlugin.getInstance().getKeyboardInventoryBuilder().updateTypeResult(player, letter);
} else if(event.getCurrentItem().getType() == Material.STICK) {
final String letter = " ";
keyboard.setTypeResult(keyboard.getTypeResult() + letter);
player.playSound(player.getLocation(), Sound.CLICK, 3, 1);
KeyboardPlugin.getInstance().getKeyboardInventoryBuilder().updateTypeResult(player, letter);
} else if(event.getCurrentItem().getType() == Material.DIAMOND && (event.getCurrentItem().getItemMeta().getDisplayName().equalsIgnoreCase(KeyboardInventoryBuilder.ITEM_DONE_ENGLISH)
|| event.getCurrentItem().getItemMeta().getDisplayName().equalsIgnoreCase(KeyboardInventoryBuilder.ITEM_DONE_GERMAN)
|| event.getCurrentItem().getItemMeta().getDisplayName().equalsIgnoreCase(KeyboardInventoryBuilder.ITEM_DONE_FRENCH))) {
KeyboardPlugin.getInstance().getKeyboardUtils().closeKeyboardByPlugin(player);
player.closeInventory();
Bukkit.getPluginManager().callEvent(new KeyboardEnteredResultEvent(player, keyboard));
player.playSound(player.getLocation(), Sound.CLICK, 3, 1);
} else if(event.getCurrentItem().getItemMeta().getDisplayName().equalsIgnoreCase(KeyboardInventoryBuilder.ITEM_CANCEL_ENGLISH)
|| event.getCurrentItem().getItemMeta().getDisplayName().equalsIgnoreCase(KeyboardInventoryBuilder.ITEM_CANCEL_FRENCH)
|| event.getCurrentItem().getItemMeta().getDisplayName().equalsIgnoreCase(KeyboardInventoryBuilder.ITEM_CANCEL_GERMAN)) {
KeyboardPlugin.getInstance().getKeyboardUtils().closeKeyboardByPlugin(player);
player.closeInventory();
Bukkit.getPluginManager().callEvent(new KeyboardCanceledTypingEvent(player, keyboard));
player.playSound(player.getLocation(), Sound.CLICK, 3, 1);
} else if(event.getCurrentItem().getItemMeta().getDisplayName().equalsIgnoreCase(KeyboardInventoryBuilder.ITEM_SYMBOLS_ENGLISH)
|| event.getCurrentItem().getItemMeta().getDisplayName().equalsIgnoreCase(KeyboardInventoryBuilder.ITEM_SYMBOLS_GERMAN)
|| event.getCurrentItem().getItemMeta().getDisplayName().equalsIgnoreCase(KeyboardInventoryBuilder.ITEM_SYMBOLS_FRENCH)) {
KeyboardPlugin.getInstance().getKeyboardUtils().closeKeyboardByPlugin(player);
player.closeInventory();
KeyboardPlugin.getInstance().getKeyboardInventoryBuilder().openSymbolsMenu(player, keyboard.getLanguage());
player.playSound(player.getLocation(), Sound.CLICK, 3, 1);
} else if(event.getCurrentItem().getItemMeta().getDisplayName().equalsIgnoreCase(KeyboardInventoryBuilder.ITEM_ASCII_ENGLISH)
|| event.getCurrentItem().getItemMeta().getDisplayName().equalsIgnoreCase(KeyboardInventoryBuilder.ITEM_ASCII_GERMAN)
|| event.getCurrentItem().getItemMeta().getDisplayName().equalsIgnoreCase(KeyboardInventoryBuilder.ITEM_ASCII_FRENCH)) {
KeyboardPlugin.getInstance().getKeyboardUtils().closeKeyboardByPlugin(player);
player.closeInventory();
KeyboardPlugin.getInstance().getKeyboardInventoryBuilder().openAsciiMenu(player, keyboard.getLanguage());
player.playSound(player.getLocation(), Sound.CLICK, 3, 1);
} else if(event.getCurrentItem().getItemMeta().getDisplayName().equalsIgnoreCase(KeyboardInventoryBuilder.ITEM_ALPHABET_ENGLISH)
|| event.getCurrentItem().getItemMeta().getDisplayName().equalsIgnoreCase(KeyboardInventoryBuilder.ITEM_ALPHABET_GERMAN)
|| event.getCurrentItem().getItemMeta().getDisplayName().equalsIgnoreCase(KeyboardInventoryBuilder.ITEM_ALPHABET_FRENCH)) {
KeyboardPlugin.getInstance().getKeyboardUtils().closeKeyboardByPlugin(player);
player.closeInventory();
KeyboardPlugin.getInstance().getKeyboardInventoryBuilder().openAlphabet(player, keyboard.getLanguage());
player.playSound(player.getLocation(), Sound.CLICK, 3, 1);
}
}
}
}
}
}
| true |
20bcde9e6d369b7722b17282a5cb2f7d2b439470 | Java | erasx3/Avanzada | /programa avanzada/src/Visual/GenerarCompraInter.java | UTF-8 | 25,840 | 1.9375 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Visual;
import Logica.Articulo;
import Logica.Consumible;
import Logica.Detalle;
import Logica.DetalleCompraVenta;
import Logica.Encabezado;
import Logica.Proveedor;
import Logica.TipoCompra;
import Logica.TipoComprobante;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
/**
*
* @author Facu
*/
public class GenerarCompraInter extends javax.swing.JInternalFrame {
private ControladoraVisual miControladoraVisual;
private DefaultTableModel modeloDetalle;
private int fila;
private int codigoDetalle;
public GenerarCompraInter(ControladoraVisual miControladoraVisual) {
initComponents();
GenerarCompraInter.txtCodigoProveedor.setVisible(false);
this.miControladoraVisual = miControladoraVisual;
this.modeloDetalle = (DefaultTableModel) this.tblDetallesCompraVenta.getModel();
this.cmdAgregarArticulo.setEnabled(false);
this.cmdGenerarCompra.setEnabled(false);
refrescarVentana();
cargarCmbCompra();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
cldFecha = new com.toedter.calendar.JDateChooser();
txtCodigoProveedor = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
lblNombreProveedor = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
cmbComprobanteCompra = new javax.swing.JComboBox<>();
jLabel3 = new javax.swing.JLabel();
lblCodigoArticulo = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
lblNombreArticulo = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
lblPrecioArticulo = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
txtCantidadArticulo = new javax.swing.JTextField();
cmdBuscarArticulo = new javax.swing.JButton();
cmdAgregarArticulo = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
tblDetallesCompraVenta = new javax.swing.JTable();
cmdBorrarRenglon = new javax.swing.JButton();
cmdCrearArticulo = new javax.swing.JButton();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
lblTotal = new javax.swing.JLabel();
cmdGenerarCompra = new javax.swing.JButton();
cmdVerCompras = new javax.swing.JButton();
cmdBuscarProveedor = new javax.swing.JButton();
setClosable(true);
setTitle("Compra");
jLabel1.setText("Nombre Proveedor:");
lblNombreProveedor.setText("Proveedor");
jLabel2.setText("Comprobante:");
cmbComprobanteCompra.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel3.setText("Codigo Articulo:");
lblCodigoArticulo.setText("xxxxxx");
jLabel4.setText("Nombre Articulo:");
lblNombreArticulo.setText("Articulo");
jLabel5.setText("Precio:");
jLabel6.setText("$");
lblPrecioArticulo.setText("0.00");
jLabel7.setText("Cantidad:");
cmdBuscarArticulo.setText("Buscar Articulo");
cmdBuscarArticulo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmdBuscarArticuloActionPerformed(evt);
}
});
cmdAgregarArticulo.setText("Agregar Articulo");
cmdAgregarArticulo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmdAgregarArticuloActionPerformed(evt);
}
});
tblDetallesCompraVenta.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Codigo", "Articulo", "Cantidad", "Subtotal"
}
));
tblDetallesCompraVenta.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tblDetallesCompraVentaMouseClicked(evt);
}
});
jScrollPane1.setViewportView(tblDetallesCompraVenta);
cmdBorrarRenglon.setText("Borrar Renglon");
cmdBorrarRenglon.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmdBorrarRenglonActionPerformed(evt);
}
});
cmdCrearArticulo.setText("Crear Articulo");
cmdCrearArticulo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmdCrearArticuloActionPerformed(evt);
}
});
jLabel8.setText("Total:");
jLabel9.setText("$");
lblTotal.setText("0.00");
cmdGenerarCompra.setText("Generar Compra");
cmdGenerarCompra.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmdGenerarCompraActionPerformed(evt);
}
});
cmdVerCompras.setText("Ver Compras");
cmdVerCompras.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmdVerComprasActionPerformed(evt);
}
});
cmdBuscarProveedor.setText("Buscar Proveedor");
cmdBuscarProveedor.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmdBuscarProveedorActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(2, 2, 2)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblNombreProveedor, javax.swing.GroupLayout.DEFAULT_SIZE, 190, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(lblCodigoArticulo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblNombreArticulo, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblPrecioArticulo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(cmbComprobanteCompra, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txtCantidadArticulo, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(44, 44, 44))
.addGroup(layout.createSequentialGroup()
.addGap(128, 128, 128)
.addComponent(txtCodigoProveedor, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(cldFecha, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(cmdAgregarArticulo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(cmdBuscarArticulo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(cmdBuscarProveedor, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE)))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane1)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel9)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(cmdCrearArticulo, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(cmdVerCompras, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(cmdBorrarRenglon, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(cmdGenerarCompra, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE))))))
.addGap(15, 15, 15))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(txtCodigoProveedor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(cldFecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(lblNombreProveedor)
.addComponent(jLabel2)
.addComponent(cmbComprobanteCompra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(cmdBuscarProveedor))
.addGap(20, 20, 20)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(lblCodigoArticulo)
.addComponent(jLabel7)
.addComponent(txtCantidadArticulo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(cmdBuscarArticulo))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(lblNombreArticulo)
.addComponent(jLabel5)
.addComponent(lblPrecioArticulo)
.addComponent(cmdAgregarArticulo)
.addComponent(jLabel6))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 224, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cmdBorrarRenglon)
.addComponent(cmdCrearArticulo))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel8)
.addComponent(jLabel9)
.addComponent(lblTotal)
.addComponent(cmdGenerarCompra))
.addComponent(cmdVerCompras, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void cmdBuscarArticuloActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdBuscarArticuloActionPerformed
BusquedaArticuloCompraInter unArticuloCompraInter = new BusquedaArticuloCompraInter(miControladoraVisual);
MenuPrincipal.Escritorio.add(unArticuloCompraInter);
unArticuloCompraInter.show();
this.cmdAgregarArticulo.setEnabled(true);
}//GEN-LAST:event_cmdBuscarArticuloActionPerformed
private void cmdBuscarProveedorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdBuscarProveedorActionPerformed
BusquedaProveedorInter unBusquedaProveedorInter = new BusquedaProveedorInter(miControladoraVisual);
MenuPrincipal.Escritorio.add(unBusquedaProveedorInter);
unBusquedaProveedorInter.show();
}//GEN-LAST:event_cmdBuscarProveedorActionPerformed
private void cmdAgregarArticuloActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdAgregarArticuloActionPerformed
Consumible unConsumible = (Consumible) this.miControladoraVisual.buscarArticulo(Integer.parseInt(GenerarCompraInter.lblCodigoArticulo.getText()));
Double subtotal = Integer.parseInt(txtCantidadArticulo.getText()) * Double.parseDouble(lblPrecioArticulo.getText());
Double total = subtotal + Double.parseDouble(this.lblTotal.getText());
try {
int codigoDetalle = this.miControladoraVisual.generarDetalleCompraVenta(Integer.parseInt(txtCantidadArticulo.getText()), unConsumible, subtotal);
this.miControladoraVisual.sumarArticulo(Integer.parseInt(txtCantidadArticulo.getText()), Integer.parseInt(this.lblCodigoArticulo.getText()));
this.lblTotal.setText(String.valueOf(total));
refrescarVentanaArticulo();
cargarTablaDetalle(codigoDetalle);
} catch (Exception ex) {
Logger.getLogger(GenerarCompraInter.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_cmdAgregarArticuloActionPerformed
private void cmdGenerarCompraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdGenerarCompraActionPerformed
List<Detalle> unosDetalles = new LinkedList();
Calendar fecha= new GregorianCalendar();
DetalleCompraVenta unDetalleCompraVenta;
Encabezado unEncabezado;
TipoComprobante unTipoComprobante;
Proveedor unProveedor;
int codigo;
int codigoComp;
int codigoEncab;
Double total = 0.00;
String cadena = (String) this.cmbComprobanteCompra.getSelectedItem();
String[] partes = cadena.split("-");
codigoComp = Integer.parseInt(partes[0]);
for (int i = 0; i < modeloDetalle.getRowCount(); i++) {
codigo = Integer.parseInt(this.modeloDetalle.getValueAt(i, 0).toString());
unDetalleCompraVenta = this.miControladoraVisual.buscarDetalleCompraVenta(codigo);
total = total + unDetalleCompraVenta.getSubtotal();
unosDetalles.add(unDetalleCompraVenta);
}
unTipoComprobante = this.miControladoraVisual.buscarTipoCompra(codigoComp);
fecha=this.cldFecha.getCalendar();
unProveedor=this.miControladoraVisual.buscarProveedor(Integer.parseInt(txtCodigoProveedor.getText()));
try {
codigoEncab=this.miControladoraVisual.generarEncabezado(fecha, unProveedor, unTipoComprobante, unosDetalles, total);
unEncabezado=this.miControladoraVisual.buscarEncabezado(codigoEncab);
this.miControladoraVisual.agregarCompra(unEncabezado);
refrescarVentana();
} catch (Exception ex) {
Logger.getLogger(GenerarCompraInter.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_cmdGenerarCompraActionPerformed
private void cmdCrearArticuloActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdCrearArticuloActionPerformed
AltaArticuloInter unAltaArticuloInter = new AltaArticuloInter(miControladoraVisual);
MenuPrincipal.Escritorio.add(unAltaArticuloInter);
unAltaArticuloInter.show();
}//GEN-LAST:event_cmdCrearArticuloActionPerformed
private void cmdBorrarRenglonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdBorrarRenglonActionPerformed
try {
DetalleCompraVenta unDetalle = this.miControladoraVisual.buscarDetalleCompraVenta(this.codigoDetalle);
int codigoArticulo = unDetalle.getUnConsumible().getCodigo();
this.miControladoraVisual.descontarArticulo(unDetalle.getCantidad(), codigoArticulo);
this.miControladoraVisual.borrarDetalleCompraVenta(unDetalle.getCodigo());
this.modeloDetalle.removeRow(this.fila);
this.lblTotal.setText(String.valueOf(Double.parseDouble(lblTotal.getText()) - unDetalle.getSubtotal()));
} catch (Exception ex) {
Logger.getLogger(GenerarVentaArticuloInter.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_cmdBorrarRenglonActionPerformed
private void cmdVerComprasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdVerComprasActionPerformed
ListarCompraInter unListarCompraInter = new ListarCompraInter(miControladoraVisual);
MenuPrincipal.Escritorio.add(unListarCompraInter);
unListarCompraInter.show();
}//GEN-LAST:event_cmdVerComprasActionPerformed
private void tblDetallesCompraVentaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblDetallesCompraVentaMouseClicked
this.fila = this.tblDetallesCompraVenta.rowAtPoint(evt.getPoint());
this.codigoDetalle = Integer.parseInt(this.modeloDetalle.getValueAt(fila, 0).toString());
}//GEN-LAST:event_tblDetallesCompraVentaMouseClicked
// Variables declaration - do not modify//GEN-BEGIN:variables
private com.toedter.calendar.JDateChooser cldFecha;
private javax.swing.JComboBox<String> cmbComprobanteCompra;
private javax.swing.JButton cmdAgregarArticulo;
private javax.swing.JButton cmdBorrarRenglon;
private javax.swing.JButton cmdBuscarArticulo;
private javax.swing.JButton cmdBuscarProveedor;
private javax.swing.JButton cmdCrearArticulo;
private javax.swing.JButton cmdGenerarCompra;
private javax.swing.JButton cmdVerCompras;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JScrollPane jScrollPane1;
public static javax.swing.JLabel lblCodigoArticulo;
public static javax.swing.JLabel lblNombreArticulo;
public static javax.swing.JLabel lblNombreProveedor;
public static javax.swing.JLabel lblPrecioArticulo;
private javax.swing.JLabel lblTotal;
private javax.swing.JTable tblDetallesCompraVenta;
private javax.swing.JTextField txtCantidadArticulo;
public static javax.swing.JTextField txtCodigoProveedor;
// End of variables declaration//GEN-END:variables
private void refrescarVentana() {
GenerarCompraInter.txtCodigoProveedor.setText(null);
GenerarCompraInter.lblNombreProveedor.setText("Proveedor");
GenerarCompraInter.lblCodigoArticulo.setText("xxxxxx");
GenerarCompraInter.lblNombreArticulo.setText("Articulo");
GenerarCompraInter.lblPrecioArticulo.setText("0.00");
this.cmbComprobanteCompra.removeAllItems();
this.modeloDetalle.setRowCount(0);
this.lblTotal.setText("0.00");
this.txtCantidadArticulo.setText(null);
}
private void cargarCmbCompra() {
Iterator<TipoCompra> itCompra = this.miControladoraVisual.traerTipoCompra().iterator();
TipoCompra unTipoCompra;
while (itCompra.hasNext()) {
unTipoCompra = itCompra.next();
this.cmbComprobanteCompra.addItem(unTipoCompra.toString());
}
}
private void refrescarVentanaArticulo() {
GenerarCompraInter.lblCodigoArticulo.setText("xxxxxx");
GenerarCompraInter.lblNombreArticulo.setText("Articulo");
GenerarCompraInter.lblPrecioArticulo.setText("0.00");
this.txtCantidadArticulo.setText(null);
}
private void cargarTablaDetalle(int codigoDetalle) {
DetalleCompraVenta unDetalleCompraVenta = this.miControladoraVisual.buscarDetalleCompraVenta(codigoDetalle);
Articulo unArticulo = (Articulo) unDetalleCompraVenta.getUnConsumible();
this.modeloDetalle.addRow(new Object[]{unDetalleCompraVenta.getCodigo(), unArticulo.getNombre(), unDetalleCompraVenta.getCantidad(), unDetalleCompraVenta.getSubtotal()});
this.cmdGenerarCompra.setEnabled(true);
}
}
| true |
373d42d2a61a5fe9c639ee34d24f683a4e041c0d | Java | suzanasaraiva/Compilador3va | /Compilador_3va/src/compiler/tree/command/DeclVariavel.java | UTF-8 | 1,706 | 2.9375 | 3 | [] | no_license | package compiler.tree.command;
import java.util.LinkedList;
import compiler.syntax.Simbolo;
import compiler.syntax.TabelaSimbolos;
import compiler.tree.DeclGlobal;
import compiler.tree.Tipo;
public class DeclVariavel implements Comando, DeclGlobal {
private LinkedList<String> idents;
private Tipo tipo;
public DeclVariavel() {
this.idents = new LinkedList<String>();
}
public DeclVariavel(LinkedList<String> ids, Tipo tipo) {
this.idents = ids;
this.tipo = tipo;
TabelaSimbolos tabela = TabelaSimbolos.getInstance();
for (String id : ids) {
Simbolo simbolo = new Simbolo(id, tipo);
tabela.put(simbolo);
}
}
public DeclVariavel(String id, Tipo tipo) {
this.idents = new LinkedList<String>();
idents.addLast(id);
this.tipo = tipo;
TabelaSimbolos tabela = TabelaSimbolos.getInstance();
Simbolo simbolo = new Simbolo(id, tipo);
tabela.put(simbolo);
}
public LinkedList<String> getIdents() {
return idents;
}
@Override
public Boolean verificarSemantica() {
TabelaSimbolos tabela = TabelaSimbolos.getInstance();
Simbolo simbolo = null;
for (String identificador : idents) {
simbolo = tabela.getSimbolo(identificador);
if (simbolo == null) {
System.err.println("Identificador ["+identificador+"] nao declarado anteriormente");
} else if (simbolo.getTipo() != tipo){
System.err.println("Identificador nao tem o mesmo tipo da expressao");
}
}
return true;
}
@Override
public String gerarCodigoIntermediario(String filename) {
return null;
}
@Override
public Tipo getTipo() {
// TODO Auto-generated method stub
return null;
}
}
| true |
0c7802a5bf99a006a85839e80d9e2e8f892c8c9e | Java | Suvidyapawaskar/Mercurytscucumberprojdemo | /src/test/java/com/mt/steps/Loginsteps.java | UTF-8 | 3,443 | 2.25 | 2 | [] | no_license | package com.mt.steps;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class Loginsteps {
public WebDriver driver;
@When("^user opens \"(.*)\" browser$")
public String Open_browser(String browsername)
{
if(browsername.equalsIgnoreCase("chrome"))
{("In open browser method");
System.out.println("In open browser method");
System.setProperty("webdriver.chrome.driver","G:\\Selenium Setup\\setup1\\chromedriver_win32 (8)\\chromedriver.exe");
driver = new ChromeDriver();
System.out.println("Chrome browser is opened successfully");
}
else if (browsername.equalsIgnoreCase("ie"))
{
System.setProperty("webdriver.ie.driver","G:\\Selenium Setup\\setup1\\IEDriverServer_x64_3.14.0 (8)\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
System.out.println("IE browser is opened successfully");
}
else
{
System.setProperty("webdriver.gecko.driver","G:\\Selenium Setup\\setup1\\geckodriver-v0.21.0-win64\\geckodriver.exe");
driver = new FirefoxDriver();
System.out.println("Fire fox browser is opened successfully");
}
return browsername;
}
@And("^user enters application url \"(.*)\"$")
public String EnterApplicationurl(String url)
{
driver.get(url);
System.out.println("Application url is entered successfully");
return url;
}
@And("^user waits \"(.*)\" seconds to page load$")
public void PageLoad(int timeoutseconds)
{
driver.manage().timeouts().pageLoadTimeout(timeoutseconds, TimeUnit.SECONDS);
}
@And("^user maximizes login page$")
public void Maximize_browser()
{
driver.manage().window().maximize();
}
@Given("^user is Login page of Mercury tours application$")
public void verify_Loginpage()
{
boolean act_flag=driver.findElement(By.xpath("//img[@src='/images/featured_destination.gif']")).isDisplayed();
System.out.println("Image is displayed:"+act_flag);
}
@When("^user enters \"(.*)\" as username$")
public String EnterUsername(String username)
{
driver.findElement(By.xpath("//input[@name='userName']")).sendKeys(username);
return username;
}
@And("^user enters \"(.*)\" as password$")
public String EnterPassword(String password)
{
driver.findElement(By.xpath("//input[@name='password']")).sendKeys(password);
return password;
}
@And("^user clicks on Sign In button$")
public void ClickonSignIn()
{
driver.findElement(By.xpath("//input[@name='login']")).click();
}
@Then("^user is on Flight Finder page$")
public void VerifyFlightfinderpage()
{
boolean act_flag1=driver.findElement(By.xpath("//img[@src='/images/masts/mast_flightfinder.gif']")).isDisplayed();
System.out.println("Flight finder page is opened"+act_flag1);
}
@When("^user clicks on Sign OFF button$")
public void ClickonSignOFF()
{
driver.findElement(By.linkText("SIGN-OFF")).click();
}
@Then("^user is Sign on page$")
public void VerifySignonpage()
{
boolean act_flag2=driver.findElement(By.xpath("//img[@src='/images/masts/mast_signon.gif']")).isDisplayed();
System.out.println("Sign on image is displayed:"+act_flag2);
}
}
| true |
c8ad692a1674bbee83f2ffa2a0cc5d88135ba872 | Java | storagebits/Vide | /src/de/malban/vide/vecx/cartridge/DS2431.java | UTF-8 | 39,945 | 1.9375 | 2 | [] | no_license |
package de.malban.vide.vecx.cartridge;
import de.malban.config.Configuration;
import de.malban.gui.CSAMainFrame;
import de.malban.gui.panels.LogPanel;
import java.io.File;
import java.io.Serializable;
// no overdrive emulation!
// no emulation of the ID code
// no protection of banks emulated
// main difference to DS2430
// a) 4 * 32 byte "banks"
// b) 16 byte as register/protection
// c) addressing uses two bytes (TA1 / TA2)
// d) Authentification byte (E/S)
// e) READ SP actually gives first 3 address bytes, instead of reading adresses from master
/**
*
* @author malban
*
*
* Emulation is only done in so far, that SP can be read and written,
* this is no FULL emulation of a DS2431!
*
*
* In General the below emulation are two state machines, one lowlevel "machine"
* which regulats bit manipulations and waits for timings slots and so on
*
* and one highlevel machine which emulates the
* commands, the highlevel uses the lowlevel machine and is "called" back from
* it when it is finished.
*
* Input/output is basically done via the lineIn and lineOut functions
* both functions in itself do not trigger any further actions.
*
* All steps of emulation are "triggered" from the "step" function.
* The step function should be called EVERY emulated cycle.
*
* The step function is basically the lowLevel statemachine, which on occassion
* triggers the highlevel.
*
*/
/*
; 1-Wire Timing constants
; Reset Pulse duration
; $032a = 810 cycles = 540us
; Presence Pulse duration
; $02d0 = 720 cycles = 480us
; Time Slot duration
; $78 = 120cycles = 80us
; Note:
;
; For reliability DS1W_RESETDUR and DS1W_TSLOTDUR are set above the
; minimums specified by the datasheet. To improve performance, values
; closer to the specified minimums may be used.
;
; DS1W_RESETDUR minimum = 480us
; DS1W_TSLOTDUR minimum = 60us
; 1-Wire ROM commands
DS1W_READROM equ $33
DS1W_SKIPROM equ $cc
DS1W_MATCHROM equ $55
DS1W_SEARCHROM equ $f0
*/
public class DS2431 implements Serializable, CartridgeInternalInterface
{
transient LogPanel log = (LogPanel) Configuration.getConfiguration().getDebugEntity();
public static final int LL_UNKOWN = 0;
public static final int LL_RESET_START = 1;
public static final int LL_RESETED = 2;
public static final int LL_PULSE_GENERATION = 3;
public static final int LL_PULSE_GENERATION_DONE = 4;
public static final int LL_READY_FOR_BITREAD = 5;
public static final int LL_BITREAD_STARTED = 6;
public static final int LL_READY_FOR_BITREAD_CONTINUE = 7;
public static final int LL_WAIT_FOR_BITWRITE_PULSE_START = 8;
public static final int LL_WAIT_FOR_BITWRITE_PULSE_END = 9;
public static final int LL_WAIT_FOR_BITWRITE_FINISH = 10;
String[] ll_names = {
"UNKOWN",
"RESET_START",
"RESETED",
"PULSE_GENERATION",
"PULSE_GENERATION_DONE",
"READY_FOR_BITREAD",
"BITREAD_STARTED",
"READY_FOR_BITREAD_CONTINUE",
"WAIT_FOR_BITWRITE_PULSE_START",
"WAIT_FOR_BITWRITE_PULSE_END",
"WAIT_FOR_BITWRITE_FINISH"
};
// Timings for low level communication (in 6809 cycles)
public static int RESET_CYCLE_DURATION = 720;
public static int WAIT_TO_GO_LOW_AFTER_RESET_CYCLES = 50;
public static int PULSE_PRESENT_DURATION_CYCLES = 700;
public static int BIT_TIMESLOT = 120; // 80u
public static int HIGH_BIT_CYLCE = 40; // something significntly smaller than 120
public static final int HL_WAIT_FOR_1W_COMMAND = 0;
public static final int HL_WAIT_FOR_2431_COMMAND = 1;
public static final int HL_WAIT_FOR_READ_ADDRESSTA1 = 2;
public static final int HL_WAIT_FOR_READ_ADDRESSTA2 = 3;
public static final int HL_WAIT_FOR_WRITESP_ADDRESSTAES1 = 4;
public static final int HL_WAIT_FOR_WRITESP_ADDRESSTAES2 = 5;
public static final int HL_WAIT_FOR_WRITESP_ADDRESSTAES3 = 6;
public static final int HL_WAIT_FOR_WRITESP_ADDRESSTAES4 = 7;
public static final int HL_READ_BYTE_FROM_SP = 8;
public static final int HL_WAIT_FOR_WRITE_ADDRESSTA1 = 9;
public static final int HL_WAIT_FOR_WRITE_ADDRESSTA2 = 10;
public static final int HL_WAIT_FOR_WRITE_ADDRESSTAES1 = 11;
public static final int HL_WAIT_FOR_WRITE_ADDRESSTAES2 = 12;
public static final int HL_WAIT_FOR_WRITE_ADDRESSTAES3 = 13;
public static final int HL_WRITE_BYTE_TO_SP = 14;
public static final int HL_SERIAL_1 = 15;
public static final int HL_SERIAL_2 = 16;
public static final int HL_SERIAL_3 = 17;
public static final int HL_SERIAL_4 = 18;
public static final int HL_SERIAL_5 = 19;
public static final int HL_SERIAL_6 = 20;
public static final int HL_SERIAL_7 = 21;
public static final int HL_SERIAL_8 = 22;
public static final int HL_SERIAL_END = 23;
String[] hl_names = {
"WAIT_FOR_1W_COMMAND",
"WAIT_FOR_2431_COMMAND",
"WAIT_FOR_READ_ADDRESSTA1",
"WAIT_FOR_READ_ADDRESSTA2",
"WAIT_FOR_WRITESP_ADDRESSTAES1",
"WAIT_FOR_WRITESP_ADDRESSTAES2",
"WAIT_FOR_WRITESP_ADDRESSTAES3",
"WAIT_FOR_WRITESP_ADDRESSTAES4",
"READ_BYTE_FROM_SP",
"WAIT_FOR_WRITE_ADDRESSTA1",
"WAIT_FOR_WRITE_ADDRESSTA2",
"WAIT_FOR_WRITE_ADDRESSTAES1",
"WAIT_FOR_WRITE_ADDRESSTAES2",
"WAIT_FOR_WRITE_ADDRESSTAES3",
"WRITE_BYTE_TO_SP",
"HL_SERIAL_1",
"HL_SERIAL_2",
"HL_SERIAL_3",
"HL_SERIAL_4",
"HL_SERIAL_5",
"HL_SERIAL_6",
"HL_SERIAL_7",
"HL_SERIAL_8",
"HL_SERIAL_END"
};
// 1 Wire protocoll commands
public static final int DS1W_NONE = 0x00;
public static final int DS1W_SKIPROM = 0xcc;
public static final int DS1W_MATCHROM = 0x55;
public static final int DS1W_SEARCHROM = 0xf0;
public static final int DS1W_READROM = 0x33;
public static final int DS1W_NOT_SUPPORTED = -1;
//public static final int DS1W_RESUME = 0xA5;
//public static final int DS1W_OVERDRIVE_SKIP_ROM = 0x3C;
//public static final int DS1W_OVERDRIVE_MATCH_ROM = 0x69;
// DS2431 commands
public static final int DS2431_NONE = 0x00;
public static final int DS2431_READMEM = 0xf0;
public static final int DS2431_WRITESP = 0x0f;
public static final int DS2431_READSP = 0xaa;
public static final int DS2431_COPYSP = 0x55;
public static final int DS2431_VALKEY = 0xa5;
public static final int DS2431_NOT_SUPPORTED = -1;
/*
; DS2431 Commands
DS2431_WRITESP equ $0f ; Write bytes to Scratch Pad
DS2431_COPYSP equ $55 ; Copy entire Scratch Pad to EEPROM
DS2431_READSP equ $aa ; Read bytes from Scratch Pad
DS2431_READMEM equ $f0 ; As READSP, but copies EEPROM to SP first
DS2431_LOCKAR equ $5a ; Lock Application Register
DS2431_READSR equ $66 ; Read Status Register
DS2431_WRITEAR equ $99 ; Write bytes to Application Register
DS2431_READAR equ $c3 ; Read bytes from Application Register
DS2431_VALKEY equ $a5 ; Validation byte for COPYSP and LOCKAR
*/
int FAMILY_CODE = 0x2d;
public byte[] SERIAL_NUMBER = new byte[6]; // 48 bit
int getCrc8()
{
int crc = 0;
crc = oneCRC8Step(crc, FAMILY_CODE);
crc = oneCRC8Step(crc, SERIAL_NUMBER[0]);
crc = oneCRC8Step(crc, SERIAL_NUMBER[1]);
crc = oneCRC8Step(crc, SERIAL_NUMBER[2]);
crc = oneCRC8Step(crc, SERIAL_NUMBER[3]);
crc = oneCRC8Step(crc, SERIAL_NUMBER[4]);
crc = oneCRC8Step(crc, SERIAL_NUMBER[5]);
return crc;
}
public long getSerial()
{
return SERIAL_NUMBER[0]+SERIAL_NUMBER[1]*256+SERIAL_NUMBER[2]*256*256+SERIAL_NUMBER[3]*256*256*256+SERIAL_NUMBER[4]*256*256*256*256+SERIAL_NUMBER[5]*256*256*256*256*256;
}
// CRC-8 (Dallas/Maxim 1-Wire Bus)
// X8 + X^5+ X^4+ 1
int CRC8_DALLAS_MSB = 0x31;//(1)00110001;
int CRC8_DALLAS_LSB = 0x8c;//10001100(1);
int oneCRC8Step(int crc, int data)
{
int i;
crc = crc ^ data;
for (i = 0; i < 8; i++)
{
if ((crc & 0x01) == 0x01)
crc = (crc >> 1) ^ CRC8_DALLAS_LSB;
else
crc >>= 1;
}
return crc;
}
public int getTA1()
{
return TA1;
}
public int getTA2()
{
return TA2;
}
public int getES()
{
return ES;
}
public int getCurrentOutValue()
{
return currentWriteByteComplete;
}
public void setIDByte1(int id)
{
epromData.data[0x86] = (byte) (id & 0xff);
}
public void setIDByte2(int id)
{
epromData.data[0x87] = (byte) (id & 0xff);
}
public String getLowLevelName()
{
return ll_names[lowLevelState];
}
public String getHighLevelName()
{
return hl_names[highLevelState];
}
public String get1WCommandName()
{
if (current1WCommand == DS1W_NONE) return "NONE";
if (current1WCommand == DS1W_SKIPROM) return "SKIPROM";
if (current1WCommand == DS1W_MATCHROM) return "MATCHROM";
if (current1WCommand == DS1W_SEARCHROM) return "SEARCHROM";
if (current1WCommand == DS1W_READROM) return "READROM";
return "NOT SUPPORTED ($"+String.format("$%02X", (current1WCommand&0xff) )+")";
}
public void init()
{
if (log == null)
log = (LogPanel) Configuration.getConfiguration().getDebugEntity();
}
public void deinit()
{
}
public String get2431CommandName()
{
if (current2431Command == DS2431_NONE) return "NONE";
if (current2431Command == DS2431_READMEM) return "READMEM";
if (current2431Command == DS2431_WRITESP) return "WRITESP";
if (current2431Command == DS2431_READSP) return "READSP";
if (current2431Command == DS2431_COPYSP) return "COPYSP";
if (current2431Command == DS2431_VALKEY) return "VALKEY";
return "NOT SUPPORTED ($"+String.format("$%02X", (current2431Command&0xff) )+")";
}
public boolean isInputToDS()
{
return isReadFromDS;
}
public String getSyncCycles()
{
return ""+dif;
}
public String getLineIn()
{
if (lineIn) return "1";
return "0";
}
public String getLineOut()
{
if (lineOut) return "1";
return "0";
}
public String getBitCounterFromVectrex()
{
return ""+bitsLoaded;
}
public String getBitCounterFromDS()
{
return ""+bitsOutputDone;
}
public String getBitFromDS()
{
return ""+(currentByteOutput & 0x01);
}
public String getBitFromVectrex()
{
return ""+(currentByteRead & 0x01);
}
public static final int MAX_DATA_LEN = 128+16;
public transient Cartridge cart;
static class EpromData implements Serializable
{
byte[] data = new byte[MAX_DATA_LEN];
EpromData()
{
// Asteroids eEprom Data
int[] ast=
{
0x40, 0x60, 0x48, 0x00, 0x00, 0x8f, 0x18, 0x34, 0xd1, 0xed, 0x04, 0x00, 0x00, 0x0e, 0x53, 0x03,
0x00, 0x00, 0x1c, 0xaf, 0x02, 0x00, 0x00, 0x24, 0x2e, 0x01, 0x00, 0x00, 0xd1, 0xed, 0x04, 0x00,
0x00, 0x0e, 0x53, 0x03, 0x00, 0x00, 0x1c, 0xaf, 0x02, 0x00, 0x00, 0x24, 0x2e, 0x01, 0x00, 0x00,
0xd1, 0xed, 0x04, 0x00, 0x00, 0x0e, 0x53, 0x03, 0x00, 0x00, 0x1c, 0xaf, 0x02, 0x00, 0x00, 0x24,
0x2e, 0x01, 0x00, 0x00, 0xd1, 0xed, 0x04, 0x00, 0x00, 0x0e, 0x53, 0x03, 0x00, 0x00, 0x1c, 0xaf,
0x02, 0x00, 0x00, 0x24, 0x2e, 0x01, 0x00, 0x00, 0x58, 0xa3, 0x00, 0x50, 0x00, 0x52, 0x58, 0x00,
0x20, 0x00, 0xd1, 0xed, 0x04, 0x00, 0x00, 0x0e, 0x53, 0x03, 0x00, 0x00, 0x1c, 0xaf, 0x02, 0x00,
0x00, 0x24, 0x2e, 0x01, 0x00, 0x00, 0x58, 0xa3, 0x00, 0x50, 0x00, 0x52, 0x58, 0x00, 0x20, 0x00
};
for (int i=0; i<0x80;i++)
{
data[i] = (byte) (ast[i] & 0x0ff);
}
}
}
EpromData epromData = new EpromData();
public byte[] getData()
{
return epromData.data;
}
long cycles = 0;
boolean line = false; // false is 0, true is 1
boolean old_line = false;
boolean lineIn = false; // false is 0, true is 1
boolean lineOut = false; // false is 0, true is 1
int lowLevelState = LL_UNKOWN;
int highLevelState = HL_WAIT_FOR_1W_COMMAND;
int currentByteRead = 0;
int bitsLoaded = 0;
int currentOutputAddress = 0;
int currentInputAddress = 0;
int currentByteOutput = 0;
int bitsOutputDone = 0;
int current1WCommand = DS1W_NONE;
int current2431Command = DS2431_NONE;
long dif = 0;
int currentWriteByteComplete = 0;
int currentWriteByteCompleteAddress = 0xff;
boolean isReadFromDS = false;
int TA1 = 0;
int TA2 = 0;
int ES = 0; // AA 00 PF 00 00 E2 E1 E0
public void reset()
{
cycles = 0;
line = false; // false is 0, true is 1
old_line = false;
lineIn = false; // false is 0, true is 1
lineOut = false; // false is 0, true is 1
lowLevelState = LL_UNKOWN;
highLevelState = HL_WAIT_FOR_1W_COMMAND;
currentByteRead = 0;
bitsLoaded = 0;
currentOutputAddress = 0;
currentInputAddress = 0;
currentByteOutput = 0;
bitsOutputDone = 0;
current1WCommand = DS1W_NONE;
current2431Command = DS2431_NONE;
dif = 0;
currentWriteByteComplete = 0;
isReadFromDS = false;
}
public DS2431(Cartridge c)
{
cart = c;
// Serial Asteroids from Thomas #2
SERIAL_NUMBER[0] = 0x60;
SERIAL_NUMBER[1] =(byte) 0x9e;
SERIAL_NUMBER[2] = 0x7f;
SERIAL_NUMBER[3] = 0x15;
SERIAL_NUMBER[4] = 0x00;
SERIAL_NUMBER[5] = 0x00;
// Serial Asteroids Deluxe from Thomas #2
SERIAL_NUMBER[0] = 0x4c;
SERIAL_NUMBER[1] =(byte) 0xa1;
SERIAL_NUMBER[2] = 0x7f;
SERIAL_NUMBER[3] = 0x15;
SERIAL_NUMBER[4] = 0x00;
SERIAL_NUMBER[5] = 0x00;
// robot arena
SERIAL_NUMBER[0] = 0x3b;
SERIAL_NUMBER[1] = 0x50;
SERIAL_NUMBER[2] = 0x43;
SERIAL_NUMBER[3] = 0x14;
SERIAL_NUMBER[4] = 0x00;
SERIAL_NUMBER[5] = 0x00;
}
public DS2431 clone()
{
DS2431 c = new DS2431(cart);
for (int i=0; i<MAX_DATA_LEN;i++)
{
c.epromData.data[i] = epromData.data[i];
}
c.cycles = cycles;
c.lineOut = lineOut;
c.line = line;
c.old_line = old_line;
c.lowLevelState = lowLevelState;
c.highLevelState = highLevelState;
c.isReadFromDS = isReadFromDS;
c.dif = dif;
c.currentByteRead = currentByteRead;
c.bitsLoaded = bitsLoaded;
c.currentOutputAddress = currentOutputAddress;
c.currentInputAddress = currentInputAddress;
c.currentByteOutput = currentByteOutput;
c.bitsOutputDone = bitsOutputDone;
c.currentWriteByteComplete = currentWriteByteComplete;
c.current1WCommand = current1WCommand;
c.current2431Command = current2431Command;
return c;
}
// receiving line information from the emulator (VIA)
public void linePB6In(boolean l)
{
line = l;
lineIn = l;
}
// sending line information to the emulator (VIA)
public void linePB6Out(boolean l)
{
line = l;
lineOut = l;
cart.setPB6FromCartridge(line);
}
// low level step
// this is triggered with every cycle from the emulator
// c is the current cylce counter of the vecx emulator, needed for timing
// (since I don't trust that we are called each cycle :-) )
public void step(long c)
{
dif = c - cycles;
if (line != old_line)
{
// reset cycle count on line changes (which are triggered from the outside)
cycles = c;
}
if ((!line) && (!old_line))
{
if (lowLevelState == LL_RESET_START) return;
// if line low longer than 480u
// initiate reset sequence
if (dif > RESET_CYCLE_DURATION) // 720 cycles = 480us reset duration as in datasheet
{
log.addLog("DS2431 Reset sequence 1) - start!", LogPanel.INFO);
lowLevelState = LL_RESET_START;
highLevelState = HL_WAIT_FOR_1W_COMMAND;
}
}
switch (lowLevelState)
{
case LL_WAIT_FOR_BITWRITE_PULSE_START:
{
if (!line)
{
lowLevelState = LL_WAIT_FOR_BITWRITE_PULSE_END;
log.addLog("DS2431 write byte pulse started!", LogPanel.INFO);
}
break;
}
case LL_WAIT_FOR_BITWRITE_PULSE_END:
{
if (line)
{
lowLevelState = LL_WAIT_FOR_BITWRITE_FINISH;
log.addLog("DS2431 write bit pulse ended, starting bit out...!", LogPanel.INFO);
// LSB first
boolean bit = (currentByteOutput & 0x01) == 0x01;
currentByteOutput = currentByteOutput>>1;
linePB6Out(bit);
bitsOutputDone++;
}
break;
}
case LL_WAIT_FOR_BITWRITE_FINISH:
{
if (dif >= BIT_TIMESLOT)
{
linePB6Out(true);
if (old_line)
{
log.addLog("DS2431 Write bit timeslot done (1)!", LogPanel.INFO);
}
else
{
log.addLog("DS2431 Write bit timeslot done (0)!", LogPanel.INFO);
}
if (bitsOutputDone == 8)
{
log.addLog("DS2431 Write completed: "+String.format("$%02X", currentWriteByteCompleteAddress )+"->"+String.format("$%02X", currentWriteByteComplete ), LogPanel.INFO);
highLevelStep();
}
else
{
lowLevelState = LL_WAIT_FOR_BITWRITE_PULSE_START;
}
}
break;
}
case LL_READY_FOR_BITREAD:
{
if (!line)
{
lowLevelState = LL_BITREAD_STARTED;
log.addLog("DS2431 Read command 1) - bit start!", LogPanel.INFO);
}
break;
}
case LL_READY_FOR_BITREAD_CONTINUE:
{
if (!line)
{
lowLevelState = LL_BITREAD_STARTED;
log.addLog("DS2431 Read command 1b) - bit start!", LogPanel.INFO);
}
break;
}
case LL_BITREAD_STARTED:
{
if (line)
{
// LSB first
currentByteRead = currentByteRead>>1;
if (dif <= HIGH_BIT_CYLCE)
{
currentByteRead+=128;
log.addLog("DS2431 Read command 2) - load 1!", LogPanel.INFO);
}
else
{
currentByteRead+=0;
log.addLog("DS2431 Read command 2) - load 0!", LogPanel.INFO);
}
lowLevelState = LL_READY_FOR_BITREAD_CONTINUE;
bitsLoaded++;
if (bitsLoaded == 8)
{
log.addLog("DS2431 Read command 3) - loaded: "+String.format("$%02X", currentByteRead ), LogPanel.INFO);
highLevelStep();
}
}
break;
}
case LL_RESET_START:
{
if (line)
{
lowLevelState = LL_RESETED;
log.addLog("DS2431 Reset sequence 2) - reset!", LogPanel.INFO);
}
break;
}
case LL_RESETED:
{
if (dif > WAIT_TO_GO_LOW_AFTER_RESET_CYCLES)
{
lowLevelState = LL_PULSE_GENERATION;
linePB6Out(false);
log.addLog("DS2431 Reset sequence 3) - pulse start!", LogPanel.INFO);
}
break;
}
case LL_PULSE_GENERATION:
{
if (dif > PULSE_PRESENT_DURATION_CYCLES)
{
lowLevelState = LL_READY_FOR_BITREAD;
currentByteRead = 0;
bitsLoaded = 0;
linePB6Out(true);
log.addLog("DS2431 Reset sequence 4) - pulse end!", LogPanel.INFO);
}
break;
}
default:
{
break;
}
}
old_line = line;
}
// High Level commands
void highLevelStep()
{
isReadFromDS = true;
if (highLevelState == HL_WAIT_FOR_1W_COMMAND)
{
switch (currentByteRead)
{
case DS1W_SKIPROM:
{
current1WCommand = DS1W_SKIPROM;
lowLevelState = LL_READY_FOR_BITREAD;
highLevelState = HL_WAIT_FOR_2431_COMMAND;
current2431Command = DS2431_NONE;
currentByteRead = 0;
bitsLoaded = 0;
log.addLog("DS2431 Command DS1W_SKIPROM - ignored (ROM read not supported anyway)! ("+cart.getPC()+")", LogPanel.INFO);
break;
}
case DS1W_MATCHROM:
{
current1WCommand = DS1W_MATCHROM;
current2431Command = DS2431_NONE;
lowLevelState = LL_READY_FOR_BITREAD;
highLevelState = HL_WAIT_FOR_1W_COMMAND;
currentByteRead = 0;
bitsLoaded = 0;
log.addLog("DS2431 Command DS1W_MATCHROM - not supported! ("+cart.getPC()+")", LogPanel.INFO);
break;
}
case DS1W_SEARCHROM:
{
current1WCommand = DS1W_SEARCHROM;
current2431Command = DS2431_NONE;
lowLevelState = LL_READY_FOR_BITREAD;
highLevelState = HL_WAIT_FOR_1W_COMMAND;
currentByteRead = 0;
bitsLoaded = 0;
log.addLog("DS2431 Command DS1W_SEARCHROM - not supported! ("+cart.getPC()+")", LogPanel.INFO);
break;
}
case DS1W_READROM:
{
current1WCommand = DS1W_READROM;
current2431Command = DS2431_NONE;
highLevelState = HL_SERIAL_2;
currentByteOutput = FAMILY_CODE;
currentWriteByteComplete = FAMILY_CODE;
currentWriteByteCompleteAddress = 0xff;
bitsOutputDone = 0;
lowLevelState = LL_WAIT_FOR_BITWRITE_PULSE_START;
isReadFromDS = false;
log.addLog("DS2431 Command DS1W_READROM! ("+cart.getPC()+")", LogPanel.INFO);
break;
}
default:
{
current1WCommand = DS1W_NOT_SUPPORTED;
break;
}
}
}
else if (highLevelState == HL_SERIAL_1)
{
log.addLog("1W Command READROM 1. byte!", LogPanel.INFO);
highLevelState = HL_SERIAL_2;
currentByteOutput = FAMILY_CODE;
currentWriteByteComplete = FAMILY_CODE;
bitsOutputDone = 0;
lowLevelState = LL_WAIT_FOR_BITWRITE_PULSE_START;
isReadFromDS = false;
}
else if (highLevelState == HL_SERIAL_2)
{
log.addLog("1W Command READROM 2. byte!", LogPanel.INFO);
highLevelState = HL_SERIAL_3;
currentByteOutput = SERIAL_NUMBER[0];
currentWriteByteComplete = SERIAL_NUMBER[0];
bitsOutputDone = 0;
lowLevelState = LL_WAIT_FOR_BITWRITE_PULSE_START;
isReadFromDS = false;
}
else if (highLevelState == HL_SERIAL_3)
{
log.addLog("1W Command READROM 3. byte!", LogPanel.INFO);
highLevelState = HL_SERIAL_4;
currentByteOutput = SERIAL_NUMBER[1];
currentWriteByteComplete = SERIAL_NUMBER[1];
bitsOutputDone = 0;
lowLevelState = LL_WAIT_FOR_BITWRITE_PULSE_START;
isReadFromDS = false;
}
else if (highLevelState == HL_SERIAL_4)
{
log.addLog("1W Command READROM 4. byte!", LogPanel.INFO);
highLevelState = HL_SERIAL_5;
currentByteOutput = SERIAL_NUMBER[2];
currentWriteByteComplete = SERIAL_NUMBER[2];
bitsOutputDone = 0;
lowLevelState = LL_WAIT_FOR_BITWRITE_PULSE_START;
isReadFromDS = false;
}
else if (highLevelState == HL_SERIAL_5)
{
log.addLog("1W Command READROM 4. byte!", LogPanel.INFO);
highLevelState = HL_SERIAL_6;
currentByteOutput = SERIAL_NUMBER[3];
currentWriteByteComplete = SERIAL_NUMBER[3];
bitsOutputDone = 0;
lowLevelState = LL_WAIT_FOR_BITWRITE_PULSE_START;
isReadFromDS = false;
}
else if (highLevelState == HL_SERIAL_6)
{
log.addLog("1W Command READROM 6. byte!", LogPanel.INFO);
highLevelState = HL_SERIAL_7;
currentByteOutput = SERIAL_NUMBER[4];
currentWriteByteComplete = SERIAL_NUMBER[4];
bitsOutputDone = 0;
lowLevelState = LL_WAIT_FOR_BITWRITE_PULSE_START;
isReadFromDS = false;
}
else if (highLevelState == HL_SERIAL_7)
{
log.addLog("1W Command READROM 7. byte!", LogPanel.INFO);
highLevelState = HL_SERIAL_8;
currentByteOutput = SERIAL_NUMBER[5];
currentWriteByteComplete = SERIAL_NUMBER[5];
bitsOutputDone = 0;
lowLevelState = LL_WAIT_FOR_BITWRITE_PULSE_START;
isReadFromDS = false;
}
else if (highLevelState == HL_SERIAL_8)
{
log.addLog("1W Command READROM 8. byte!", LogPanel.INFO);
highLevelState = HL_SERIAL_END;
currentByteOutput = getCrc8();
currentWriteByteComplete = currentByteOutput;
bitsOutputDone = 0;
lowLevelState = LL_WAIT_FOR_BITWRITE_PULSE_START;
isReadFromDS = false;
}
else if (highLevelState == HL_SERIAL_END)
{
current1WCommand = DS1W_READROM;
current2431Command = DS2431_NONE;
lowLevelState = LL_READY_FOR_BITREAD;
highLevelState = HL_WAIT_FOR_2431_COMMAND;
currentByteRead = 0;
bitsLoaded = 0;
log.addLog("DS2431 Command READROM - finished!", LogPanel.INFO);
}
else if (highLevelState == HL_WAIT_FOR_2431_COMMAND)
{
switch (currentByteRead)
{
case DS2431_READMEM:
{
current2431Command = DS2431_READMEM;
loadBytesFromDisk();
lowLevelState = LL_READY_FOR_BITREAD;
highLevelState = HL_WAIT_FOR_READ_ADDRESSTA1;
currentByteRead = 0;
bitsLoaded = 0;
log.addLog("DS2431 Command DS2431_READMEM - accepted! ("+cart.getPC()+")", LogPanel.INFO);
break;
}
// read bytes from ds
case DS2431_READSP:
{
current2431Command = DS2431_READSP;
log.addLog("DS2431 Command DS2431_READSP - accepted! ("+cart.getPC()+")", LogPanel.INFO);
highLevelState = HL_WAIT_FOR_WRITESP_ADDRESSTAES2;
lowLevelState = LL_WAIT_FOR_BITWRITE_PULSE_START;
currentByteOutput = TA1;
currentWriteByteComplete = TA1;
currentWriteByteCompleteAddress = 0xff;
bitsOutputDone = 0;
isReadFromDS = false;
break;
}
// write bytes to ds
case DS2431_WRITESP:
{
isReadFromDS = true;
current2431Command = DS2431_WRITESP;
lowLevelState = LL_READY_FOR_BITREAD;
highLevelState = HL_WAIT_FOR_WRITE_ADDRESSTA1;
currentByteRead = 0;
bitsLoaded = 0;
log.addLog("DS2431 Command DS2431_WRITESP - accepted! ("+cart.getPC()+")", LogPanel.INFO);
break;
}
case DS2431_COPYSP:
{
current2431Command = DS2431_COPYSP;
lowLevelState = LL_READY_FOR_BITREAD;
highLevelState = HL_WAIT_FOR_WRITE_ADDRESSTAES1;
currentByteRead = 0;
bitsLoaded = 0;
log.addLog("DS2431 Command DS2431_COPYSP - accepted! ("+cart.getPC()+")", LogPanel.INFO);
break;
}
case DS2431_VALKEY:
{
current2431Command = DS2431_VALKEY;
// do nothing, what is there to verify?
lowLevelState = LL_READY_FOR_BITREAD;
highLevelState = HL_WAIT_FOR_2431_COMMAND;
currentByteRead = 0;
bitsLoaded = 0;
log.addLog("DS2431 Command DS2431_VALKEY - accepted! ("+cart.getPC()+")", LogPanel.INFO);
break;
}
default:
{
current2431Command = DS2431_NOT_SUPPORTED;
break;
}
}
}
else if (highLevelState == HL_WAIT_FOR_READ_ADDRESSTA1)
{
TA1 = currentByteRead;
log.addLog("DS2431 Command READ TA1 Address received!", LogPanel.INFO);
current2431Command = DS2431_READSP;
lowLevelState = LL_READY_FOR_BITREAD;
highLevelState = HL_WAIT_FOR_READ_ADDRESSTA2;
currentByteRead = 0;
bitsLoaded = 0;
}
else if (highLevelState == HL_WAIT_FOR_READ_ADDRESSTA2)
{
TA2 = currentByteRead;
currentOutputAddress = TA1+256*TA2;
log.addLog("DS2431 Command READ TA2 Address received!", LogPanel.INFO);
if (current2431Command == DS2431_READMEM)
{
initOutputNextByte();
}
else
{
initOutputNextByte();
}
}
else if (highLevelState == HL_WAIT_FOR_WRITESP_ADDRESSTAES1)
{
// not used
highLevelState = HL_WAIT_FOR_WRITESP_ADDRESSTAES2;
currentByteOutput = TA1;
currentWriteByteComplete = TA1;
currentWriteByteCompleteAddress = 0xff;
bitsOutputDone = 0;
lowLevelState = LL_WAIT_FOR_BITWRITE_PULSE_START;
isReadFromDS = false;
log.addLog("DS2431 Command WRITE TA1 Address started!", LogPanel.INFO);
}
else if (highLevelState == HL_WAIT_FOR_WRITESP_ADDRESSTAES2)
{
log.addLog("TA1 Address written:" +String.format("$%02X", currentWriteByteComplete ), LogPanel.INFO);
highLevelState = HL_WAIT_FOR_WRITESP_ADDRESSTAES3;
currentByteOutput = TA2;
currentWriteByteComplete = TA2;
currentWriteByteCompleteAddress = 0xff;
bitsOutputDone = 0;
lowLevelState = LL_WAIT_FOR_BITWRITE_PULSE_START;
isReadFromDS = false;
log.addLog("DS2431 Command WRITE TA2 Address started!", LogPanel.INFO);
}
else if (highLevelState == HL_WAIT_FOR_WRITESP_ADDRESSTAES3)
{
log.addLog("TA2 Address written:" +String.format("$%02X", currentWriteByteComplete ), LogPanel.INFO);
highLevelState = HL_WAIT_FOR_WRITESP_ADDRESSTAES4;
currentByteOutput = ES;
currentWriteByteComplete = ES;
currentWriteByteCompleteAddress = 0xff;
bitsOutputDone = 0;
lowLevelState = LL_WAIT_FOR_BITWRITE_PULSE_START;
isReadFromDS = false;
log.addLog("DS2431 Command WRITE ES Address started!", LogPanel.INFO);
}
else if (highLevelState == HL_WAIT_FOR_WRITESP_ADDRESSTAES4)
{
log.addLog("ES Address written:" +String.format("$%02X", currentWriteByteComplete ), LogPanel.INFO);
currentOutputAddress = TA1+256*TA2;
log.addLog("DS2431 Continuing read from DS2431...", LogPanel.INFO);
initOutputNextByte();
}
else if (highLevelState == HL_READ_BYTE_FROM_SP)
{
log.addLog("DS2431 Continuing read from DS2431...", LogPanel.INFO);
initOutputNextByte();
}
else if (highLevelState == HL_WAIT_FOR_WRITE_ADDRESSTA1)
{
TA1 = currentByteRead;
isReadFromDS = true;
current2431Command = DS2431_WRITESP;
lowLevelState = LL_READY_FOR_BITREAD;
highLevelState = HL_WAIT_FOR_WRITE_ADDRESSTA2;
currentByteRead = 0;
bitsLoaded = 0;
log.addLog("DS2431 Command WRITE Address TA1 received!", LogPanel.INFO);
}
else if (highLevelState == HL_WAIT_FOR_WRITE_ADDRESSTA2)
{
TA2 = currentByteRead;
currentInputAddress = TA1+256*TA2;
log.addLog("DS2431 Command WRITE Address TA2 received!", LogPanel.INFO);
initInputNextByte();
}
else if (highLevelState == HL_WAIT_FOR_WRITE_ADDRESSTAES1)
{
TA1 = currentByteRead;
isReadFromDS = true;
lowLevelState = LL_READY_FOR_BITREAD;
highLevelState = HL_WAIT_FOR_WRITE_ADDRESSTAES2;
currentByteRead = 0;
bitsLoaded = 0;
log.addLog("DS2431 Command WRITE Address TA1 received!", LogPanel.INFO);
}
else if (highLevelState == HL_WAIT_FOR_WRITE_ADDRESSTAES2)
{
TA2 = currentByteRead;
currentInputAddress = TA1+256*TA2;
isReadFromDS = true;
lowLevelState = LL_READY_FOR_BITREAD;
highLevelState = HL_WAIT_FOR_WRITE_ADDRESSTAES3;
currentByteRead = 0;
bitsLoaded = 0;
log.addLog("DS2431 Command WRITE Address TA2 received!", LogPanel.INFO);
}
else if (highLevelState == HL_WAIT_FOR_WRITE_ADDRESSTAES3)
{
// ignoring the actual SP addresses that are saved (TAx) but always saving everything
ES = currentByteRead;
log.addLog("DS2431 Command WRITE Address ES received!", LogPanel.INFO);
if (current2431Command == DS2431_COPYSP)
{
highLevelState = HL_WAIT_FOR_2431_COMMAND;
saveBytestoDisk();
log.addLog("Scratchpad DS2431 saved to disk!", LogPanel.INFO);
}
else
initInputNextByte();
}
else if (highLevelState == HL_WRITE_BYTE_TO_SP)
{
log.addLog("DS2431 Continuing write to DS2431..., byte written "+String.format("$%02X", currentByteRead )+"->"+String.format("$%02X", currentInputAddress ), LogPanel.INFO);
epromData.data[currentInputAddress%MAX_DATA_LEN] = (byte) currentByteRead;
currentInputAddress++;
initInputNextByte();
}
}
public static EpromData loadData(String serialname)
{
return (EpromData)CSAMainFrame.deserialize(serialname);
}
public static boolean saveData(String serialname, EpromData d)
{
return CSAMainFrame.serialize(d, serialname);
}
void loadBytesFromDisk()
{
epromData = loadData(getSaveName());
if (epromData == null)
{
epromData = new EpromData();
}
}
void saveBytestoDisk()
{
saveData(getSaveName(), epromData);
}
// output from DS2431 to VIA
void initOutputNextByte()
{
highLevelState = HL_READ_BYTE_FROM_SP;
currentByteOutput = epromData.data[currentOutputAddress%MAX_DATA_LEN];
currentWriteByteComplete = currentByteOutput;
currentWriteByteCompleteAddress = currentOutputAddress%MAX_DATA_LEN;
bitsOutputDone = 0;
currentOutputAddress++;
lowLevelState = LL_WAIT_FOR_BITWRITE_PULSE_START;
isReadFromDS = false;
}
// input from VIA to DS2431
void initInputNextByte()
{
highLevelState = HL_WRITE_BYTE_TO_SP;
bitsLoaded = 0;
currentByteRead = 0;
lowLevelState = LL_READY_FOR_BITREAD;
isReadFromDS = true;
}
public String getSaveName()
{
return cart.cartName+".ds2431.ser";
}
public boolean isActive()
{
return highLevelState != HL_WAIT_FOR_1W_COMMAND;
}
public boolean usesPB6() {return true;}
public void lineIRQIn(boolean i)
{
}
}
| true |
a4c0ae37074203ef049886516474994efa3fb8cb | Java | CynPa/gambaSoftware | /MIO/AS2/src/main/java/com/asinfo/as2/programacion/TareaSincronizarGuiaRemision.java | UTF-8 | 3,037 | 1.9375 | 2 | [] | no_license | /* 1: */ package com.asinfo.as2.programacion;
/* 2: */
/* 3: */ import com.asinfo.as2.compronteselectronicos.ServicioComprobanteElectronicoPeriodico;
/* 4: */ import com.asinfo.as2.enumeraciones.DocumentoBase;
/* 5: */ import com.asinfo.as2.utils.ServiceLocator;
/* 6: */ import java.io.PrintStream;
/* 7: */ import java.util.ArrayList;
/* 8: */ import java.util.List;
/* 9: */ import javax.naming.Context;
/* 10: */ import javax.naming.InitialContext;
/* 11: */ import javax.naming.NamingException;
/* 12: */ import org.quartz.Job;
/* 13: */ import org.quartz.JobDataMap;
/* 14: */ import org.quartz.JobExecutionContext;
/* 15: */ import org.quartz.JobExecutionException;
/* 16: */
/* 17: */ public class TareaSincronizarGuiaRemision
/* 18: */ implements Job
/* 19: */ {
/* 20: */ private ServicioComprobanteElectronicoPeriodico servicioComprobanteElectronicoPeriodico;
/* 21: */ private Context context;
/* 22: */
/* 23: */ public ServicioComprobanteElectronicoPeriodico getServicioComprobanteElectronicoPeriodico()
/* 24: */ {
/* 25:24 */ if (this.servicioComprobanteElectronicoPeriodico == null) {
/* 26: */ try
/* 27: */ {
/* 28:26 */ this.context = new InitialContext();
/* 29:27 */ this.servicioComprobanteElectronicoPeriodico = ((ServicioComprobanteElectronicoPeriodico)this.context.lookup("java:global/" + ServiceLocator.APP_NAME + "/ServicioComprobanteElectronicoPeriodicoImpl"));
/* 30: */ }
/* 31: */ catch (NamingException e)
/* 32: */ {
/* 33:30 */ e.printStackTrace();
/* 34: */ }
/* 35: */ }
/* 36:33 */ return this.servicioComprobanteElectronicoPeriodico;
/* 37: */ }
/* 38: */
/* 39: */ public void execute(JobExecutionContext jec)
/* 40: */ throws JobExecutionException
/* 41: */ {
/* 42:37 */ Integer idOrganizacion = (Integer)jec.getMergedJobDataMap().get("idOrganizacion");
/* 43: */ try
/* 44: */ {
/* 45:39 */ List<DocumentoBase> listaDocumentoBase = new ArrayList();
/* 46:40 */ listaDocumentoBase.add(DocumentoBase.GUIA_REMISION);
/* 47: */
/* 48:42 */ getServicioComprobanteElectronicoPeriodico().sincronizarComprobantesSRI(idOrganizacion.intValue(), listaDocumentoBase);
/* 49: */ }
/* 50: */ catch (Exception e)
/* 51: */ {
/* 52:44 */ System.out.println("******************************** ERROR SINCRONIZANDO FACTURAS ELECTRONICAS AL SRI *****************************");
/* 53:45 */ e.printStackTrace();
/* 54:46 */ System.out.println("****************************** FIN ERROR SINCRONIZANDO FACTURAS ELECTRONICAS AL SRI ***************************");
/* 55: */ }
/* 56: */ }
/* 57: */ }
/* Location: C:\backups\AS2(26-10-2017)\WEB-INF\classes\
* Qualified Name: com.asinfo.as2.programacion.TareaSincronizarGuiaRemision
* JD-Core Version: 0.7.0.1
*/ | true |
93800778b81e99745ab43c0528368f6a2f5ee5ab | Java | Paulokim1/Q2_PI_DesAgil_2021.1 | /src/br/insper/edu/desagil/pi/Video.java | UTF-8 | 913 | 2.90625 | 3 | [] | no_license | package br.insper.edu.desagil.pi;
import java.util.HashMap;
import java.util.Map;
public class Video {
private int id;
private Usuario usuario;
private Produto produto;
private Map<Usuario, Integer> avaliacoes;
public Video(int id, Usuario usuario, Produto produto) {
this.id = id;
this.usuario = usuario;
this.produto = produto;
this.avaliacoes = new HashMap<>();
}
public void adicionaAvaliacao(Usuario usuario, int avaliacao) {
if (this.usuario.getNome() != usuario.getNome() & avaliacao >= 1 & avaliacao <= 5) {
this.avaliacoes.put(usuario, avaliacao);
}
}
public int mediaAvaliacoes() {
double s = 0;
for (Usuario usuario : this.avaliacoes.keySet()) {
s += (double) this.avaliacoes.get(usuario);
}
if (this.avaliacoes.size() == 0) {
return 0;
}
double media = s/this.avaliacoes.size();
int mediaFinal = (int) Math.round(media);
return mediaFinal;
}
}
| true |
4ccdee6367761de757e1382dbf3cfd4d4bd9f2b8 | Java | moutainhigh/sunnyday | /pst/src/main/java/com/softtek/pst/controller/FinanceController.java | UTF-8 | 13,012 | 2.015625 | 2 | [] | no_license | package com.softtek.pst.controller;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import jxl.Workbook;
import jxl.format.UnderlineStyle;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.softtek.pst.model.LoggingModel;
import com.softtek.pst.model.ProjectFinancialModel;
import com.softtek.pst.model.ProjectModel;
import com.softtek.pst.model.UserModel;
import com.softtek.pst.service.LoggingService;
import com.softtek.pst.service.ProjectFinancialService;
import com.softtek.pst.service.ProjectService;
import com.softtek.pst.util.Page;
@Controller
@RequestMapping("/projectsManagement/finance")
public class FinanceController {
private Logger logger = Logger.getLogger(FinanceController.class);
private final int ORIGIN_X = 0; // 报表中写入内容的起始横坐标,即excel的行
private final int ORIGIN_Y = 0; // 报表中写入内容的起始纵坐标,即excel的列
@Autowired
private ProjectService projectService;
@Autowired
private LoggingService loggingService;
@Autowired
private ProjectFinancialService projectFinancialService;
@RequestMapping(value = "financeList")
public String financeList(HttpServletRequest request) {
request.setAttribute("url", request.getServletPath());
return "finance/financeList";
}
@RequestMapping(value = "getFinances")
@ResponseBody
public Page<ProjectModel> getFinances(Integer start, Integer length, String column, String dir, String sch,
HttpServletRequest request,HttpSession session) {
if (sch != null && !sch.equals("")) {
sch = "%" + sch + "%";
} else {
sch = "%%";
}
Page<ProjectModel> page = projectService.getProjectsForFinance(start, length, column, dir, sch);
session.setAttribute("search", sch);
return page;
}
@RequestMapping(value = "updateFinance")
public ModelAndView updateFinance(HttpServletRequest request, Integer id) {
request.setAttribute("url", request.getServletPath());
ProjectModel project = projectService.getProjectById(id);
return new ModelAndView("finance/updateFinance", "project", project);
}
@RequestMapping(value = "addFinanceReceive")
public ModelAndView addFinanceReceive(HttpServletRequest request,Integer projectId) {
request.setAttribute("url", request.getServletPath());
// request.setAttribute("projectId",projectId);
return new ModelAndView("finance/addFinanceReceive","projectId",projectId);
}
@RequestMapping(value="addFinancePayment")
public ModelAndView addFinancePayment(HttpServletRequest request,Integer projectId){
request.setAttribute("url", request.getServletPath());
return new ModelAndView("finance/addFinancePayment","projectId",projectId);
}
@RequestMapping(value="viewFinanceReceive")
public ModelAndView viewFinanceReceive(HttpServletRequest request,Integer projectId){
request.setAttribute("url", request.getServletPath());
List<ProjectFinancialModel> list = projectFinancialService.queryFinancialReceive(projectId);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
list.stream().forEach(a -> {
a.setCreateTimeStr(sdf.format(a.getCreateTime()));
});
return new ModelAndView("finance/viewFinanceReceive","list",list);
}
@RequestMapping(value="viewFinancePayment")
public ModelAndView viewFinancePayment(HttpServletRequest request,Integer projectId){
request.setAttribute("url", request.getServletPath());
List<ProjectFinancialModel> list = projectFinancialService.queryFinancialPayment(projectId);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
list.stream().forEach(a -> {
a.setCreateTimeStr(sdf.format(a.getCreateTime()));
});
return new ModelAndView("finance/viewFinancePayment","list",list);
}
@RequestMapping("/update")
@ResponseBody
public Map<String, Object> update(HttpServletRequest request, ProjectModel project) {
Map<String, Object> result = new HashMap<>();
int res = projectService.updateFinance(project);
if (res == 1) {
result.put("success", true);
// 记录日志
UserModel user = (UserModel) request.getSession().getAttribute("user");
LoggingModel loggingModel = new LoggingModel();
loggingModel.setOperator(user.getChineseName());
SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String datetime = (date.format(new Date())).toString();
loggingModel.setAction(user.getChineseName() + "于" + datetime + "更新项目【" + project.getProjectName() + "】财务信息");
loggingModel.setUserId(user.getUserId());
loggingModel.setEventType(1);
loggingModel.setEventName("增加");
loggingModel.setTables("project");
loggingService.addLogging(loggingModel);
} else {
result.put("success", false);
result.put("errmsg", "更新项目财务信息失败,请稍候再试或联系管理员");
}
return result;
}
@RequestMapping("/addProjectFinancial")
@ResponseBody
public Map<String,Object> addProjectFinancial(HttpServletRequest request,ProjectFinancialModel projectFinancial){
Map<String,Object> map = new HashMap<String, Object>();
int result = projectFinancialService.addProjectFinancial(projectFinancial);
if(result == 1){
// 记录日志
UserModel user = (UserModel) request.getSession().getAttribute("user");
ProjectModel project = projectService.getProjectById(projectFinancial.getProjectId());
LoggingModel loggingModel = new LoggingModel();
loggingModel.setOperator(user.getChineseName());
SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String datetime = (date.format(new Date())).toString();
if(projectFinancial.getReceive() > 0){
loggingModel.setAction(user.getChineseName() + "于" + datetime + "对项目:【" + project.getProjectName() + "】添加收款");
}else{
loggingModel.setAction(user.getChineseName() + "于" + datetime + "对项目:【" + project.getProjectName() + "】添加付款");
}
loggingModel.setUserId(user.getUserId());
loggingModel.setEventType(1);
loggingModel.setEventName("增加");
loggingModel.setTables("project_financial");
loggingService.addLogging(loggingModel);
map.put("success", true);
}else{
map.put("success", false);
map.put("errmsg", "添加失败,请稍候再试或联系管理员");
}
return map;
}
@RequestMapping("/export")
public void export(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws WriteException{
String sch = (String) session.getAttribute("search");
List<ProjectModel> list = projectService.getProjectsForFinance(null, null, "create_time", "desc", sch).getData();
WritableWorkbook wb = null;
OutputStream stream = null;
SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd.hh.mm");
String fileName = "财务管理列表" + format.format(new Date()) + ".xls";
try {
fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
response.setContentType("application/vnd.ms-excel");
stream = response.getOutputStream();
} catch (IOException e1) {
logger.info(e1.getMessage());
}
int i = 0;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
WritableFont wfont = new WritableFont(WritableFont.ARIAL, 12, WritableFont.BOLD);
WritableFont wfont1 = new WritableFont(WritableFont.ARIAL, 10, WritableFont.NO_BOLD);
WritableFont wf_title = new WritableFont(WritableFont.ARIAL, 16, WritableFont.BOLD, false,
UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.BLACK);
WritableCellFormat wcf_title = new WritableCellFormat(wf_title); // 标题单元格定义
try {
wcf_title.setAlignment(jxl.format.Alignment.CENTRE);
WritableCellFormat wcf = new WritableCellFormat(wfont);
WritableCellFormat wcf1 = new WritableCellFormat(wfont1);
wcf.setAlignment(jxl.format.Alignment.CENTRE); // 设置标题居中对齐
wcf1.setAlignment(jxl.format.Alignment.CENTRE); // 设置内容居中对齐
wcf.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);// 设置边框
wcf1.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);// 设置边框
// 创建workbook
wb = Workbook.createWorkbook(stream);
WritableSheet sheet = wb.createSheet("财务管理列表", i++);
Label label;
label = new Label(ORIGIN_Y, ORIGIN_X, "财务管理列表", wcf_title);
sheet.addCell(label);
sheet.setColumnView(ORIGIN_Y, 21);
label = new Label(ORIGIN_Y, ORIGIN_X + 1, "项目编号", wcf);
sheet.addCell(label);
label = new Label(ORIGIN_Y + 1, ORIGIN_X + 1, "项目名称", wcf);
sheet.addCell(label);
label = new Label(ORIGIN_Y + 2, ORIGIN_X + 1, "项目经理", wcf);
sheet.addCell(label);
label = new Label(ORIGIN_Y + 3, ORIGIN_X + 1, "客户经理", wcf);
sheet.addCell(label);
label = new Label(ORIGIN_Y + 4, ORIGIN_X + 1, "开始时间", wcf);
sheet.addCell(label);
label = new Label(ORIGIN_Y + 5, ORIGIN_X + 1, "结束时间", wcf);
sheet.addCell(label);
label = new Label(ORIGIN_Y + 6, ORIGIN_X + 1, "总价", wcf);
sheet.addCell(label);
label = new Label(ORIGIN_Y + 7, ORIGIN_X + 1, "已收款", wcf);
sheet.addCell(label);
label = new Label(ORIGIN_Y + 8, ORIGIN_X + 1, "未收款", wcf);
sheet.addCell(label);
label = new Label(ORIGIN_Y + 9, ORIGIN_X + 1, "外包款", wcf);
sheet.addCell(label);
label = new Label(ORIGIN_Y + 10, ORIGIN_X + 1, "已付款", wcf);
sheet.addCell(label);
label = new Label(ORIGIN_Y + 11, ORIGIN_X + 1, "未付款", wcf);
sheet.addCell(label);
for(ProjectModel project : list){
i++;
label = new Label(ORIGIN_Y, ORIGIN_X + i, project.getProjectCode(), wcf1);
sheet.addCell(label);
label = new Label(ORIGIN_Y + 1, ORIGIN_X + i, project.getProjectName(), wcf1);
sheet.addCell(label);
sheet.setColumnView(1, 18);
label = new Label(ORIGIN_Y + 2, ORIGIN_X + i, project.getProjectManager(), wcf1);
sheet.addCell(label);
sheet.setColumnView(ORIGIN_Y + 2, 18);
label = new Label(ORIGIN_Y + 3, ORIGIN_X + i, project.getImplementManager(), wcf1);
sheet.addCell(label);
sheet.setColumnView(ORIGIN_Y + 3, 18);
label = new Label(ORIGIN_Y + 4, ORIGIN_X + i,sdf.format(project.getStartTime()), wcf1);
sheet.addCell(label);
sheet.setColumnView(ORIGIN_Y + 4, 18);
label = new Label(ORIGIN_Y + 5, ORIGIN_X + i, sdf.format(project.getLeadTime()), wcf1);
sheet.addCell(label);
sheet.setColumnView(ORIGIN_Y + 5, 18);
label = new Label(ORIGIN_Y + 6, ORIGIN_X + i,"¥" + String.valueOf(project.getCrTotal()), wcf1);
sheet.addCell(label);
sheet.setColumnView(ORIGIN_Y + 6, 18);
label = new Label(ORIGIN_Y + 7, ORIGIN_X + i, "¥" + String.valueOf(project.getReceive()), wcf1);
sheet.addCell(label);
sheet.setColumnView(ORIGIN_Y + 7, 18);
label = new Label(ORIGIN_Y + 8, ORIGIN_X + i, "¥" + String.valueOf(project.getUnreceive()), wcf1);
sheet.addCell(label);
sheet.setColumnView(ORIGIN_Y + 8, 18);
label = new Label(ORIGIN_Y + 9, ORIGIN_X + i, "¥" + String.valueOf(project.getOutsourcingQuotation()), wcf1);
sheet.addCell(label);
sheet.setColumnView(ORIGIN_Y + 9, 18);
label = new Label(ORIGIN_Y + 10, ORIGIN_X + i, "¥" + String.valueOf(project.getPayment()), wcf1);
sheet.addCell(label);
sheet.setColumnView(ORIGIN_Y + 10, 18);
label = new Label(ORIGIN_Y + 11, ORIGIN_X + i, "¥" + String.valueOf(project.getUnpayment()), wcf1);
sheet.addCell(label);
sheet.setColumnView(ORIGIN_Y + 11, 18);
}
// 记录日志
UserModel user = (UserModel) request.getSession().getAttribute("user");
LoggingModel loggingModel = new LoggingModel();
loggingModel.setOperator(user.getChineseName());
SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String datetime = (date.format(new Date())).toString();
loggingModel.setAction(user.getChineseName() + "于" + datetime + "导出了财务管理列表");
loggingModel.setUserId(user.getUserId());
loggingModel.setEventType(4);
loggingModel.setEventName("导出");
loggingModel.setTables("project");
loggingService.addLogging(loggingModel);
wb.write();
wb.close();
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| true |
c937a5df038193f28a92d69b400391518ee8c0d7 | Java | vasylya/kamon.io | /_code_examples/kamon-core-examples/src/main/java/kamon/examples/java/TraceContextManipulation.java | UTF-8 | 2,569 | 2.984375 | 3 | [] | no_license | package kamon.examples.java;
import kamon.Kamon;
import kamon.trace.Segment;
import kamon.trace.TraceContext;
import kamon.trace.Tracer;
import scala.Some;
public class TraceContextManipulation {
public static void main(String[] args) throws InterruptedException {
Kamon.start();
// tag:creating-a-trace-context:start
final TraceContext newContext = Kamon.tracer().newContext("test-trace");
Thread.sleep(3000);
newContext.finish();
// tag:creating-a-trace-context:end
// tag:new-context:start
final TraceContext testTrace = Kamon.tracer().newContext("test-trace");
final TraceContext testTraceWithToken = Kamon.tracer().newContext("trace-with-token", Some.apply("token-42"));
// You can rename a trace before it is finished.
testTrace.rename("cool-functinality-X");
testTrace.finish();
// And you can also access it's token if you want to.
System.out.println("Test Trace Token: " + testTrace.token());
// tag:new-context:end
// tag:new-context-block:start
Tracer.withNewContext("GetUserDetails", true, ()-> {
// While this block of codes executes a new TraceContext
// is set as the current context and finished after the
// block returns.
System.out.println("Current Trace Token: " + Tracer.currentContext().token());
return "Some awesome result";
});
// No TraceContext is present when you reach this point.
// tag:new-context-block:end
// tag:storing-the-trace-context:start
final TraceContext context = Kamon.tracer().newContext("example-trace");
Tracer.withContext(context, () -> {
// While this code executes, `context` is the current
// TraceContext.
System.out.println("Current Trace Token: " + Tracer.currentContext().token());
return "Some awesome result";
});
// tag:storing-the-trace-context:end
// tag:creating-segments:start
Tracer.withNewContext("trace-with-segments", true, () -> {
final Segment segment = Tracer.currentContext().startSegment("some-cool-section", "business-logic", "kamon");
// Some application code here.
segment.finish();
return "done";
});
// tag:creating-segments:end
// tag:managed-segments:start
Tracer.withNewContext("trace-with-segments", true, () -> {
Tracer.currentContext().withNewSegment("some-cool-section", "business-logic", "kamon", () -> {
// Here is where the segment does it's job.
return 0;
});
return "done";
});
// tag:managed-segments:end
}
} | true |
8f5f6f2772312f79ec8d952eaf2a2b222ba9cd4c | Java | chrismwilliams/aquarium-sim | /UserCode/Manager/PreyLvlManagerTest.java | UTF-8 | 1,505 | 2.65625 | 3 | [] | no_license | package UserCode.Manager;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* The test class PreyLvlManagerTest for testing the PreyLvlManager production class.
*
* @author Chris Williams
* @version 3.0
*
* Test Conditions
*
* 1) Construction (default): all fields are initialised as expected - do once via object bench.
* 2) checkEntities(): check if the method adds a number of IEntity's based on the IEntity's within the _entities array passed. This
* test is performed by running the simulation as it requires a number of concrete implementations to be created. This was tested by
* printing out the amount passed to the method topUpPreyLvls and checking the _entities size in the class EntityManager
* 3) checkEntities(): check that if the _entities array is full of prey's the method doesn't add more prey IEntity's. This again was
* tested using the system print's of the amout passed to topUpPreyLvls and checking the _entities array doesn't increase
*
*/
public class PreyLvlManagerTest
{
/**
* Default constructor for test class PreyLvlManagerTest
*/
public PreyLvlManagerTest()
{
}
/**
* Sets up the test fixture.
*
* Called before every test case method.
*/
@Before
public void setUp()
{
}
/**
* Tears down the test fixture.
*
* Called after every test case method.
*/
@After
public void tearDown()
{
}
}
| true |
e8ebce2e5ecc58a24b9dfb730e95678494887be6 | Java | ikhlef/informatique_statistique_java | /IKHLEF_Projet3_LI323/src/foufa/Exercice2.java | UTF-8 | 3,276 | 3.296875 | 3 | [] | no_license | package foufa;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class Exercice2 {
public static int K = 6;
public static double p = 0.02;
public static double q = 0.01;
public static double[] resolutionGaussSeidel(double[][] P, int nit, double epsilon ){
double[] VectPI =new double[K+1];
double som=0;
//On initialise tab PI comme pour la resolution des puissances a l'etape initiale n=0 : "VectPI[i]=1.0/|E|".
for(int i=0;i<VectPI.length;i++){
VectPI[i]=1.0/VectPI.length;
}
// som1 le cas i<j , et som2 le cas i>j
double som1, som2;
int cpt=0; // nombre d'iterations
boolean critereConvergence = false;
// On a besoin de garder les precedentes valeurs de vectPI pour comparer les distances entre VectPi(n) et VectPi(n-1)
//avec epsilon .Les pr�c�dentes valeurs sont copiees dans CopyVect dans la boucle ci dessous.
double[] CopyVectPi = new double[VectPI.length];
for(int i=0;i<VectPI.length;i++){
CopyVectPi[i] = VectPI[i];
}
//critere de Convergence qui dépend de la distance entre Pi(n) et Pi(n-1) par rapport a epsilon et de nit
while (cpt<nit && !critereConvergence){
cpt++;
som = 0;
for (int j=0;j<VectPI.length;j++){
som1 = 0;
som2 = 0;
for (int i=0;i<VectPI.length;i++) {
//CAS DE la 1ere somme i < j.
if(i<j) {
som1 += VectPI[i]*P[i][j];
}
//CAS de la 2eme somme i > j
if(i>j) {
som2 += VectPI[i]*P[i][j];
}
}
// equation finale :1/(1-P[j][j]) *(som1+som2)
VectPI[j] = (1/(1-P[j][j]))*(som1+som2);
// Et on rajoute PI[j] a la somme des PI pour pouvoir normaliser par la suite
som+=VectPI[j];
}
// Normalisation de PI a chaque iteration demander dans l'ennonce
for(int i=0;i<VectPI.length;i++){
VectPI[i]/=som;
}
// Convergence par similarite
if (epsilon >= 0) {
critereConvergence = true;
for (int i=0;i<VectPI.length;i++){
if ( Math.abs((double)(VectPI[i]-CopyVectPi[i])) > epsilon ) {
critereConvergence = false;
break;
}
}
}
// On doit recopier les valeurs a chaque tour de boucle car les valeurs du VecteurPi change a chaque fois que
//l'on termine de parcourir une colonne de la matrice P. On recopie ces nouvelles valeurs dans CopyVect pour
// pouvoir au prochain tour de boucle recomparer les distances
for(int i=0;i<VectPI.length;i++){
CopyVectPi[i] = VectPI[i];
}
cpt++;
}
System.out.println("nombre d'iterations pour la convergence " +cpt);
return VectPI;
}
@SuppressWarnings("static-access")
public static void main(String[] args) throws IOException{
PrintWriter ecrivain;
Exercice1 ex1=new Exercice1();
double[] v1 = new double[K+1];
double[][] matriceP = new double[K+1][K+1];
String fic1="C:/Users/foufi2012/workspace/IKHLEF_Projet3_LI323/methode_puissance.txt";
matriceP =ex1.matriceTransition();
System.out.println("Methode Gauss Seidel :");
v1=resolutionGaussSeidel(matriceP, 7000,10E-5);
ex1.afficherVectPI(v1);
ecrivain = new PrintWriter(new BufferedWriter(new FileWriter(fic1)));
for(int a =0; a<v1.length;a++)
ecrivain.println(a+" "+v1[a]);
ecrivain.close();
}
}
| true |
91f866e80ff4bdb07b21c0d7fa1ab2afc34dd41c | Java | jaydenwangwei/code | /open-source/open-source-design-pattern/src/main/java/com/jayden/design/pattern/factory/factorymethod/SimpleFactoryImpl.java | UTF-8 | 313 | 2.296875 | 2 | [] | no_license | package com.jayden.design.pattern.factory.factorymethod;
import com.jayden.design.pattern.factory.enyity.ICourse;
import com.jayden.design.pattern.factory.enyity.SimpleCourseImpl;
public class SimpleFactoryImpl implements IFactory {
public ICourse iCourse() {
return new SimpleCourseImpl();
}
}
| true |
03d4e9d3d8de399c60931c585ba6bf797ccf69ab | Java | falcuun/LolChmapGenerator | /src/namegenerator/Helpers/JSONParser.java | UTF-8 | 1,680 | 2.84375 | 3 | [] | no_license | package namegenerator.Helpers;
import com.google.gson.*;
import namegenerator.Models.Champion;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
public class JSONParser {
public static ArrayList<Champion> FromJsonToChampions() {
String championsJSON = null;
try {
championsJSON = new String(Files.readAllBytes(Paths.get("champion.json")));
Gson gson = new Gson();
ArrayList<Champion> champions = new ArrayList<>();
JsonObject wholeJson = gson.fromJson(championsJSON, JsonObject.class);
JsonObject data = gson.fromJson(wholeJson.get("data"), JsonObject.class);
var keySet = data.keySet().toArray();
for (Object o : keySet) {
champions.add(gson.fromJson(data.get(o.toString()), Champion.class));
}
return champions;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public static Dictionary<String, String> FromJsonToChampionGuideLinks() {
String championsGuideJSON;
try {
championsGuideJSON = new String(Files.readAllBytes(Paths.get("championGuides.json")));
Gson gson = new Gson();
Dictionary<String, String> championGuides = new Hashtable<>();
JsonObject wholeJson = gson.fromJson(championsGuideJSON, JsonObject.class);
championGuides = gson.fromJson(wholeJson.get("data"), Hashtable.class);
return championGuides;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
| true |
9875f674eb47a5bfe649a1cc727702cf2348d8c7 | Java | SRIDHAR42/code-scratch | /src/main/java/intrvwbit/RainWaterTrapped.java | UTF-8 | 796 | 2.984375 | 3 | [] | no_license | package intrvwbit;
import java.util.ArrayList;
public class RainWaterTrapped {
public int solve(ArrayList<Integer> A) {
int n = A.size();
ArrayList<Integer> left = new ArrayList<Integer>();
ArrayList<Integer> right = new ArrayList<Integer>();
left.add(A.get(0)); //init
for (int i = 1; i < n; i++) {
left.add(Math.max(A.get(i), left.get(i - 1)));
}
right.add(A.get(n - 1)); // init
for (int i = n - 2; i >= 0; i--) {
right.add(0, Math.max(A.get(i), right.get(0)));
}
int res = 0;
int ele; // curr elevation
for (int i = 0; i < n; i++) {
ele = Math.min(left.get(i), right.get(i));
res += ele - A.get(i);
}
return res;
}
}
| true |
306a109c4292079f99e2deefe3e319ca1507da71 | Java | PavlidisLab/Gemma | /gemma-core/src/test/java/ubic/gemma/core/loader/expression/arrayDesign/AffyProbeReaderTest.java | UTF-8 | 3,587 | 2.171875 | 2 | [
"Apache-2.0"
] | permissive | /*
* The Gemma project
*
* Copyright (c) 2006 University of British Columbia
*
* 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 ubic.gemma.core.loader.expression.arrayDesign;
import junit.framework.TestCase;
import ubic.gemma.model.expression.designElement.CompositeSequence;
import java.io.InputStream;
import java.util.Collection;
/**
* @author pavlidis
*/
public class AffyProbeReaderTest extends TestCase {
private AffyProbeReader apr;
private InputStream is;
/*
* Class under test for Map read(InputStream)
*/
public final void testReadInputStream() throws Exception {
is = AffyProbeReaderTest.class.getResourceAsStream( "/data/loader/affymetrix-probes-test.txt" );
apr.setSequenceField( 5 );
apr.parse( is );
String expectedValue = "GCCCCCGTGAGGATGTCACTCAGAT"; // 10
CompositeSequence cs = this.getProbeMatchingName( "1004_at" );
TestCase.assertNotNull( "CompositeSequence was null", cs );
boolean foundIt = false;
for ( Reporter element : apr.get( cs ) ) {
if ( element.getName().equals( "1004_at#2:557:275" ) ) {
String actualValue = element.getImmobilizedCharacteristic().getSequence();
TestCase.assertEquals( expectedValue, actualValue );
foundIt = true;
break;
}
}
TestCase.assertTrue( "Didn't find the probe ", foundIt );
}
public final void testReadInputStreamNew() throws Exception {
is = AffyProbeReaderTest.class.getResourceAsStream( "/data/loader/affymetrix-newprobes-example.txt" );
apr.setSequenceField( 4 );
apr.parse( is );
String expectedValue = "AGCTCAGGTGGCCCCAGTTCAATCT"; // 4
CompositeSequence cs = this.getProbeMatchingName( "1000_at" );
TestCase.assertNotNull( "CompositeSequence was null", cs );
boolean foundIt = false;
for ( Reporter element : apr.get( cs ) ) {
if ( element.getName().equals( "1000_at:617:349" ) ) {
String actualValue = element.getImmobilizedCharacteristic().getSequence();
TestCase.assertEquals( expectedValue, actualValue );
foundIt = true;
break;
}
}
TestCase.assertTrue( "Didn't find the probe ", foundIt );
}
@Override
protected void setUp() throws Exception {
super.setUp();
apr = new AffyProbeReader();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
apr = null;
if ( is != null )
is.close();
}
private CompositeSequence getProbeMatchingName( String name ) {
Collection<CompositeSequence> keySet = apr.getKeySet();
CompositeSequence cs = null;
for ( CompositeSequence compositeSequence : keySet ) {
if ( compositeSequence.getName().equals( name ) ) {
cs = compositeSequence;
break;
}
}
return cs;
}
}
| true |
9bdbdeb467e641dd71f4f03c62c82b4050651a4f | Java | wangyne/flinkdemo | /src/main/java/com/wy/stream2kafka/MySqlTwoPhaseCommitSink.java | UTF-8 | 2,861 | 2.390625 | 2 | [] | no_license | package com.wy.stream2kafka;
import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.common.typeutils.base.VoidSerializer;
import org.apache.flink.api.java.typeutils.runtime.kryo.KryoSerializer;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.flink.streaming.api.functions.sink.TwoPhaseCommitSinkFunction;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
/**
* @author wangyn3
* @date 2019-12-30 11:25
*/
public class MySqlTwoPhaseCommitSink extends TwoPhaseCommitSinkFunction<String, Connection, Void> {
public MySqlTwoPhaseCommitSink() {
super(new KryoSerializer<>(Connection.class, new ExecutionConfig()), VoidSerializer.INSTANCE);
}
/**
* 执行数据库写入操作
*/
@Override
protected void invoke(Connection connection, String value, Context context) {
// String value = objectNode.get("value").toString();
System.out.println("=============="+value);
String sql = "insert into `t_test` (`name`,`insert_time`) values (?,?)";
PreparedStatement ps = null;
try {
ps = connection.prepareStatement(sql);
ps.setString(1, value);
ps.setTimestamp(2, new Timestamp(System.currentTimeMillis()));
//执行insert语句
ps.execute();
} catch (Exception e) {
e.printStackTrace();
}
// if("asdasd".equals(value)){
// System.out.println(1/0);
// }
}
/**
* 获取连接,开启手动提交事务
* */
@Override
protected Connection beginTransaction() throws Exception {
String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&useSSL=false&autoReconnect=true";
Connection connection = DBConnectUtil.getConnection(url, "root", "123456");
System.err.println("start beginTransaction......."+connection);
return connection;
}
/**
* 预提交,提交逻辑在invoke方法中
* */
@Override
protected void preCommit(Connection connection) throws Exception {
System.err.println("start preCommit......."+connection);
}
/**
* 如果invoke执行正常则提交事务
* */
@Override
protected void commit(Connection connection) {
System.err.println("start commit......."+connection);
DBConnectUtil.commit(connection);
}
/**
* 如果invoke执行异常则回滚事物,下一次的checkpoint操作也不会执行
* */
@Override
protected void abort(Connection connection) {
System.err.println("start abort rollback......."+connection);
DBConnectUtil.rollback(connection);
}
}
| true |
74669a28453117c7073363bc02b94ac30f9720d3 | Java | jjromannet/HomeAutomationCoreOsgiProject | /CoalBurnerModuleDS/src/main/java/net/jjroman/homeautomation/osgi/consumer/coalburnerds/CoalBurnerState.java | UTF-8 | 593 | 2.140625 | 2 | [] | no_license | package net.jjroman.homeautomation.osgi.consumer.coalburnerds;
/**
* This enum should be used to define current state of coalburner
* ACTIVE - when water tank temperature is below given temp and coal burner actively trying to increase the temperature
* STANDBY - when max temperature condition has been satisfied but water temp is still above minimum, then coal burner
* executes empty - cycles - but once in a while it performs maintenance cycle to maintain fire in coal burner fire
* chamber
* Created by Jan on 06/04/2015.
*/
public enum CoalBurnerState {
ACTIVE,
STANDBY
}
| true |
a0c15180fd8341cfbddfd29714c04e489ecdc196 | Java | zeruth/quest-helper | /src/main/java/com/questhelper/quests/kingsransom/LockpickPuzzle.java | UTF-8 | 4,654 | 2.09375 | 2 | [
"BSD-2-Clause"
] | permissive | /*
* Copyright (c) 2020, Zoinkwiz
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.questhelper.quests.kingsransom;
import com.questhelper.QuestHelperPlugin;
import com.questhelper.questhelpers.QuestHelper;
import com.questhelper.steps.QuestStep;
import java.awt.Color;
import java.awt.Graphics2D;
import net.runelite.api.events.GameTick;
import net.runelite.api.widgets.Widget;
import net.runelite.client.eventbus.Subscribe;
public class LockpickPuzzle extends QuestStep
{
int[] TUMBLER_ANSWERS = new int[]{3894, 3895, 3896, 3897};
int[] TUMBLER_WIDGETS = new int[]{20, 21, 22, 23};
int[] TUMBLER_CURRENT = new int[]{3901, 3902, 3903, 3904};
int CURRENT_TUMBLER = 3905;
int UP_WIDGET = 12;
int DOWN_WIDGET = 13;
int TRY_LOCK = 14;
int highlightChildID;
public LockpickPuzzle(QuestHelper questHelper)
{
super(questHelper, "Click the highlighted boxes to solve the puzzle. The solution is:");
}
@Override
public void startUp()
{
updateSolvedPositionState();
this.setText("Click the highlighted boxes to solve the puzzle. The solution is:");
this.addText("Tumbler 1: " + client.getVarbitValue(TUMBLER_ANSWERS[0]) + ".");
this.addText("Tumbler 2: " + client.getVarbitValue(TUMBLER_ANSWERS[1]) + ".");
this.addText("Tumbler 3: " + client.getVarbitValue(TUMBLER_ANSWERS[2]) + ".");
this.addText("Tumbler 4: " + client.getVarbitValue(TUMBLER_ANSWERS[3]) + ".");
}
@Subscribe
public void onGameTick(GameTick event)
{
updateSolvedPositionState();
}
private void updateSolvedPositionState()
{
int current0 = client.getVarbitValue(TUMBLER_CURRENT[0]);
int answer0 = client.getVarbitValue(TUMBLER_ANSWERS[0]);
if (current0 != answer0)
{
updateWidget(0, current0, answer0);
return;
}
int current1 = client.getVarbitValue(TUMBLER_CURRENT[1]);
int answer1 = client.getVarbitValue(TUMBLER_ANSWERS[1]);
if (current1 != answer1)
{
updateWidget(1, current1, answer1);
return;
}
int current2 = client.getVarbitValue(TUMBLER_CURRENT[2]);
int answer2 = client.getVarbitValue(TUMBLER_ANSWERS[2]);
if (current2 != answer2)
{
updateWidget(2, current2, answer2);
return;
}
int current3 = client.getVarbitValue(TUMBLER_CURRENT[3]);
int answer3 = client.getVarbitValue(TUMBLER_ANSWERS[3]);
if (current3 != answer3)
{
updateWidget(3, current3, answer3);
return;
}
highlightChildID = TRY_LOCK;
}
private void updateWidget(int widgetID, int currentVal, int answer)
{
int currentTumbler = client.getVarbitValue(CURRENT_TUMBLER);
if (currentTumbler != widgetID + 1)
{
highlightChildID = TUMBLER_WIDGETS[widgetID];
}
else if (currentVal > answer)
{
highlightChildID = DOWN_WIDGET;
}
else
{
highlightChildID = UP_WIDGET;
}
}
@Override
public void makeWidgetOverlayHint(Graphics2D graphics, QuestHelperPlugin plugin)
{
super.makeWidgetOverlayHint(graphics, plugin);
Widget widgetWrapper = client.getWidget(588, highlightChildID);
if (widgetWrapper != null)
{
graphics.setColor(new Color(questHelper.getConfig().targetOverlayColor().getRed(),
questHelper.getConfig().targetOverlayColor().getGreen(),
questHelper.getConfig().targetOverlayColor().getBlue(), 65));
graphics.fill(widgetWrapper.getBounds());
graphics.setColor(questHelper.getConfig().targetOverlayColor());
graphics.draw(widgetWrapper.getBounds());
}
}
}
| true |
d0a2f95a16c71ac471f782405bef599447753e61 | Java | qql2019/ShopSystem | /day2612/src/com/cissst/bysales/service/impl/Usersserverimpl.java | UTF-8 | 535 | 2.046875 | 2 | [] | no_license | package com.cissst.bysales.service.impl;
import com.cissst.bysales.dao.Usersdao;
import com.cissst.bysales.dao.impl.Usersdaoimpl;
import com.cissst.bysales.daomain.Users;
import com.cissst.bysales.service.Usersservice;
/**登录处理
*
* @author Administrator
*
*/
public class Usersserverimpl implements Usersservice {
private Usersdao userdao=new Usersdaoimpl();
@Override
public Users islogin(String username, String userpass) {
// TODO Auto-generated method stub
return userdao.islogin(username, userpass);
}
}
| true |
a909794e23dbe1341cf622e546fb3315835d435e | Java | sawal16/j8unit | /repository/src/test/java/org/j8unit/repository/javax/swing/text/DocumentFilterClassTest.java | UTF-8 | 3,548 | 2.46875 | 2 | [] | no_license | package org.j8unit.repository.javax.swing.text;
import static org.junit.Assert.fail;
import javax.swing.text.DocumentFilter;
import javax.swing.text.DocumentFilter.FilterBypass;
import org.j8unit.repository.categories.Draft;
import org.j8unit.runners.J8Unit4;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
/**
* Specific JUnit test class to proof the type relevant aspects of type {@link DocumentFilter} (by simply reusing the
* J8Unit test interface {@link org.j8unit.repository.javax.swing.text.DocumentFilterClassTests}).
*/
@RunWith(J8Unit4.class)
public class DocumentFilterClassTest
implements DocumentFilterClassTests<DocumentFilter> {
// J8UNIT-MARKER-[BEGIN]-[CLASS]-[javax.swing.text.DocumentFilter]
@Override
public Class<DocumentFilter> createNewSUT() {
return DocumentFilter.class;
}
/**
* <p>
* Test method for the hereby targeted constructor-under-test
* {@link javax.swing.text.DocumentFilter#DocumentFilter() public javax.swing.text.DocumentFilter()}.
*
* Up to now, there is no real implementation of this test method. But with your help at
* <a href="http://www.j8unit.org">http://www.j8unit.org</a> this marker method will be replaced by meaningful test
* methods soon.
* </p>
*
* @since 0.9.0
*/
@Ignore("With your help at http://www.j8unit.org this marker method will be replaced by meaningful test methods soon.")
@Test
@Category(Draft.class)
public void create_DocumentFilter()
throws Exception {
// create new instance
@SuppressWarnings("unused")
final DocumentFilter sut = new DocumentFilter();
}
// J8UNIT-MARKER-[MANUAL]-[CLASS]-[javax.swing.text.DocumentFilter]
// J8UNIT-MARKER-[END]-[CLASS]-[javax.swing.text.DocumentFilter]
/**
* Specific JUnit test class to proof the type relevant aspects of type {@link FilterBypass} (by simply reusing the
* J8Unit test interface
* {@link org.j8unit.repository.javax.swing.text.DocumentFilterClassTests.FilterBypassClassTests}).
*/
@RunWith(J8Unit4.class)
public static class FilterBypassClassTest
implements org.j8unit.repository.javax.swing.text.DocumentFilterClassTests.FilterBypassClassTests<FilterBypass> {
// J8UNIT-MARKER-[BEGIN]-[CLASS]-[javax.swing.text.DocumentFilter$FilterBypass]
@Override
public Class<FilterBypass> createNewSUT() {
return FilterBypass.class;
}
/**
* <p>
* Test method for the hereby targeted constructor-under-test
* {@link javax.swing.text.DocumentFilter.FilterBypass#FilterBypass() public
* javax.swing.text.DocumentFilter$FilterBypass()}.
*
* Up to now, there is no real implementation of this test method. But with your help at
* <a href="http://www.j8unit.org">http://www.j8unit.org</a> this marker method will be replaced by meaningful
* test methods soon.
* </p>
*
* @since 0.9.0
*/
@Ignore("Cannot construct an abstract class!")
@Test
@Category(Draft.class)
public void create_FilterBypass()
throws Exception {
fail("Cannot construct an abstract class!");
}
// J8UNIT-MARKER-[MANUAL]-[CLASS]-[javax.swing.text.DocumentFilter$FilterBypass]
// J8UNIT-MARKER-[END]-[CLASS]-[javax.swing.text.DocumentFilter$FilterBypass]
}
}
| true |
f51ddd2ab9f549679024b329303769b207625f1d | Java | GraemeHBrown/SSS | /src/test/java/DataRepositoryTest.java | UTF-8 | 2,051 | 2.671875 | 3 | [] | no_license | import com.graemehbrown.simplestockmarket.Model.Stock;
import com.graemehbrown.simplestockmarket.Model.StockType;
import com.graemehbrown.simplestockmarket.Model.Trade;
import com.graemehbrown.simplestockmarket.Model.TradeIndicator;
import com.graemehbrown.simplestockmarket.Repository.DataRepository;
import org.junit.Before;
import org.junit.Test;
import java.util.Calendar;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class DataRepositoryTest {
private static DataRepository dataRepository = DataRepository.getInstance();
private Stock testStock;
private Stock testStock2;
private Trade testTrade;
@Before
public void before() {
testStock = new Stock("TEA", StockType.COMMON, 0, 0, 100);
testStock2 = new Stock("POP", StockType.COMMON, 16, 0, 100);
testTrade = new Trade(testStock, Calendar.getInstance().getTime(), 23, TradeIndicator.BUY, 12.50);
dataRepository.addStock(testStock);
}
@Test
public void getStockReturnsStockForSymbol() {
Stock foundStock = dataRepository.getStock(testStock.getSymbol());
assertEquals("TEA", foundStock.getSymbol());
}
@Test
public void addStockAddsStockToStockList() {
int stockListBefore = dataRepository.getStockList().size();
dataRepository.addStock(testStock2);
assertEquals(stockListBefore+1, dataRepository.getStockList().size());
}
@Test
public void addTradeAddsTradeToTradeList() {
int tradeListSizeBefore = dataRepository.getTradeList().size();
dataRepository.addTrade(testTrade);
assertEquals(tradeListSizeBefore+1, dataRepository.getTradeList().size());
}
@Test
public void getTradeListReturnsListOfTrades() {
dataRepository.addTrade(testTrade);
assertTrue(dataRepository.getTradeList().contains(testTrade));
}
@Test
public void getStockListReturnsListOfStocks() {
assertTrue(dataRepository.getStockList().contains(testStock));
}
}
| true |
b9e8cef53bccd546fda658d785692b77ee77a635 | Java | yulanheng/pattern | /src/main/java/cn/ylh/pattern/observer/ObserverTest.java | UTF-8 | 503 | 3.328125 | 3 | [] | no_license | package cn.ylh.pattern.observer;
/**
*观察者模式
*/
public class ObserverTest {
public static void main(String[] args) {
//创建主题对象
ConcreteSubject subject=new ConcreteSubject();
//创建观察者对象
Observer observer=new ConcreteObserver();
Observer observer2=new ConcreteObserver();
//将观察者对象关联到主题对象
subject.attach(observer);
subject.attach(observer2);
//主题对象改变状态
subject.change("cccccc");
}
}
| true |
b6ef75e23526adbbe2dc700af5a82a4b21625c8b | Java | syrus-ru/amficom | /AMFICOM/v1/prediction/src/com/syrus/AMFICOM/Client/Prediction/UI/TimeDependence/TimeDependenceTable.java | WINDOWS-1251 | 6,498 | 2.046875 | 2 | [] | no_license | package com.syrus.AMFICOM.Client.Prediction.UI.TimeDependence;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.ImageIcon;
import javax.swing.JInternalFrame;
import javax.swing.JScrollPane;
import javax.swing.WindowConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;
import com.syrus.AMFICOM.Client.Analysis.Reflectometry.UI.ReportTable;
import com.syrus.AMFICOM.Client.Prediction.StatisticsMath.PredictionModel;
import com.syrus.AMFICOM.Client.Prediction.StatisticsMath.Statistics;
import com.syrus.AMFICOM.Client.Prediction.StatisticsMath.TimeDependenceData;
import com.syrus.AMFICOM.client.UI.ATable;
import com.syrus.AMFICOM.client.resource.I18N;
import com.syrus.AMFICOM.resource.PredictionResourceKeys;
import com.syrus.util.Log;
/**
* @author Levchenko Alexandre S.
*/
public class TimeDependenceTable extends JInternalFrame implements ReportTable, ChangeListener {
JScrollPane scrollPane = new JScrollPane();
ATable dataTable = new ATable();
TimeDependenceTableModel timeDependenceTableModel;
public TimeDependenceTable() {
try
{
jbInit();
}
catch(Exception e)
{
e.printStackTrace();
}
PredictionModel.addChangeListener(this);
}
private void jbInit() throws Exception
{
this.setClosable(true);
this.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
this.setIconifiable(true);
this.setResizable(true);
this.getContentPane().setBackground(Color.white);
scrollPane.getViewport().setBackground(Color.white);
this.getContentPane().add(scrollPane, BorderLayout.CENTER);
scrollPane.getViewport().add(dataTable, null);
timeDependenceTableModel = new TimeDependenceTableModel();
timeDependenceTableModel.clearTable();
this.dataTable.setModel(timeDependenceTableModel);
this.setFrameIcon(new ImageIcon(Toolkit.getDefaultToolkit().
getImage("images/general.gif").getScaledInstance(16, 16, Image.SCALE_SMOOTH)));
setTitle(I18N.getString(PredictionResourceKeys.FRAME_TIME_DEPENDANCE_TABLE));
dataTable.getColumnModel().getColumn(0).setPreferredWidth(130);
dataTable.getColumnModel().getColumn(1).setPreferredWidth(40);
}
public String getReportTitle()
{
return I18N.getString(PredictionResourceKeys.FRAME_TIME_DEPENDANCE_TABLE);
}
public TableModel getTableModel()
{
return timeDependenceTableModel;
}
private void setData(TimeDependenceData [] tdd, com.syrus.AMFICOM.Client.Prediction.StatisticsMath.LinearCoeffs linearCoeffs, String dim)
{
if (tdd.length == 0) {
timeDependenceTableModel.clearTable();
return;
}
if(dim == null)
dim = "";
else if(dim.equals("connector_db"))
dim = "";
else if(dim.equals("weld_db"))
dim = "";
else if(dim.equals("linear_db"))
dim = "";
else if(dim.equals("db"))
dim = "";
else if(dim.equals("linear_db/km"))
dim = "/";
else if(dim.equals("db/km"))
dim = "/";
else dim = "";
double day = 1000.*60.*60.*24;
long maxTime = tdd[tdd.length-1].date;
long minTime = tdd[0].date;
double max = tdd[0].value;
double min = tdd[0].value;
for(int i=0; i<tdd.length; i++)
{
if(max<tdd[i].value) max = tdd[i].value;
if(min>tdd[i].value) min = tdd[i].value;
}
double sigma = 100000.;
max = (int)(max*sigma)/sigma;
min = (int)(min*sigma)/sigma;
double beginVal = (int)(linearCoeffs.f(tdd[0].date)*sigma)/sigma;
double deriv = (int)(linearCoeffs.k*day*sigma)/sigma;
double disp = (int)(linearCoeffs.dispersia*sigma)/sigma;
double absDisp = (int)(linearCoeffs.absDispersia*sigma)/sigma;
double quality = (int)((1./(linearCoeffs.chi2))*sigma)/sigma;
double statError = (int)((1./Math.sqrt((double)tdd.length))*100.*sigma)/sigma;
double systErr = (int)((1./Math.sqrt((double)(maxTime-minTime)/day))*100.*sigma)/sigma;
if(systErr>100.) systErr=100.;
double totalErr = (int)Math.sqrt(systErr*systErr + statError*statError);
if(totalErr>100.) totalErr = 100.;
Object[][] data = {
{"", String.valueOf(tdd.length)},
{" , "+dim, String.valueOf(beginVal)},
{" (), "+"("+dim+")"+"/", String.valueOf(deriv)},
{" , "+dim, String.valueOf(max)},
{" , "+dim, String.valueOf(min)},
{", "+dim, String.valueOf(disp)},
{" , "+dim, String.valueOf(absDisp)},
{" ", String.valueOf(quality)},
{" , %", String.valueOf(statError)},
{" , %", String.valueOf(systErr)},
{" (), %", String.valueOf(totalErr)}
};
this.timeDependenceTableModel.setTableData(data);
}
public void stateChanged(ChangeEvent e) {
if (e.getSource().equals(PredictionModel.class)) {
try {
Statistics statistics = PredictionModel.getCurrentStatistics();
setData(statistics.getTimeDependence(), statistics.getLc(), statistics.getDimension());
} catch (IllegalArgumentException e1) {
Log.errorMessage("Incorrect state of PredictionManager: possibly no traces selected for prediction: " + e1.getMessage());
return;
}
}
}
}
class TimeDependenceTableModel extends AbstractTableModel
{
String[] columnNames = {"", ""};
Object[][] data = {
{"--", "--"},
{"--", "--"},
{"--", "--"},
{"--", "--"}
};
TimeDependenceTableModel()
{
super();
}
public void clearTable()
{
data = new Object[][]{};
super.fireTableDataChanged();
}
public void setTableData(Object[][] data)
{
this.data = data;
super.fireTableDataChanged();
}
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
return data.length;
}
public String getColumnName(int col) {
return columnNames[col];
}
public Object getValueAt(int row, int col) {
return data[row][col];
}
public double getvalueat(int row, int col) {
return ((Double)(data[row][col])).doubleValue();
}
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
public boolean isCellEditable(int row, int col)
{
return false;
}
public void setValueAt(Object value, int row, int col)
{
data[row][col] = value;
fireTableCellUpdated(row, col);
}
}
| true |
48936b740e5c1913963e849d8caf998c5d241f7b | Java | eiiches/jackson-jq | /jackson-jq/src/main/java/net/thisptr/jackson/jq/internal/tree/matcher/PatternMatcher.java | UTF-8 | 1,137 | 2.078125 | 2 | [
"MIT",
"CC-BY-3.0",
"Apache-2.0"
] | permissive | package net.thisptr.jackson.jq.internal.tree.matcher;
import java.util.List;
import java.util.Stack;
import com.fasterxml.jackson.databind.JsonNode;
import net.thisptr.jackson.jq.Scope;
import net.thisptr.jackson.jq.exception.JsonQueryException;
import net.thisptr.jackson.jq.internal.misc.Functional;
import net.thisptr.jackson.jq.internal.misc.Pair;
import net.thisptr.jackson.jq.path.Path;
public interface PatternMatcher {
void match(final Scope scope, final JsonNode in, final Functional.Consumer<List<Pair<String, JsonNode>>> out, final Stack<Pair<String, JsonNode>> accumulate) throws JsonQueryException;
public static class MatchWithPath {
public final String name;
public final JsonNode value;
public final Path path;
public MatchWithPath(final String name, final JsonNode value, final Path path) {
this.name = name;
this.value = value;
this.path = path;
}
}
public interface MatchOutput {
void emit(List<MatchWithPath> vars) throws JsonQueryException;
}
void matchWithPath(Scope scope, JsonNode in, Path path, MatchOutput output, Stack<MatchWithPath> accumulate) throws JsonQueryException;
}
| true |
40fa9ba04e01c197ed9a7272ccd281a933abbf20 | Java | Arehns/myAutomation | /src/test/java/stepdefinitions/StringModifier.java | UTF-8 | 1,532 | 3.078125 | 3 | [] | no_license | package stepdefinitions;
import java.util.Random;
public class StringModifier {
//In order to generate new emails and usernames
private String characters = "qwertyuiopasdfghjklzxcvbnm1234567890";
private String newEmail = "";
private String newUser = "";
private String newTooLongUser = "";
private int normalLength = 10;
char[] randomArray = new char[normalLength];
char[] randomUserArray = new char[normalLength];
char[] tooLongArray = new char[102];
Random rand = new Random();
public String randomEmailString() {
for (int i = 0; i < normalLength; i++) {
randomArray[i] = characters.charAt(rand.nextInt(characters.length()));
}
for (int j = 0; j < randomArray.length; j++) {
this.newEmail += randomArray[j];
}
return newEmail + "@email.se";
}
public String randomUserString() {
for (int i = 0; i < normalLength; i++) {
randomUserArray[i] = characters.charAt(rand.nextInt(characters.length()));
}
for (int j = 0; j < randomUserArray.length; j++) {
this.newUser += randomUserArray[j];
}
return newUser;
}
public String userNameTooLong() {
for (int i = 0; i < 102; i++) {
tooLongArray[i] = characters.charAt(rand.nextInt(characters.length()));
}
for (int j = 0; j < tooLongArray.length; j++) {
this.newTooLongUser += tooLongArray[j];
}
return newTooLongUser;
}
}
| true |
d227e223a1fb739b80e38b2c9e1b54846ee1d371 | Java | AdrianRomanski/university-java | /src/main/java/basics_of_programming/lectures/lecture_2/PPJWin.java | UTF-8 | 867 | 3.25 | 3 | [] | no_license | package basics_of_programming.lectures.lecture_2;
public class PPJWin {
public static void main(String[] args) {
System.out.println("Hello PPJ");
System.out.println("Hello PPJ");
// System.out.println(null);
System.out.println(5);
System.out.println(05); // 5 - Octal Decimal 1 * 10^1 + 5 * 10^0
System.out.println(15);
System.out.println(015); // 13 - Octal Decimal 8^1 + 5 * 8^0 => 13
System.out.println(15L);
System.out.println(15l);
System.out.println(0x15); // 21
System.out.println(0b0001_0110); // 22
System.out.println('a');
System.out.println('0');
System.out.println('O');
System.out.println('\t');
System.out.println('\uFFFF'); // UTF-16
System.out.println(1e-9d);
System.out.println(1e127);
}
}
| true |
f9cc1501afb87ea7aa1fbf8142b96f4d66348e02 | Java | haweiYu/spark_defaultDataSources_hbase | /src/main/scala/utils/KerberosAuthenticator.java | UTF-8 | 2,175 | 2.65625 | 3 | [] | no_license | package utils;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.security.UserGroupInformation;
import java.io.IOException;
/**
* Kerberos认证工具类
*/
public class KerberosAuthenticator {
public static void authentication(String authenticationType, String krb5FilePath, String principal, String keytab) {
// 判断认证类型,如果不需要认证直接返回
if (authenticationType != null && "kerberos".equalsIgnoreCase(authenticationType.trim())) {
System.out.println("开始设置kerberos身份验证.");
} else {
System.out.println("未设置kerberos身份验证.");
return;
}
// 设置认证服务器连接配置文件
if (System.getProperty("os.name").toLowerCase().startsWith("win")) {
// 默认:这里不设置的话,win默认会到 C盘下读取krb5.init
System.setProperty("java.security.krb5.conf", krb5FilePath);
System.out.println(krb5FilePath);
} else {
// linux 会默认到 /etc/krb5.conf
// 中读取krb5.conf,本文笔者已将该文件放到/etc/目录下,因而这里便不用再设置了
System.setProperty("java.security.krb5.conf", krb5FilePath);
System.out.println(krb5FilePath);
}
// 使用Hadoop安全登录
org.apache.hadoop.conf.Configuration conf = new org.apache.hadoop.conf.Configuration();
conf.set("hadoop.security.authentication", authenticationType);
conf.addResource(new Path("hdfs-site.xml"));
conf.addResource(new Path("core-site.xml"));
conf.addResource(new Path("hbase-site.xml"));
// conf.addResource(new Path("hive-site.xml"));
try {
// 用户认证
UserGroupInformation.setConfiguration(conf);
UserGroupInformation.loginUserFromKeytab(principal, keytab);
System.out.println(
"Kerberos身份认证完成, krb5FilePath:" + krb5FilePath + ", principal:" + principal + ", keytab:" + keytab);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
| true |
e3bf0848966a218f7dac0d06c04098e0c2b6c8d0 | Java | AlviDwi/Tugas-Modul-1 | /src/Modul1/tugasno2prak.java | UTF-8 | 1,511 | 3.015625 | 3 | [] | no_license | package Modul1;
import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.swing.*;
import java.io.IOException;
public class tugasno2prak {
public static void main(String[] args) throws UnknownHostException, IOException {
String[] options = {"HOST", "IP"};
int a = JOptionPane.showOptionDialog(null, "Silahkan Pilih",
"Click a button",
JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
if(a==0){String host=JOptionPane.showInputDialog(null, "Masukkan Host Address");
System.out.println("Host: "+
InetAddress.getByName(host));
System.out.println("\n# Check Connection");
InetAddress ia = InetAddress.getByName(host);
if(ia.isReachable(3000)){
System.out.println(ia+" is Reachable");
}else{
System.out.println(ia+" is unReachable");
}
}else{
String ip=JOptionPane.showInputDialog(null, "Masukkan IP Address");
System.out.println("IP: "+
InetAddress.getByName(ip));
System.out.println("\n# Check Connection");
InetAddress ia = InetAddress.getByName(ip);
if(ia.isReachable(3000)){
System.out.println(ia+" is Reachable");
}else{
System.out.println(ia+" is unReachable");
}
}
}
}
| true |
8ec7c06ec2b0ee0ed99a69570444de3004b928b5 | Java | Peachball/ShadowStone | /src/client/tooltip/TooltipCard.java | UTF-8 | 466 | 2.375 | 2 | [] | no_license | package client.tooltip;
import server.card.ClassCraft;
public abstract class TooltipCard extends Tooltip {
public int cost, id;
public ClassCraft craft;
public TooltipCard(String name, String description, String imagepath, ClassCraft craft, int cost, int id,
Tooltip... references) {
super(name, cost + "-cost " + craft.toString() + " " + description, imagepath, references);
this.craft = craft;
this.cost = cost;
this.id = id;
}
}
| true |
3e9b41093470d5d93ec635bef2413e2147ea9f24 | Java | rohiniy/interview-algorithms | /src/com/basicAlgorithms/arrays/RemoveKDigitsToFormSmallestNo.java | UTF-8 | 1,522 | 3.984375 | 4 | [] | no_license | /**
* Get the smallest possible number by removing k digits from the number
* 23178 k=1 output = 2178 remove 3
* 23178 k = 3, remove 3 elements and make the number the smallest = 17
*/
package com.basicAlgorithms.arrays;
import java.util.*;
public class RemoveKDigitsToFormSmallestNo {
public String removeKdigits(String num, int k) {
int n = num.length();
if (n == 0) {
return "0";
}
if (n == k) {
// remove all digits
return "0";
}
Stack<Character> stack = new Stack<>();
for (int i=0; i< n; i++) {
char c = num.charAt(i);
while (k > 0 && !stack.isEmpty() && stack.peek() >= c) {
stack.pop();
k--;
}
stack.push(c);
}
while (k > 0) {
// remove the last element as it is the largest
stack.pop();
k--;
}
int size = stack.size();
StringBuilder result = new StringBuilder();
for (int i=0; i<size; i++) {
result.append(stack.pop());
}
String strResult;
strResult = result.reverse().toString();
for (int i=0; i< result.length(); i++) {
if (result.charAt(i) == '0') {
strResult = result.substring(i+1, result.length());
}
else {
break;
}
}
return strResult.equals("") ? "0" : strResult ;
}
public static void main(String args[]) {
RemoveKDigitsToFormSmallestNo obj = new RemoveKDigitsToFormSmallestNo();
System.out.println(obj.removeKdigits("19888", 4));
// 23178 k=1 output = 2178 remove 3
}
}
| true |
62b7d73a7273854a4785e3a258e81f80f54d1294 | Java | Dmitriy1Fokin/tavrzcms3 | /src/main/java/ru/fds/tavrzcms3/specification/impl/SpecificationImpl.java | UTF-8 | 3,429 | 2.421875 | 2 | [] | no_license | package ru.fds.tavrzcms3.specification.impl;
import org.springframework.data.jpa.domain.Specification;
import ru.fds.tavrzcms3.dictionary.Operations;
import ru.fds.tavrzcms3.specification.SearchCriteria;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.time.LocalDate;
public class SpecificationImpl implements Specification {
private SearchCriteria criteria;
public SpecificationImpl(SearchCriteria searchCriteria){
criteria = searchCriteria;
}
@Override
public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder criteriaBuilder) {
if(criteria.getOperation() == Operations.GREATER){
if(criteria.getValue().getClass() == String.class) {
return criteriaBuilder.greaterThan(root.<String>get(criteria.getKey()), criteria.getValue().toString());
}
else if(criteria.getValue().getClass() == LocalDate.class){
return criteriaBuilder.greaterThan(root.<LocalDate> get(criteria.getKey()), (LocalDate) criteria.getValue());
}
else {
return null;
}
}
if(criteria.getOperation() == Operations.GREATER_EQUAL){
if(criteria.getValue().getClass() == String.class) {
return criteriaBuilder.greaterThanOrEqualTo(root.<String>get(criteria.getKey()), criteria.getValue().toString());
}
else if(criteria.getValue().getClass() == LocalDate.class){
return criteriaBuilder.greaterThanOrEqualTo(root.<LocalDate> get(criteria.getKey()), (LocalDate) criteria.getValue());
}
else {
return null;
}
}
if(criteria.getOperation() == Operations.LESS){
if(criteria.getValue().getClass() == String.class) {
return criteriaBuilder.lessThan(root.<String>get(criteria.getKey()), criteria.getValue().toString());
}
else if(criteria.getValue().getClass() == LocalDate.class){
return criteriaBuilder.lessThan(root.<LocalDate> get(criteria.getKey()), (LocalDate) criteria.getValue());
}
else {
return null;
}
}
if(criteria.getOperation() == Operations.LESS_EQUAL){
if(criteria.getValue().getClass() == String.class) {
return criteriaBuilder.lessThanOrEqualTo(root.<String>get(criteria.getKey()), criteria.getValue().toString());
}
else if(criteria.getValue().getClass() == LocalDate.class){
return criteriaBuilder.lessThanOrEqualTo(root.<LocalDate> get(criteria.getKey()), (LocalDate) criteria.getValue());
}
else {
return null;
}
}
if(criteria.getOperation() == Operations.EQUAL_IGNORE_CASE){
if(root.get(criteria.getKey()).getJavaType() == String.class){
return criteriaBuilder.like(criteriaBuilder.lower(root.<String> get(criteria.getKey())), "%" + criteria.getValue().toString().toLowerCase() + "%");
}
else {
return criteriaBuilder.equal(root.get(criteria.getKey()), criteria.getValue());
}
}
return null;
}
}
| true |
a09b892e393d331dbb20d5def1637161969a77cc | Java | hyunkin2127/CodingInterviewJava | /main.java | UTF-8 | 14,071 | 2.15625 | 2 | [] | no_license | import dynamicProblems.FindMaxAsc;
import dynamicProblems.FindMaxSum;
import etc.memoization;
import graph.*;
import heap.ArrayHeap;
import heap.ArrayHeap2;
import linkedList.LinkedList;
import queue.ArrayQueue;
import sort.BaseSort2;
import sort.MergeSort;
import sort.QuickSort;
import sort.quick;
import stack.FindMaxRect;
import stringAlgorithm.Trie;
import stringAlgorithm.stringExamples;
import threads.threadExams;
import trees.AVL;
import trees.BST;
import trees.Node;
import algorithm.drawingLots;
import java.util.Arrays;
import java.util.Collections;
import java.util.Stack;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class main {
public static void main(String[] args) {
// testArrayQueue();
// testSort();
// testquick();
// testMemoization();
testBST2();
// testAVL();
// testGraph();
// testGraph2();
// testMST_Kruskal();
// testDijkstra();
// testLots();
// testExtends();
// testThread();
// testSort();
// testXOR();
// testTrie();
// testStringExamples();
// Integer[] a = {8, 9, 51, 122, 36, 4, 65, 15, 12, 13, 24, 26, 27, 48, 19, 20, 44, 88, 29, 8, 64, 2, 8};
// Integer[] d={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,20};
// int[] c = {20, 22, 23, 24,10,11,12,13,14,15,16,17,18,19};
// int[] b={1,14,4,5,2,6,9,3,12,10,7,8,20,15,13,11,17,19,16}; //18
// String a = "abcd";
// char[] q = a.toCharArray();
// System.out.println(q[0]);
//
// String qwe = Arrays.toString(q);
// System.out.println(qwe);
// System.out.println(q);
// int[] q = testArr(c);
// System.out.println(c);
// System.out.println(q[1]);
// SpliteArrayOddEven sa = new SpliteArrayOddEven(c);
// sa.spliteByQuick();
// for(int q : sa.arr){
// System.out.println(q);
// }
// testGraph();
// testTree();
// testHeap();
// FindSumNumb fs = new FindSumNumb(c);
// System.out.println(fs.FindByBF(43));
// System.out.println(fs.FindByHash(1));
// FindMissingNumb fNum = new FindMissingNumb(b);
// System.out.println("BF : "+fNum.findNumbByBF());
// System.out.println("HASH : "+fNum.findNumbByHash());
// System.out.println("SORT : "+fNum.findNumbBySort());
// TestHashMap tm = new TestHashMap();
// tm.makeHashMap(a);
}
public static void testXOR(){
// 코딩인터뷰 p.416 중복되는수와 빠진숫자 찾기
// 이거 실행하면 잘 되는데 원리를 모르겠네
// 문제점 : 중복된수가 2개 이상일 경우 결과값이 0 으로 나옴
int[] b={2,1, 7, 4, 5, 6, 3, 14, 9, 10, 11, 12, 13, 8, 15, 16, 17, 19, 19};
int temp = b[0];
int setBit;
int x = 0; // 중복되는 수
int y = 0; // 빠진 수
for(int i=1; i<b.length; i++) temp ^= b[i]; // 배열원소 간 XOR 연산
System.out.println("temp(XOR b[]): "+temp);
for(int i=1; i<=b.length; i++) temp ^= i; // 배열 원소 XOR 연산 결과에 1~N까지 XOR 연산
System.out.println("temp(XOR b[], i ): "+temp);
setBit = temp & ~(temp-1); // 전체 XOR 연산 결과에서 1로 세팅되어있는 가장 오른쪽 비트 확인
for(int i=0; i<b.length; i++){
System.out.println("b["+i+"] : " +b[i]+ " // b["+i+"] & setBit : "+ (b[i] & setBit));
if((b[i] & setBit) > 0 ) x = x^b[i];
else y = y^b[i];
}
for(int i=1; i<=b.length; i++){
if( (i & setBit) > 0) x = x ^ i;
else y = y ^ i;
}
System.out.println("DuplicatedNum : "+ x +" // MissingNum : " + y);
}
public static void testThread(){
threadExams te = new threadExams();
te.processThread();
}
public static int[] testArr(int[] a){
// 배열을 함수로 전달하면 해당 배열의 주소로 접근해서
// 전달된 배열 자체에 변경이 일어난다.
int[] b = a.clone();
b[0] = 0;
return b;
}
public static void testMemoization(){
memoization memo = new memoization(100);
long startM = System.nanoTime();
memo.memoziedFib(20);
long endM = System.nanoTime();
System.out.println( endM - startM );
long startF = System.nanoTime();
memo.normalFib(20);
long endF = System.nanoTime();
System.out.println(endF - startF);
System.out.println(memo.cnt1 + " // " +memo.cnt2);
}
public static void testLL(){
LinkedList ll = new LinkedList();
ll.insert(0);
ll.insert(1);
ll.insert(2);
ll.insert(3);
ll.insert(4);
ll.insert(5);
ll.insert(6);
ll.insert(7);
ll.insert(8);
ll.insert(9);
ll.deleteNode(5);
ll.deleteNode(3);
//
ll.printList();
}
public static void testArrayQueue(){
ArrayQueue<Integer> aq = new ArrayQueue(5);
aq.enQueue(10);
aq.enQueue(11);
aq.enQueue(12);
aq.enQueue(13);
aq.enQueue(14);
aq.enQueue(15);
aq.enQueue(16);
aq.printQueue();
aq.enQueue(17);
aq.enQueue(18);
aq.enQueue(19);
aq.enQueue(9);
// aq.enQueue(20);
System.out.println("deQ : " +aq.deQueue());
System.out.println("deQ : " +aq.deQueue());
aq.printQueue();
aq.enQueue(20);
aq.enQueue(21);
aq.printQueue();
aq.enQueue(23);
aq.enQueue(24);
aq.enQueue(25);
}
public static void testSort(){
int[] a = {8, 9, 51, 122, 36, 4, 65, 15, 12, 13, 24, 26, 27, 48, 19, 20, 44, 88, 29, 64, 2};
// MergeSort ms = new MergeSort(a);
// QuickSort qs = new QuickSort(a);
BaseSort2 bs = new BaseSort2(a);
// bs.selectionSort();
// bs.insertionSort();
bs.shellSort();
bs.showArr();
// ms.sort(0, a.length-1); //merge는 잘됨
// ms.showRepository();
// qs.sort(0, a.length-1); //안됨
// qs.showRepository();
}
public static void testquick(){
int[] list = {10,5,3,8,4,9,1,6,2,7};
quick quick = new quick();
System.out.println("before quick : " + Arrays.toString(list));
quick.quickSort(list, 0, list.length - 1);
System.out.println("after quick : " + Arrays.toString(list));
}
public static void testBST2(){
Node root = new Node(50);
BST bb = new BST(root);
bb.insert(root, null, 40);
bb.insert(root, null, 20);
bb.insert(root, null, 60);
bb.insert(root, null, 30);
bb.insert(root, null, 48);
bb.insert(root, null, 70);
bb.insert(root, null, 15);
bb.insert(root, null, 10);
bb.insert(root, null, 13);
bb.insert(root, null, 52);
bb.insert(root, null, 51);
bb.insert(root, null, 55);
bb.insert(root, null, 64);
bb.insert(root, null, 72);
bb.insert(root, null, 8);
// Node root = new Node(50);
// BST bb = new BST(root);
// bb.insert(root, null, 40);
// bb.insert(root, null, 20);
// System.out.println("BTS2 : " + bb.search(root, 60).getParent().getData());
bb.traverseTree(root);
// bb.delete(root, 60);
// bb.traverseTree(root);
}
public static void testAVL(){
Node root = new Node(50);
AVL aa = new AVL(root);
root = aa.insert(root , 40);
aa.insert(root , 60);
aa.insert(root , 70);
aa.insert(root , 80);
aa.insert(root , 45);
aa.insert(root , 48);
aa.insert(root , 47);
aa.insert(root , 43);
aa.insert(root , 30);
aa.insert(root , 25);
aa.insert(root , 27);
aa.insert(root , 35);
aa.insert(root , 94);
aa.insert(root , 90);
aa.insert(root , 16);
aa.insert(root , 21);
// LL 회전 -- 50만 나옴
// Node root = new Node(50);
// AVL aa = new AVL(root);
// root = aa.insert(root, 49);
// root = aa.insert(root, 48);
// //RR 회전 -- 50만 나옴
// Node root = new Node(50);
// AVL aa = new AVL(root);
// root = aa.insert(root, 51);
// root = aa.insert(root, 52);
System.out.println("root.data : " + root.getData());
System.out.println("root.left : " + root.getChild("left").getData());
System.out.println("root.right : " + root.getChild("right").getData());
aa.traverseTree(root);
}
public static void testHeap(){
ArrayHeap2 ah = new ArrayHeap2(20);
ah.insert(1);
ah.insert(2);
ah.insert(3);
ah.insert(4);
ah.insert(5);
ah.insert(6);
ah.insert(7);
ah.insert(8);
ah.insert(9);
ah.insert(10);
ah.printHeap();
System.out.println(ah.removeTop());
ah.printHeap();
System.out.println(ah.removeTop());
ah.printHeap();
System.out.println(ah.removeTop());
ah.printHeap();
System.out.println(ah.removeTop());
ah.printHeap();
System.out.println(ah.removeTop());
System.out.println(ah.removeTop());
}
public static void testPC(){
BlockingQueue queue = new ArrayBlockingQueue(50);
//BlockingQueue queue = new LinkedBlockingQueue();
ProdNCons2 pc2 = new ProdNCons2(queue);
Thread p = new Thread(pc2.p);
Thread c = new Thread(pc2.c);
p.start();
c.start();
// ProdNCons pc = new ProdNCons(4, 3);
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// synchronized (pc.list) {
// pc.done = true;
// pc.list.notifyAll();
// }
}
public static void testGraph(){
Graph g = new Graph(new boolean[6][6]);
g.insertEdge(0, 1);
g.insertEdge(0, 2);
g.insertEdge(1, 3);
g.insertEdge(1, 4);
g.insertEdge(2, 3);
g.insertEdge(4, 5);
g.insertEdge(3, 5);
g.point = 6;
GraphSearch tv = new GraphSearch(g);
tv.DSF(0);
// tv.BFS(0);
}
public static void testGraph2(){
// ShortestPathFinder sf = new ShortestPathFinder(4);
// sf.insertEdges(1, 2, 1);
// sf.insertEdges(1, 3, 4);
// sf.insertEdges(2, 3, 2);
// sf.insertEdges(3, 4, 2);
ShortestPathFinder sf = new ShortestPathFinder(7);
sf.insertEdges(1, 2, 1);
sf.insertEdges(1, 3, 4);
sf.insertEdges(2, 4, 5);
sf.insertEdges(3, 4, 3);
sf.insertEdges(4, 5, 2);
sf.insertEdges(4, 6, 5);
sf.insertEdges(5, 6, 1);
// sf.insertEdges(5, 7, 4);
sf.insertEdges(6, 7, 3);
sf.findShortestPath(1);
sf.showWay();
}
public static void testDijkstra(){
// Dijkstra d = new Dijkstra(6);
// d.insertEdges(0, 1, 1);
// d.insertEdges(0, 2, 3);
// d.insertEdges(1, 3, 5);
// d.insertEdges(2, 4, 4);
// d.insertEdges(3, 5, 2);
// d.insertEdges(4, 5, 2);
// d.findWay(0);
// d.showWay();
Dijkstra_complete d = new Dijkstra_complete(14);
d.insertEdges(0, 1, 1);
d.insertEdges(0, 2, 2);
d.insertEdges(0, 3, 3);
d.insertEdges(1, 4, 4);
d.insertEdges(1, 5, 5);
d.insertEdges(2, 5, 6);
d.insertEdges(3, 6, 11);
d.insertEdges(3, 12, 15);
d.insertEdges(4, 7, 8);
d.insertEdges(5, 7, 9);
d.insertEdges(5, 8, 10);
d.insertEdges(6, 8, 11);
d.insertEdges(7, 9, 1);
d.insertEdges(7, 10, 2);
d.insertEdges(8, 10, 3);
d.insertEdges(9, 11, 4);
d.insertEdges(10, 11, 5);
d.insertEdges(10, 12, 6);
d.insertEdges(11, 13, 3);
d.insertEdges(12, 13, 4);
d.findWay(0);
d.showWay();
}
public static void testMST_Kruskal(){
MST_Kruskal mk = new MST_Kruskal(7);
mk.insertEdge(0, 1, 1);
mk.insertEdge(0, 2, 4);
mk.insertEdge(1, 3, 5);
mk.insertEdge(2, 3, 3);
mk.insertEdge(3, 4, 2);
mk.insertEdge(3, 5, 5);
mk.insertEdge(4, 5, 1);
mk.insertEdge(5, 6, 3);
mk.insertEdge(4, 6, 4);
mk.showGraph(0, mk.originAdj);
System.out.println("=================================================");
mk.makeMST();
for(int i=0; i<mk.newAdj.length; i++){
for(int j=0; j<mk.newAdj[i].length; j++){
if(mk.newAdj[i][j] == Integer.MAX_VALUE) System.out.print("M ");
else System.out.print(mk.newAdj[i][j]+ " ");
}
System.out.println();
}
// mk.showGraph(0, mk.newAdj);
//
// for(int i=0; i<mk.newAdj.length; i++){
// for(int j=0; j<mk.newAdj[i].length; j++){
// System.out.print(mk.newAdj[i][j]+ " ");
// }
// System.out.println();
// }
}
public static void testDP_Q4(){
int [] a ={-10,-14,-5,-2,-7,-1,-15,-9,-25};
FindMaxSum fms = new FindMaxSum(a);
fms.findSection();
fms.findSection2();
fms.findSection3();
}
public static void testDP_Q20(){
int [] a ={-10, 1, 2, 3, 4, -14, -15, 2, 7, 10, 15, 24, 25, -1, -15, -9, -25, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
FindMaxAsc fma = new FindMaxAsc(a);
fma.findAsc();
}
public static void testStack_Q24(){
int[] arr= {1, 2, 4, 3, 2, 1, 5, 9, 7, 1, 4, 8};
FindMaxRect fmr = new FindMaxRect(arr);
fmr.calRect();
}
public static void testTrie(){
Trie t = new Trie();
t.add("APPLE");
t.add("APPLESAUCE");
t.add("APPLICATION");
System.out.println(t.contains("FOO") + " " + false);
System.out.println(t.contains("APPL") + " " + false);
System.out.println(t.contains("APPLES") + " " + false);
System.out.println(t.contains("APPLE") + " " + true);
}
public static void testStringExamples(){
stringExamples rs = new stringExamples("This is a apple");
rs.parseString();
}
public static void testLots(){
int[] c = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 13, 14, 16, 18, 20, 21, 23, 26, 28, 30, 31, 33, 34, 37, 39, 41, 45, 47, 49,
51, 54, 57, 60, 64, 67, 69, 73, 76, 77, 81, 89};
drawingLots dl = new drawingLots(c);
boolean isSuccess;
long start = System.nanoTime();
isSuccess = dl.canWin1(c, 231);
long end = System.nanoTime();
System.out.println((end-start) + " // "+ isSuccess);
long start2 = System.nanoTime();
isSuccess = dl.canWin2(c, 231);
long end2 = System.nanoTime();
System.out.println((end2-start2) + " // "+ isSuccess);
long start3 = System.nanoTime();
isSuccess = dl.canWin3(c, 231);
long end3 = System.nanoTime();
System.out.println((end3-start3) + " // "+ isSuccess);
long start4 = System.nanoTime();
isSuccess = dl.canWin4(c, 231);
long end4 = System.nanoTime();
System.out.println((end4-start4) + " // "+ isSuccess);
long start5 = System.nanoTime();
isSuccess = dl.canWin5(c, 231);
long end5 = System.nanoTime();
System.out.println((end5-start5) + " // "+ isSuccess);
}
public static void testExtends(){
abstract class A{
int a =10;
public void showA(){
System.out.println(a);
}
abstract public void showB();
}
class B extends A{
int b = 20;
public void showA(){
System.out.println(a+3);
}
public void showB() {
System.out.println(b);
}
}
A aa = new B();
B bb = new B();
aa.showA(); // 자식메서드에서 오버라이딩한 함수는 부모메서드 자료형에 넣더라도 잘 실행된다. // C++에서는 안된다
aa.showB(); // 추상클래스를 상속받아서 추상메서드를 구현하면, 자식메서드를 부모메서드자료형에 넣어도 실행가능
bb.showA();
}
}
| true |
7ce0a6a54315234b22d0ce57c4b777576dd3c3f2 | Java | yevhenii-filatov/denovo-linkedin | /projects/linkedin-scraper/src/main/java/com/dataox/linkedinscraper/parser/parsers/LinkedinExperienceParser.java | UTF-8 | 5,922 | 2.25 | 2 | [] | no_license | package com.dataox.linkedinscraper.parser.parsers;
import com.dataox.linkedinscraper.parser.LinkedinParser;
import com.dataox.linkedinscraper.parser.dto.LinkedinExperience;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;
import java.time.Instant;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.dataox.jsouputils.JsoupUtils.absUrlFromHref;
import static com.dataox.jsouputils.JsoupUtils.text;
import static com.dataox.linkedinscraper.parser.utils.ParsingUtils.toElement;
import static java.util.Objects.nonNull;
import static org.apache.commons.lang3.StringUtils.*;
@Service
@Slf4j
public class LinkedinExperienceParser implements LinkedinParser<List<LinkedinExperience>, String> {
@Override
public List<LinkedinExperience> parse(String source) {
if (isBlank(source)) {
log.info("received empty source");
return Collections.emptyList();
}
Element experienceSectionElement = toElement(source);
Instant time = Instant.now();
return splitExperience(experienceSectionElement).stream()
.flatMap(element -> resolveMultiplePositions(time, element))
.collect(Collectors.toList());
}
private Elements splitExperience(Element experienceSectionElement) {
return experienceSectionElement.select("header + ul > li");
}
private Stream<LinkedinExperience> resolveMultiplePositions(Instant time, Element element) {
if (isMultiplePositions(element)) {
return getAllPositions(time, element);
}
return Stream.of(getLinkedinExperience(element, time));
}
private boolean isMultiplePositions(Element element) {
return nonNull(element.selectFirst("h3 > span:contains(Company Name)"));
}
private Stream<LinkedinExperience> getAllPositions(Instant time, Element element) {
return splitMultiplePositions(element).stream()
.map(innerElement -> {
LinkedinExperience experience = getLinkedinExperience(innerElement, time);
experience.setCompanyName(parseCompanyName(element));
experience.setCompanyProfileUrl(parseCompanyProfileUrl(element));
experience.setJobType(parseJobTypeForMultiplePositions(element));
return experience;
});
}
private Elements splitMultiplePositions(Element experienceElement) {
return experienceElement.select(".pv-entity__position-group.mt2 > li");
}
private LinkedinExperience getLinkedinExperience(Element experienceElement, Instant time) {
LinkedinExperience experience = new LinkedinExperience();
experience.setUpdatedAt(time);
experience.setItemSource(experienceElement.html());
experience.setJobType(parseJobType(experienceElement));
experience.setCompanyName(parseCompanyName(experienceElement));
experience.setCompanyProfileUrl(parseCompanyProfileUrl(experienceElement));
experience.setPosition(parsePosition(experienceElement));
String dateRange = parseDateRange(experienceElement);
if (isNoneBlank(dateRange)) {
experience.setDateStarted(getDateStarted(dateRange));
experience.setDateFinished(getDateFinished(dateRange));
experience.setTotalDuration(parseTotalDuration(experienceElement));
}
experience.setLocation(parseLocation(experienceElement));
experience.setDescription(parseDescription(experienceElement));
return experience;
}
private String parseJobType(Element experienceElement) {
return text(experienceElement.selectFirst("span.pv-entity__secondary-title"));
}
private String parseJobTypeForMultiplePositions(Element experienceElement) {
return text(experienceElement.selectFirst(".pv-entity__position-group.mt2 > li .pv-entity__summary-info-v2 > h4.t-14.t-black.t-normal"));
}
private String parseCompanyName(Element experienceElement) {
Element companyNameElement = experienceElement.selectFirst("h3 > span:contains(Company Name) + span");
return nonNull(companyNameElement)
? text(companyNameElement)
: text(experienceElement.selectFirst("p:contains(Company Name) + p"));
}
private String parseCompanyProfileUrl(Element experienceElement) {
return absUrlFromHref(experienceElement.selectFirst("a[data-control-name=background_details_company]"));
}
private String parsePosition(Element experienceElement) {
return text(experienceElement.selectFirst("h3:not(:contains(Company name))"))
.replace("Title", "")
.trim();
}
private String parseDateRange(Element experienceElement) {
return text(experienceElement.selectFirst(".pv-entity__date-range > span + span"));
}
private String getDateStarted(String dateRange) {
return substringBefore(dateRange, " – ").trim();
}
private String getDateFinished(String dateRange) {
return substringAfter(dateRange, " – ").trim();
}
private String parseTotalDuration(Element experienceElement) {
return text(experienceElement.selectFirst("h4:contains(Employment Duration) > span + span"));
}
private String parseLocation(Element experienceElement) {
return text(experienceElement.selectFirst(".pv-entity__location > span + span"));
}
private String parseDescription(Element experienceElement) {
String description = text(experienceElement.selectFirst(".pv-entity__extra-details"));
return nonNull(description)
? description.replaceAll("see less", "")
: null;
}
}
| true |
936ceabda168b664cf2fafaf055668d910e784c4 | Java | hzf007/WatchPlus | /greendao/src/main/java/com/example/mobi/greendao/dbmanager/GoodsDbManager.java | UTF-8 | 706 | 2.1875 | 2 | [] | no_license | package com.example.mobi.greendao.dbmanager;
import android.content.Context;
import com.example.mobi.greendao.BaseDao;
import com.example.mobi.greendao.entity.Goods;
/**
* Created by hzf on 2016/12/15 0015.
*/
public class GoodsDbManager extends BaseDao<Goods> {
public GoodsDbManager(Context context) {
super(context);
} /***************************数据库查询*************************/
/**
* 通过ID查询对象
* @param id
* @return
*/
private Goods loadById(int id){
return daoSession.getGoodsDao().load(id);
}
@Override
public Goods QueryById(long id, Class object) {
return super.QueryById(id, object);
}
}
| true |
ed5debc394d6a64e343990630219c13cca5c960c | Java | InMobi/incubator-falcon | /metrics/src/main/java/org/apache/falcon/aspect/AbstractFalconAspect.java | UTF-8 | 3,999 | 2.234375 | 2 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.falcon.aspect;
import org.apache.falcon.util.ResourcesReflectionUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
/**
* Abstract Falcon Aspect, which intercept methods annotated with Monitored and
* publishes messages. Subclasses should override publishMessage Method.
*/
@Aspect
public abstract class AbstractFalconAspect {
private static final Logger LOG = LoggerFactory.getLogger(AbstractFalconAspect.class);
@Around("@annotation(org.apache.falcon.monitors.Monitored)")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
Object result = null;
ResourceMessage.Status status;
long startTime = System.nanoTime();
long endTime;
try {
result = joinPoint.proceed();
} catch (Exception e) {
endTime = System.nanoTime();
status = ResourceMessage.Status.FAILED;
publishMessage(getResourceMessage(joinPoint.getSignature()
.getDeclaringType().getSimpleName()
+ "." + methodName, args, status, endTime - startTime));
throw e;
}
endTime = System.nanoTime();
status = ResourceMessage.Status.SUCCEEDED;
publishMessage(getResourceMessage(joinPoint.getSignature()
.getDeclaringType().getSimpleName()
+ "." + methodName, args, status, endTime - startTime));
return result;
}
private ResourceMessage getResourceMessage(String methodName,
Object[] args, ResourceMessage.Status status, long executionTime) {
String action = ResourcesReflectionUtil
.getResourceMonitorName(methodName);
assert action != null : "Method :" + methodName
+ " not parsed by reflection util";
Map<String, String> dimensions = new HashMap<String, String>();
if (ResourcesReflectionUtil.getResourceDimensionsName(methodName) == null) {
LOG.warn("Class for method name: {} is not added to ResourcesReflectionUtil", methodName);
} else {
for (Map.Entry<Integer, String> param : ResourcesReflectionUtil
.getResourceDimensionsName(methodName).entrySet()) {
dimensions.put(
param.getValue(),
args[param.getKey()] == null ? "NULL" : args[param
.getKey()].toString());
}
}
Integer timeTakenArg = ResourcesReflectionUtil
.getResourceTimeTakenName(methodName);
return timeTakenArg == null ? new ResourceMessage(action, dimensions, status, executionTime)
: new ResourceMessage(action, dimensions, status, Long.valueOf(args[timeTakenArg].toString()));
}
public abstract void publishMessage(ResourceMessage message);
}
| true |
b65b2afc9d669105d27eaa80dfa08bdb32425e63 | Java | JmcRobbie/FS_numerical-simulation | /simulator/src/main/java/msp/simulator/Main.java | UTF-8 | 2,035 | 2.234375 | 2 | [] | no_license | /* Copyright 20017-2018 Melbourne Space Program
* 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 msp.simulator;
import org.hipparchus.complex.Quaternion;
import org.hipparchus.geometry.euclidean.threed.Vector3D;
import msp.simulator.NumericalSimulator;
import msp.simulator.dynamic.torques.TorqueProviderEnum;
import msp.simulator.satellite.assembly.SatelliteBody;
import msp.simulator.user.Dashboard;
/**
* @author Florian CHAUBEYRE <chaubeyre.f@gmail.com>
*
*/
public class Main {
/**
* Main method: compute the main use-case of the simulator.
* @param args - unused
*/
public static void main(String[] args) {
try {
/* *** Configuration of the simulator. *** */
Dashboard.setDefaultConfiguration();
Dashboard.setRealTimeProcessing(true);
Dashboard.setSimulationDuration(1000000);
Dashboard.setIntegrationTimeStep(0.1);
Dashboard.setEphemerisTimeStep(0.1);
Dashboard.setInitialAttitudeQuaternion(new Quaternion(1, 0, 0, 0));
Dashboard.setInitialSpin(new Vector3D(0.3, 0.3, 0.3)); // tip off 30 degrees per second
Dashboard.setInitialRotAcceleration(new Vector3D(0,0,0));
Dashboard.setTorqueDisturbances(false);
Dashboard.setCommandTorqueProvider(TorqueProviderEnum.CONTROLLER);
Dashboard.setVtsConnection(false);
/* *** Creating and launching the simulation. *** */
NumericalSimulator simulator = new NumericalSimulator();
simulator.initialize();
simulator.process();
simulator.exit();
} catch (Exception e) {
e.printStackTrace();
return;
}
}
}
| true |
57d343ca73108b5c7a70bb27b8d1d7b4299487f0 | Java | fancyboy2050/sockethttpconvert | /src/main/java/com/xgama/sockethttpconvert/client/ChargeClientHandler.java | UTF-8 | 2,722 | 2.28125 | 2 | [] | no_license | package com.xgama.sockethttpconvert.client;
import java.io.IOException;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.handler.timeout.ReadTimeoutException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.xgama.sockethttpconvert.pb.ChargeClass.Result;
public class ChargeClientHandler extends SimpleChannelHandler{
private final static Logger logger = LoggerFactory.getLogger(ChargeClientHandler.class);
private ChargeClient client;
private String key;
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
throws Exception {
if(e.getMessage() instanceof Result){
Result result = (Result)e.getMessage();
client.putResponse(result);
} else {
logger.error("receive message error,only support com.projectx.web.pb.ChargeClass.Result");
throw new Exception("receive message error,only support com.projectx.web.pb.ChargeClass.Result");
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
throws Exception {
if(!(e.getCause() instanceof IOException)){
logger.error("catch some exception not IOException",e.getCause());
//ReadTimeout异常
if(e.getCause() instanceof ReadTimeoutException){
logger.info("catch ReadTimeoutException , connection closed: " + ctx.getChannel().getRemoteAddress());
ChargeClientFactory.getInstance().removeClient(key);
//关闭channel
safeCloseChannel(ctx.getChannel());
}
}
}
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)
throws Exception {
logger.info("connection connected remote address : "+ctx.getChannel().getRemoteAddress());
logger.info("connection connected local address : "+ctx.getChannel().getLocalAddress());
}
@Override
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e)
throws Exception {
logger.warn("connection closed: "+ctx.getChannel().getRemoteAddress());
ChargeClientFactory.getInstance().removeClient(key);
}
public static void safeCloseChannel(Channel channel) {
if (null == channel) {
return;
}
try {
channel.close();
} catch (Exception e) {
logger.error("safeCloseChannel error", e.getCause());
}
}
public ChargeClient getClient() {
return client;
}
public void setClient(ChargeClient client) {
this.client = client;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
}
| true |
e1c1fa545c7ec49fbc06e4fd4ac658cce5969bd2 | Java | kdheeraj-cse/TestCaseGenerateWeb | /Dummy/InputXmlRead.java | UTF-8 | 8,759 | 2.390625 | 2 | [] | no_license | package operations;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import utilities.TestAttribute;
import java.io.File;
import java.util.ArrayList;
public class InputXmlRead {
static final String BoldStart = "[b]";
static final String BoldEnd = "[/b]";
static final String OrderedListStart = "[ol]";
static final String OrderedListEnd = "[/ol]";
static final String ListElementStart = "[li]";
static final String ListElementEnd = "[/li]";
//
// String processStepsToExecute(ArrayList<String>)
// {
//
//
//
// return "";
// }
ArrayList<String> processNodeWithNoChild(Node inputNode, String separatorStart, String separatorEnd)
{
ArrayList<String> returnList = new ArrayList<>();
if(!separatorStart.equalsIgnoreCase("")){
returnList.add(separatorStart);
}
returnList.add(inputNode.getTextContent());
if(!separatorEnd.equals("")){
returnList.add(separatorEnd);
}
return returnList;
}
ArrayList<String> processNodeWithChild(Node inputNode, String separatorStart, String separatorEnd)
{
ArrayList<String> returnList = new ArrayList<>();
if(!separatorStart.equals("")){
returnList.add(separatorStart);
}
returnList.add(OrderedListStart);
NodeList objNodeList = inputNode.getChildNodes();
System.out.println("Number of child node is "+objNodeList.getLength());
for (int j = 0; j < objNodeList.getLength(); j++) {
Node pcdNode = objNodeList.item(j);
pcdNode.getTextContent().trim();
if(pcdNode.hasChildNodes())
{
System.out.println("Node "+pcdNode.getNodeName()+" has child node");
returnList.addAll(processNodeWithChild(pcdNode, "", ""));
}
if(pcdNode.getNodeType() == Node.ELEMENT_NODE) {
returnList.add(ListElementStart+ pcdNode.getTextContent()+ ListElementEnd);
}
}
if(!separatorEnd.equals("")){
returnList.add(separatorEnd);
}
returnList.add(OrderedListEnd);
return returnList;
}
ArrayList<String> processXMltoList() {
String tempModifiedString = null;
TestAttribute.mylogger.info("Entered processXMltoList");
ArrayList<String> testparameterList = new ArrayList<String>();
try {
File fXmlFile = new File(TestAttribute.testStepsXmlInputPath);
TestAttribute.mylogger.info("XML File Path is set to "+TestAttribute.testStepsXmlInputPath);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
dbFactory.setIgnoringElementContentWhitespace(true);
//dbFactory.setSchema(schema);
dbFactory.setNamespaceAware(true);
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
Node rootNode = doc.getDocumentElement();
TestAttribute.mylogger.info("Root element :" + rootNode.getNodeName());
TestAttribute.testName=rootNode.getNodeName();
// testparameterList.add(rootNode.getNodeName()); // first element
// is
// testcase name
NodeList listOfNodes = doc.getDocumentElement().getChildNodes();
for (int i = 0; i < listOfNodes.getLength(); i++) {
Node HeadingNode = listOfNodes.item(i);
if (HeadingNode.getNodeType() == Node.ELEMENT_NODE) {
if (HeadingNode.getNodeName().equalsIgnoreCase("Category")) {
TestAttribute.mylogger.info("XML element found "+HeadingNode.getNodeName());
TestAttribute.objtestAttr.put("Category",
HeadingNode.getTextContent());
System.out.println("CategoryPut");
}
if (HeadingNode.getNodeName().equalsIgnoreCase("Priority")) {
TestAttribute.mylogger.info("XML element found "+HeadingNode.getNodeName());
TestAttribute.objtestAttr.put("Priority",
HeadingNode.getTextContent());
System.out.println("priorityPut");
}
if (HeadingNode.getNodeName().equalsIgnoreCase("Path")) {
TestAttribute.mylogger.info("XML element found "+HeadingNode.getNodeName());
testparameterList.addAll(processNodeWithNoChild(HeadingNode,"PATHSTART","PATHEND"));
System.out.println("pathPut");
}
if (HeadingNode.getNodeName().equalsIgnoreCase(
"TestCaseName")) {
TestAttribute.mylogger.info("XML element found "+HeadingNode.getNodeName());
testparameterList.addAll(processNodeWithNoChild(HeadingNode,"TCNAMESTART","TCNAMEEND"));
System.out.println("TCaseNamePut");
}
if (HeadingNode.getNodeName().equalsIgnoreCase(
"Prerequisite")) {
TestAttribute.mylogger.info("XML element found "+HeadingNode.getNodeName());
testparameterList.addAll(processNodeWithChild(HeadingNode, "PREREQUISITESTART", "PREREQUISITEEND"));
}
if (HeadingNode.getNodeName().equalsIgnoreCase(
"Description")) {
TestAttribute.mylogger.info("XML element found "+HeadingNode.getNodeName());
testparameterList.addAll(processNodeWithChild(HeadingNode, "DESCRIPTIONSTART", "DESCRIPTIONEND"));
}
if (HeadingNode.getNodeName().equalsIgnoreCase(
"TestCaseDescription")) {
TestAttribute.mylogger.info("XML element found "+HeadingNode.getNodeName());
testparameterList.add("TCDDESCRIPTIONSTART");
NodeList tcdNodeList = HeadingNode.getChildNodes();
for (int j = 0; j < tcdNodeList.getLength(); j++) {
Node tcdNode = tcdNodeList.item(j);
if (tcdNode.getNodeName().equalsIgnoreCase(
"StepsToExecute")) {
tempModifiedString = BoldStart
+ tcdNode.getNodeName() + BoldEnd;
testparameterList.add(tempModifiedString);
tempModifiedString = OrderedListStart;
testparameterList.add(tempModifiedString);
NodeList listOfSteps = tcdNode.getChildNodes();
for (int j1 = 0; j1 < listOfSteps.getLength(); j1++) {
Node stepNode = listOfSteps.item(j1);
if (stepNode.getNodeType() == Node.ELEMENT_NODE) {
/*
* System.out.println(stepNode
* .getNodeName() + " contains " +
* stepNode.getTextContent());
*/
tempModifiedString = ListElementStart
+ stepNode.getTextContent()
+ ListElementEnd;
testparameterList
.add(tempModifiedString);
}
}
tempModifiedString = OrderedListEnd;
testparameterList.add(tempModifiedString);
}
if (tcdNode.getNodeName().equalsIgnoreCase(
"ExpectedResult")) {
tempModifiedString = BoldStart
+ tcdNode.getNodeName() + BoldEnd;
testparameterList.add(tempModifiedString);
tempModifiedString = OrderedListStart;
testparameterList.add(tempModifiedString);
NodeList expectedList = tcdNode.getChildNodes();
for (int j1 = 0; j1 < expectedList.getLength(); j1++) {
Node expectedNode = expectedList.item(j1);
if (expectedNode.getNodeType() == Node.ELEMENT_NODE) {
/*
* System.out
* .println(expectedList.item(j)
* .getNodeName() + " contains " +
* expectedList.item(j)
* .getTextContent());
*/
tempModifiedString = ListElementStart
+ expectedNode.getTextContent()
+ ListElementEnd;
testparameterList
.add(tempModifiedString);
}
}
tempModifiedString = OrderedListEnd;
testparameterList.add(tempModifiedString); // list
// ends
}
if (tcdNode.getNodeName().equalsIgnoreCase(
"FinalExpectedResult")) {
tempModifiedString = BoldStart
+ tcdNode.getNodeName() + BoldEnd;
testparameterList.add(tempModifiedString);
tempModifiedString = OrderedListStart;
testparameterList.add(tempModifiedString);
NodeList expectedList = tcdNode.getChildNodes();
for (int j1 = 0; j1 < expectedList.getLength(); j1++) {
Node expectedNode = expectedList.item(j1);
if (expectedNode.getNodeType() == Node.ELEMENT_NODE) {
/*
* System.out
* .println(expectedList.item(j)
* .getNodeName() + " contains " +
* expectedList.item(j)
* .getTextContent());
*/
tempModifiedString = ListElementStart
+ expectedNode.getTextContent()
+ ListElementEnd;
testparameterList
.add(tempModifiedString);
}
}
tempModifiedString = OrderedListEnd;
testparameterList.add(tempModifiedString); // list
// ends
}
}
testparameterList.add("TCDDESCRIPTIONEND");
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return testparameterList;
}
} | true |
7a80324ac8dfee74ccbdbe5e2bb253e623757aff | Java | jihazard/android | /ex0729_viewer/app/src/main/java/com/example/ex0729_viewer/API/Api.java | UTF-8 | 215 | 1.78125 | 2 | [] | no_license | package com.example.ex0729_viewer.API;
public class Api {
public static final String BASE_URL = "https://script.google.com/macros/s/AKfycbxqog2NIKw1W5_mWgJfWhr0vPT5p3TFnIcrUzrB5WtXXVa0G9I/exec?action=read";
}
| true |
0ec6888d794e5b0ee1951d26af8567cf09e6d3fe | Java | TaoGe96/GLLMaven_Project1_Fall2020 | /src/main/java/GLListIterator.java | UTF-8 | 1,498 | 2.953125 | 3 | [] | no_license | import java.util.ListIterator;
public class GLListIterator<E> implements ListIterator<E> {
GenericLinkedList<E>.Node curr;
GenericLinkedList<E> Glist;
int index;
public GLListIterator(int i,GenericLinkedList<E>.Node curr,GenericLinkedList<E> Glist){
this.curr=curr;
this.Glist=Glist;
index=i;
}
@Override
public boolean hasNext() {
// TODO Auto-generated method stub
if(curr!=null) {
return true;
}
return false;
}
@Override
public E next() {
// TODO Auto-generated method stub
if(hasNext()) {
E data1 = curr.data;
curr=curr.next;
return data1;
}
return null;
}
@Override
public boolean hasPrevious() {
// TODO Auto-generated method stub
if(curr.prev!=null) {
return true;
}
return false;
}
@Override
public E previous() {
// TODO Auto-generated method stub
if(hasPrevious()) {
E data1 = curr.data;
curr=curr.prev;
// nextindex--;nextindex
return data1;
}
return null;
}
@Override
public int nextIndex() {
// TODO Auto-generated method stub
return index+1;
}
@Override
public int previousIndex() {
// TODO Auto-generated method stub
return index-1;
}
@Override
public void remove() {
// TODO Auto-generated method stub
}
@Override
public void set(E e) {
// TODO Auto-generated method stub
}
@Override
public void add(E e) {
// TODO Auto-generated method stub
}
}
| true |
33d1baa3f813205d227cfb501b3dc317388eac4a | Java | tomii07/ej-java-111mil | /EjerciciosJuegos/src/methods/Usuario.java | UTF-8 | 325 | 2.84375 | 3 | [] | no_license | package methods;
import java.util.Scanner;
public class Usuario {
public static String usuario(){
Scanner sc = new Scanner(System.in);
System.out.print("Tu eleccion?" + "[piedra ; papel ; tijera]: ");
String eleccion = sc.next();
System.out.print("\n");
return eleccion;
}
}
| true |
ff093881aa8680299b7b44cae85a53285ed6ddb5 | Java | antobattista89/Cuenta2 | /test/ar/edu/unlam/pb2/cuenta2/TestCuenta.java | UTF-8 | 601 | 2.3125 | 2 | [] | no_license | package ar.edu.unlam.pb2.cuenta2;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
public class TestCuenta {
@Test
public void queSePuedaCrearUnaCuentaSueldo() {
CuentaSueldo2 cuentaSueldo = new CuentaSueldo2("Anto");
assertNotNull(cuentaSueldo);
}
@Test
public void queSePuedaCrearUnaCuentaCorriente() {
CuentaCorriente2 cuentaCorriente = new CuentaCorriente2("Anto");
assertNotNull(cuentaCorriente);
}
@Test
public void queSePuedaCrearUnaCajaDeAhorro() {
CajaDeAhorro2 cajaDeAhorro = new CajaDeAhorro2("Anto");
assertNotNull(cajaDeAhorro);
}
}
| true |
3d88275a84c534739a43a2938e758df865a0796e | Java | xiaohao3137/SmsForwarder | /app/src/main/java/com/idormy/sms/forwarder/model/AppInfo.java | UTF-8 | 1,248 | 2.21875 | 2 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | package com.idormy.sms.forwarder.model;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import androidx.annotation.NonNull;
import lombok.Data;
@Data
public class AppInfo {
public String pkgName;
public String appName;
public Drawable appIcon;
public Intent appIntent;
public String verName;
public int verCode;
public AppInfo() {
}
public AppInfo(String appName) {
this.appName = appName;
}
public AppInfo(String appName, String pkgName) {
this.appName = appName;
this.pkgName = pkgName;
}
public AppInfo(String appName, String pkgName, Drawable appIcon, String verName, int verCode) {
this.appName = appName;
this.pkgName = pkgName;
this.appIcon = appIcon;
this.verName = verName;
this.verCode = verCode;
}
@NonNull
@Override
public String toString() {
return "AppInfo{" +
"appName='" + appName + '\'' +
", pkgName='" + pkgName + '\'' +
", appIcon=" + appIcon +
", verName=" + verName +
", verCode=" + verCode +
'}';
}
}
| true |
cecc58832231b272e2e86fb6dd247643790a1b2b | Java | marshauf/uni | /irrlicht/Irrlicht/src/com/marcelhauf/irrlicht/world/PhysicsObject.java | UTF-8 | 1,532 | 2.984375 | 3 | [] | no_license | package com.marcelhauf.irrlicht.world;
import com.badlogic.gdx.math.Vector2;
public class PhysicsObject {
protected final Vector2 acceleration = new Vector2(0,0);
protected final Vector2 position = new Vector2(0,0);
protected final Vector2 velocity = new Vector2(0,0);
public Vector2 getAcceleration(Vector2 value) { return value.set(acceleration); }
public Vector2 getPosition(Vector2 value) { return value.set(position); }
public Vector2 getVelocity(Vector2 value) { return value.set(velocity); }
public void setAcceleration(Vector2 value) { acceleration.set(value); }
// Sets the center position of the physics object.
public void setPosition(Vector2 value) { position.set(value); }
public void setVelocity(Vector2 value) { velocity.set(value); }
/* Velocity Verlet
private final Vector2 lastPosition = new Vector2();
private final Vector2 nextPosition = new Vector2();
*/
public void update(float deltaTime) {
// Euler method to calculate motion over time
velocity.x += acceleration.x * deltaTime;
velocity.y += acceleration.y * deltaTime;
position.x += velocity.x * deltaTime;
position.y += velocity.y * deltaTime;
// Velocity Verlet integration, second degree
/*
velocity.x = position.x - lastPosition.x;
velocity.y = position.y - lastPosition.y;
nextPosition.x = position.x + velocity.x + acceleration.x * deltaTime;
nextPosition.y = position.y + velocity.y + acceleration.y * deltaTime;
lastPosition.set(position);
position.set(nextPosition);
*/
}
}
| true |
eac73472d51f68bf374c4eb152e1a8cf4209f222 | Java | CalumMortimer/clean-up-application | /Clean-Up-Application/app/src/main/java/com/example/communitycleanup/Data/LogIssueDatabase.java | UTF-8 | 1,862 | 2.421875 | 2 | [] | no_license | package com.example.communitycleanup.Data;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.example.communitycleanup.DataTransfer.LogAnIssue;
public class LogIssueDatabase extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "Reported Issue";
private static final String TABLE_NAME = "Issue";
private static final String KEY_ID = "id";
//private static final String KEY_User = "User_Email";
private static final String KEY_Area = "Area Postcode";
private static final String KEY_Details = "Details";
private static final String[] COLUMNS = { KEY_ID, KEY_Area,
KEY_Details };
public LogIssueDatabase (Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
//String CREATION_TABLE = "CREATE TABLE Issues ( "
// + "id INTEGER PRIMARY KEY AUTOINCREMENT, "
// + "Postcode TEXT, " + "Details TEXT )";
//db.execSQL(CREATION_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// you can implement here migration process
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
this.onCreate(db);
}
public void addIssue(LogAnIssue evidence) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
//values.put(KEY_User, evidence.userEmail);
//values.put(KEY_Area, evidence.postcode);
values.put(KEY_Details, evidence.description);
// insert
db.insert(TABLE_NAME,null, values);
db.close();
}
}
| true |
7996fc3dafd6ea8f0b9b83ece47d15e425df57eb | Java | markphip/testing | /jira-dvcs-connector-api/src/main/java/com/atlassian/jira/plugins/dvcs/service/message/HasProgress.java | UTF-8 | 295 | 1.585938 | 2 | [
"BSD-2-Clause"
] | permissive | package com.atlassian.jira.plugins.dvcs.service.message;
import com.atlassian.jira.plugins.dvcs.model.Progress;
public interface HasProgress extends HasRepository
{
Progress getProgress();
int getSyncAuditId();
boolean isSoftSync();
boolean isWebHookSync();
}
| true |
838aa60377d38fbafdc2709fa6bd2257ff1d06bd | Java | Azgalor/Additional-Buildcraft-Objects-Mod | /common/abo/pipes/PipeTransportItemsCrossover.java | UTF-8 | 1,284 | 2.359375 | 2 | [] | no_license | /**
* Copyright (C) 2011-2012 Flow86
*
* AdditionalBuildcraftObjects is open-source.
*
* It is distributed under the terms of my Open Source License.
* It grants rights to read, modify, compile or run the code.
* It does *NOT* grant the right to redistribute this software or its
* modifications in any form, binary or source, except if expressively
* granted by the copyright holder.
*/
package abo.pipes;
import java.util.LinkedList;
import net.minecraftforge.common.ForgeDirection;
import buildcraft.api.core.Position;
import buildcraft.transport.EntityData;
import buildcraft.transport.PipeTransportItems;
/**
* This pipe will always prefer to use the opposite direction, so items will go
* "straight through"
*
* @author blakmajik ported to BC > 2.2 by Flow86
*/
public class PipeTransportItemsCrossover extends PipeTransportItems {
@Override
public LinkedList<ForgeDirection> getPossibleMovements(EntityData data) {
LinkedList<ForgeDirection> list = new LinkedList<ForgeDirection>();
Position newPos = new Position(xCoord, yCoord, zCoord, data.input);
newPos.moveForwards(1.0);
if (canReceivePipeObjects(newPos.orientation, data.item))
list.add(newPos.orientation);
else
list = super.getPossibleMovements(data);
return list;
}
}
| true |
f2417cbd4537556aeb8d3d9e179550604a54c510 | Java | FlyingPigQAQ/leetcoding | /src/main/java/com/pigcanfly/leetcoding/s237/DeleteNodeinaLinkedList.java | UTF-8 | 610 | 3.015625 | 3 | [] | no_license | package com.pigcanfly.leetcoding.s237;
/**
* TODO: WOW stupid
*
* The linked list will have at least two elements.
* All of the nodes' values will be unique.
* The given node will not be the tail and it will always be a valid node of the linked list.
* Do not return anything from your function.
* @author Tobby Quinn
* @date 2019/07/18
*/
public class DeleteNodeinaLinkedList {
public void deleteNode(ListNode node) {
node.val=node.next.val;
node.next=node.next.next;
}
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
}
| true |
483e0365ad9f62b74a0b79e4584f37bbc19e646a | Java | doctormacky/WeChatService | /src/main/java/com/qx/wechat/comm/sdk/request/msg/PassiveTextSendMsg.java | UTF-8 | 640 | 2.15625 | 2 | [] | no_license | package com.qx.wechat.comm.sdk.request.msg;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
/**
*
* @author Macky(liuyunsh@cn.ibm.com)
*
* @date: Apr 12, 2020 12:07:00 PM
*
* @since: 1.0.0
*
*/
public class PassiveTextSendMsg extends PassiveMsg{
private static final long serialVersionUID = 929204027660555935L;
public PassiveTextSendMsg(){
super.setType(PassiveMsgType.TEXT_MSG.getValue());
}
@Override
public PassiveTextSendMsg setMsg(String msg) {
try {
super.setMsg(URLEncoder.encode(msg, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return this;
}
}
| true |
d497fdb99c50474eb0f839fc8245cb290e3e0664 | Java | tranvuluan/quancafe | /Quancafe_TranVuLuan/src/DAL/BanHang/TaoHoaDon/BanKhuVucDAL.java | UTF-8 | 2,300 | 2.484375 | 2 | [] | no_license | package DAL.BanHang.TaoHoaDon;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Vector;
import DAL.MyJDBCUtil;
import DTO.Ban;
import DTO.KhuVuc;
public class BanKhuVucDAL {
private static Connection conn = null;
private static PreparedStatement pstm = null;
private static ResultSet result = null;
public static Vector<KhuVuc> hienthiKhuVuc() {
Vector<KhuVuc> listKhuVuc = new Vector<KhuVuc>();
String sql = "SELECT * FROM tbl_khuvuc";
try {
conn = MyJDBCUtil.getConnection();
pstm = conn.prepareStatement(sql);
result = pstm.executeQuery();
while (result.next()) {
KhuVuc kv = new KhuVuc();
kv.setMaKV(result.getInt("ma_khuvuc"));
kv.setTenKV(result.getString("ten_khuvuc"));
listKhuVuc.add(kv);
}
result.close();
pstm.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return listKhuVuc;
}
public static Vector<Ban> hienthiBanTheoKhuVuc(KhuVuc kv) {
Vector<Ban> listBan = new Vector<Ban>();
String sql = "SELECT * FROM tbl_khuvuc, tbl_ban WHERE tbl_khuvuc.ma_khuvuc = tbl_ban.ma_khuvuc AND tbl_khuvuc.ten_khuvuc = ?";
try {
conn = MyJDBCUtil.getConnection();
pstm = conn.prepareStatement(sql);
pstm.setString(1, kv.getTenKV());
result = pstm.executeQuery();
while (result.next()) {
Ban ban = new Ban();
ban.setMaBan(result.getInt("ma_ban"));
ban.setTenBan(result.getString("ten_ban"));
ban.setKhuvuc(kv);
ban.setStatus(result.getInt("status"));
listBan.add(ban);
}
result.close();
pstm.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return listBan;
}
public void mokhoa(int ma_ban) {
String sql = "UPDATE tbl_ban SET status = 0 WHERE ma_ban = ?";
try {
conn = MyJDBCUtil.getConnection();
pstm = conn.prepareStatement(sql);
pstm.setInt(1, ma_ban);
pstm.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
public void khoaban(int ma_ban) {
String sql = "UPDATE tbl_ban SET status = 3 WHERE ma_ban = ?";
try {
conn = MyJDBCUtil.getConnection();
pstm = conn.prepareStatement(sql);
pstm.setInt(1, ma_ban);
pstm.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true |
e295d4b5200817208f0fc795a854a9b8335f4b31 | Java | yoshiylife/OZonJava | /src/executor/ExCommCipher.java | EUC-JP | 9,787 | 2 | 2 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | /*
Copyright(c) 1996-1998
IPA, ETL, AT21, FSIABC, FXIS, InArc, MRI, NUL, SBC, Sharp, TEC, TIS
All rights reserved. No guarantee.
This technology is a result of the Advanced Software Enrichment
Project of Information-technology Promotion Agency, Japan (IPA).
Permissions to use, copy, modify and distribute this software
are governed by the terms and conditions set forth in the file
COPYRIGHT, located on the top directory of this software.
*/
package JP.go.ipa.oz.system;
import java.lang.reflect.*;
import java.io.*;
import java.net.*;
import java.util.*;
/***
* ExCommCipher handles cache of cipher type of each terget GOL.
* Packets Types of cipher type negotiation is defined also.
*
* @author Tadayuki Higuchi
* @author Yoichi Hamazaki
*/
final class ExCommCipher {
private static String CN = "ExCommCipher";
private static final String fileSeparator = File.separator;
/**
* ʿʸ
*/
static public final String PlainText = new String("PlainText");
/**
* ѥåȥ
*/
static public final int Plain = 0;
static public final int PlainNegotiation = 1; // no one use this;
static public final int NegotiationStart = 2;
static public final int NegotiationStop = 3;
static public final int Result = 4;
static public final int Cryptogram = 5;
static public final int Cache = 6;
static public final int CryptogramEnd = 7;
static public final int NegotiationOk = 8;
static public final int CipherStart = -1;
/**
* ͥ륿
*/
static public final int caller = 0;
static public final int callee = 1;
/**
* ǡ¹ԥ
*/
static public final int Exe = 0;
static public final int ReCipher = 1;
static public final int Error = 2;
static public final int what = -1;
/**
* Hashtable to store cache of cipher type<br>
* cipherCache is Hashtable of (String)GOD as key and
* (Hashtable)CipherCacheOfThisCaller as value.
*/
static Dictionary cipherCache = new Hashtable();
/**
* Hashtable to store know type of cipher for each object<br>
*
* cipherTypes is Hashtable of (String)GOD as key and
* (Hashtable)KnownCipherType as value.
*/
private static Dictionary cipherTypes = new Hashtable();
/**
* å夬뤫å롣
*
* @return åˤꡢŹ沽֤̾
* å夬̵Ȥ null ֤
*
*/
public static synchronized String checkCache(String caller,
OzProxy calleeProxy)
throws ExException {
String calleeGolString = calleeProxy.getName();
Executor.debug(CN, "checkCache", "callee: " + calleeGolString);
ExGOD callerGod = newGOD(caller);
Dictionary cipherCacheTable
= (Dictionary)cipherCache.get(callerGod.getName());
if (cipherCacheTable == null) {
/* GOD/.ciphercache file has not been read */
cipherCacheTable = tryCacheFile(callerGod);
if (cipherCacheTable == null) {
cipherCacheTable = new Hashtable();
}
{
Hashtable t = (Hashtable)cipherCacheTable;
java.util.Enumeration keys = t.keys();
while (keys.hasMoreElements()) {
Executor.debug(CN, "checkCache",
"key: " + (String)keys.nextElement());
}
}
cipherCache.put(callerGod.getName(), cipherCacheTable);
}
return (String)cipherCacheTable.get(calleeGolString);
}
private static ExGOD newGOD(String caller) throws ExException {
try {
return new ExGOD(new ExGOL(caller));
} catch (ExException e) {
Executor.debug(CN, "newGOD", "cannot find GOD: " + caller, e);
throw e;
}
}
private static Dictionary tryCacheFile(ExGOD callerGod) {
File cacheFile = new File(callerGod, ".ciphercache");
if (cacheFile.exists() == true) {
Executor.debug(CN, "tryCacheFile", "file ok:" + cacheFile);
File cipherFile = new File(callerGod, ".cipher");
if (cacheFile.lastModified() < cipherFile.lastModified()) {
/* .cipher is newer than .ciphercache. Discard .ciphercache. */
Executor.debug(CN, "tryCacheFile", "obsolete cache");
cacheFile.delete();
return null;
} else {
ObjectInputStream oistream;
Executor.debug(CN, "tryCacheFile", "valid cache");
try {
oistream
= new ObjectInputStream(new FileInputStream(cacheFile));
} catch (IOException ioex) {
Executor.syslog(CN, "tryCacheFile",
"cache file open error. deleting it.",
ioex);
cacheFile.delete();
return null;
}
try {
return (Dictionary)oistream.readObject();
} catch (IOException ioex) {
Executor.syslog(CN, "tryCacheFile",
"cache file read error. deleting it.",
ioex);
cacheFile.delete();
return null;
} catch (ClassNotFoundException cnex) {
Executor.debug(CN, "tryCacheFile",
"cache file read error (class not found).",
cnex);
return null;
} finally {
try {
oistream.close();
} catch (IOException ioex) {
// ignore
}
}
}
} else {
return null;
}
}
/**
* å롣
*
* @param
*/
public static synchronized void makeCache(String caller, String callee,
String name)
throws ExException {
Dictionary cipherCacheTable;
ExGOD callerGod = newGOD(caller);
cipherCacheTable = (Dictionary)cipherCache.get(callerGod.getName());
if (cipherCacheTable != null) {
String registeredName = (String)cipherCacheTable.put(callee, name);
if (registeredName != null && registeredName.equals(name)) {
/* the cipher has already been registered. no need to save. */
return;
}
} else {
cipherCacheTable = new Hashtable();
cipherCacheTable.put(callee, name);
cipherCache.put(callerGod.getName(), cipherCacheTable);
}
Executor.debug("ExCommCipher#makeCache: saving cache");
File cacheFile = new File(callerGod, ".ciphercache");
if (cacheFile.exists()) {
File tmpFile = new File(callerGod, "ciphercache.tmp");
if (writeToFile(cipherCacheTable, tmpFile)) {
if (cacheFile.delete()) {
tmpFile.renameTo(cacheFile);
} else {
tmpFile.delete();
}
}
} else {
writeToFile(cipherCacheTable, cacheFile);
}
Executor.debug("ExCommCipher#makeCache: End");
}
private static boolean writeToFile(Object o, File file) {
ObjectOutputStream oostream;
try {
oostream = new ObjectOutputStream(new FileOutputStream(file));
} catch (IOException e) {
file.delete();
return false;
}
try {
oostream.writeObject(o);
} catch (IOException ioex) {
file.delete();
return false;
} finally {
try {
oostream.close();
} catch (IOException ioex) {
/* ignore */
}
}
return true;
}
/**
* .cipher Ƥɽ Dictionary 롣
* ޥΰŹ沽ꥹȤˤʤΤϴޤޤƤʤ
*
* @param gol callee GOL
* @return .cipher Ƥɽ Dictionary ֤
* ޥΥꥹȤˤʤΤϴޤޤƤʤ
* .cipher ʤϥޥΥꥹȤΤΤ֤
* @exception ExGOLFormatException
* when argument gol is in illegal format.
* @exception ExCommCipherException
* when other recoverable error occured.
*/
public static synchronized String[] getCellCipherList(String gol)
throws ExException {
Executor.debug(CN, "getCellCipherList", gol);
ExGOD god = newGOD(gol);
String[] cellCipherList
= (String[])ExCommCipher.cipherTypes.get(god.getName());
if (cellCipherList == null) {
cellCipherList = readCipherFile(god);
ExCommCipher.cipherTypes.put(god.getName(), cellCipherList);
}
return cellCipherList;
}
private static String[] readCipherFile(ExGOD god)
throws ExCommCipherException {
File cipherFile = new File(god, ".cipher");
if (cipherFile.exists()) {
Executor.debug(CN, "readCipherFile",
"reading " + cipherFile.getPath());
BufferedReader distream;
try {
distream = new BufferedReader(new FileReader(cipherFile));
} catch (FileNotFoundException e) {
Executor.syslog(CN, "readCipherFile",
"open failed: " + cipherFile, e);
throw new ExCommCipherException("open failed: " + cipherFile);
}
Vector list = new Vector();
boolean emptyfile = true;
try {
String name;
while ((name = distream.readLine()) != null) {
name = name.trim();
if (! name.startsWith("#") && ! name.equals("")) {
emptyfile = false;
if (name.equals(ExCommCipher.PlainText)
|| ExCipherTable.getCipher(name) != null) {
list.addElement(name);
Executor.debug(CN, "readCipherFile", name);
}
}
}
} catch (IOException e) {
Executor.syslog(CN, "readCipherFile",
"IOException while reading " + cipherFile, e);
throw new ExCommCipherException("read error: " + cipherFile);
} finally {
try {
distream.close();
} catch (IOException e) {
// ignore
}
}
/*
.cipher ե뤬äɤä˲᤹٤
ߤϡ¦Ƥ롣
.cipher ʤȤߤʤ٤ʤСʲ if ʸ褫Ф褤
if (emptyfile) {
Executor.debug(CN, "readCipherFile",
cipherFile.getPath() + " is empty");
return ExCipherTable.CipherName;
} else {
*/
String[] cellCipherList = new String[list.size()];
list.copyInto(cellCipherList);
return cellCipherList;
//}
} else {
Executor.debug(CN, "readCipherFile",
cipherFile.getPath() + "doesn't exist");
return ExCipherTable.CipherName;
}
}
}
| true |
60ee69b379ba079a755db4bd093f3b0ea984d418 | Java | haodoan/AndroidTVTest | /app/src/main/java/com/jindo/FPTTV/data/ChannelProvider.java | UTF-8 | 10,757 | 1.984375 | 2 | [] | no_license | package com.jindo.FPTTV.data;
import android.content.ContentProvider;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.OperationApplicationException;
import android.content.UriMatcher;
import android.content.pm.ProviderInfo;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.provider.BaseColumns;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import com.jindo.FPTTV.data.ChannelContracts.ItemTable;
import com.jindo.FPTTV.BuildConfig;
import java.util.ArrayList;
public class ChannelProvider extends ContentProvider {
private static final String LOG_TAG = ChannelProvider.class.getSimpleName();
public static final String AUTHORITY =
BuildConfig.APPLICATION_ID + "." + ChannelProvider.class.getSimpleName();
private static final String DATABASE_NAME = "channel_list.db";
private static final int DATABASE_VERSION_CURRENT = 3;
private DatabaseHelper openHelper;
private final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
private static final int MATCHER_CONTAINER = 1;
private static final int MATCHER_CONTAINER_ID = 2;
private static final int MATCHER_ITEM = 3;
private static final int MATCHER_ITEM_ID = 4;
private static final int MATCHER_BROWSE = 5;
private static final int MATCHER_BROWSE_ID = 6;
private void initMatcher(String authority) {
matcher.addURI(authority, ItemTable.PATH, MATCHER_ITEM);
matcher.addURI(authority, ItemTable.PATH + "/#", MATCHER_ITEM_ID);
}
@Nullable
@Override
public String getType(@NonNull Uri uri) {
String miner;
switch (matcher.match(uri)) {
case MATCHER_CONTAINER:
case MATCHER_CONTAINER_ID:
break;
case MATCHER_ITEM:
case MATCHER_ITEM_ID:
break;
case MATCHER_BROWSE:
case MATCHER_BROWSE_ID:
break;
default:
throw new IllegalArgumentException("uri " + uri + " not matched.");
}
String major;
if (isCollectionUri(uri)) {
major = "vnd.android.cursor.dir";
} else {
major = "vnd.android.cursor.item";
}
return major + "/";
}
@Override
public void attachInfo(Context context, ProviderInfo info) {
// ChannelProvider.AUTHORITY と、 AndroidManifest.xml の authority が一致していることを確認。
if (!AUTHORITY.equals(info.authority)) {
throw new RuntimeException(
"authority not matched. Expected: " + AUTHORITY + ", Actual:" + info.authority);
}
super.attachInfo(context, info);
}
@Override
public boolean onCreate() {
initMatcher(AUTHORITY);
openHelper = new DatabaseHelper(getContext(), DATABASE_NAME, null, DATABASE_VERSION_CURRENT);
return true;
}
private SQLiteDatabase getReadableDatabase() {
return openHelper.getReadableDatabase();
}
private SQLiteDatabase getWritableDatabase() {
return openHelper.getWritableDatabase();
}
private boolean isCollectionUri(Uri uri) {
switch (matcher.match(uri)) {
case MATCHER_CONTAINER:
case MATCHER_ITEM:
case MATCHER_BROWSE:
return true;
case MATCHER_CONTAINER_ID:
case MATCHER_ITEM_ID:
case MATCHER_BROWSE_ID:
return false;
default:
break;
}
throw new IllegalArgumentException("uri " + uri + " not matched.");
}
private String getTableName(Uri uri) {
switch (matcher.match(uri)) {
case MATCHER_ITEM:
case MATCHER_ITEM_ID:
return ItemTable.PATH;
default:
break;
}
throw new IllegalArgumentException("uri " + uri + " not matched.");
}
private ContentResolver getContentResolver() {
Context context = getContext();
if (context == null) {
throw new RuntimeException("context not initialized.");
}
return context.getContentResolver();
}
private void notifyChange(Uri itemUri) {
getContentResolver().notifyChange(itemUri, null);
}
@Nullable
@Override
public Cursor query(@NonNull Uri uri, String[] projection,
String selection, String[] selectionArgs, String sortOrder) {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String tableName = getTableName(uri);
qb.setTables(tableName);
if (!isCollectionUri(uri)) {
qb.appendWhere(BaseColumns._ID + " = " + ContentUris.parseId(uri));
}
String orderBy;
if (TextUtils.isEmpty(sortOrder)) {
orderBy = null;
} else {
orderBy = sortOrder;
}
// logd("query = " + qb.buildQuery(projection, selection, null, null, sortOrder, null));
Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy);
if (c != null) {
c.setNotificationUri(getContentResolver(), uri);
}
return c;
}
@Nullable
@Override
public Uri insert(@NonNull Uri uri, ContentValues values) {
SQLiteDatabase db = getWritableDatabase();
String tableName = getTableName(uri);
try {
long rowID = db.insertOrThrow(tableName, null, values);
Uri itemUri = ContentUris.withAppendedId(uri, rowID);
notifyChange(itemUri);
return itemUri;
} catch (SQLException e) {
throw e;
}
}
@Override
public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
final String tableName = getTableName(uri);
SQLiteDatabase db = getWritableDatabase();
db.beginTransaction();
try {
for (ContentValues val : values) {
db.insertWithOnConflict(tableName, null, val, SQLiteDatabase.CONFLICT_IGNORE);
}
db.setTransactionSuccessful();
} catch (SQLException e) {
throw e;
} finally {
db.endTransaction();
}
notifyChange(uri);
return values.length;
}
@NonNull
@Override
public ContentProviderResult[] applyBatch(
@NonNull ArrayList<ContentProviderOperation> operations)
throws OperationApplicationException {
SQLiteDatabase db = getWritableDatabase();
db.beginTransaction();
try {
ContentProviderResult[] result = super.applyBatch(operations);
db.setTransactionSuccessful();
return result;
} catch (SQLException e) {
throw e;
} finally {
db.endTransaction();
}
}
@Override
public int delete(@NonNull Uri uri, String selection, String[] selectionArgs) {
SQLiteDatabase db = getWritableDatabase();
final String tableName = getTableName(uri);
int ret;
if (!isCollectionUri(uri)) {
ret = db.delete(tableName, BaseColumns._ID + " = " + ContentUris.parseId(uri), null);
} else {
ret = db.delete(tableName, selection, selectionArgs);
}
if (ret > 0) {
notifyChange(uri);
}
return ret;
}
@Override
public int update(@NonNull Uri uri, ContentValues values,
String selection, String[] selectionArgs) {
SQLiteDatabase db = getWritableDatabase();
String tableName = getTableName(uri);
int ret;
if (!isCollectionUri(uri)) {
ret = db.update(tableName, values,
BaseColumns._ID + " = " + ContentUris.parseId(uri), null);
} else {
ret = db.update(tableName, values, selection, selectionArgs);
}
if (ret > 0) {
notifyChange(uri);
}
return ret;
}
private static void execSQL(SQLiteDatabase db, String sql) {
db.execSQL(sql);
}
private static void createTables(SQLiteDatabase db) {
final String ItemTableSQL = "CREATE TABLE IF NOT EXISTS " + ItemTable.PATH + " ( "
+ ItemTable._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ ItemTable.mChannelName + " TEXT NOT NULL, "
+ ItemTable.mGroupTitle + " TEXT NOT NULL, "
+ ItemTable.mLogoURL + " TEXT, "
+ ItemTable.mStreamURL + " TEXT, "
+ ItemTable.mType + " TEXT, "
+ ItemTable.flag_groupChanel + " INTEGER ) ";
// + ItemTable.mDuration + " TEXT ) ";
execSQL(db, ItemTableSQL);
// execSQL(db, "CREATE INDEX IF NOT EXISTS 'mChannelName_index' ON "
// + ItemTable.PATH + " (" + ItemTable.mChannelName);
// execSQL(db, "CREATE INDEX IF NOT EXISTS 'container_row_id_index' ON "
// + ItemTable.PATH + " (" + ItemTable.mGroupTitle
// + ")");
// execSQL(db, "CREATE INDEX IF NOT EXISTS 'title_index' ON "
// + ItemTable.PATH + " (" + ItemTable.mLogoURL + ")");
// execSQL(db, "CREATE INDEX IF NOT EXISTS 'date_index' ON "
// + ItemTable.PATH + " (" + ItemTable.mStreamURL + ")");
}
private static void dropTables(SQLiteDatabase db) {
String[] tables = { ItemTable.PATH };
for (String table : tables) {
execSQL(db, "DROP TABLE IF EXISTS " + table);
}
}
private static class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
createTables(db);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// このDBはキャッシュとして使用しているため、upgrade時は単純に削除して作り直している。
dropTables(db);
createTables(db);
}
}
}
| true |
c3eb037a8d39bcc217b98d7a03856c65ab71b672 | Java | EliasFrank/Algotithm | /src/day/hl2020_09_24/TwoSum.java | IBM855 | 1,142 | 3.796875 | 4 | [] | no_license | package day.hl2020_09_24;
public class TwoSum {
public static void main(String[] args) {
int[] numbers = {5,25,75};
int target = 100;
int[] result = new TwoSum().twoSum(numbers, target);
System.out.println(result[0] + " " + result[1]);
}
public int[] twoSum(int[] numbers, int target) {
if(numbers == null || numbers.length == 0) return null;
int a = 0;
int b = numbers.length - 1;
while(true) {
if((numbers[a] + numbers[b]) > target)
b--;
else if((numbers[a] + numbers[b]) < target)
a++;
else return new int[] {a, b};
}
}
private int[] ַ(int[] numbers, int target) {
if(numbers == null || numbers.length == 0) return null;
for(int i = 0; i < numbers.length - 1; i++) {
int a = target - numbers[i];
int low = i + 1;
int high = numbers.length - 1;
int mid = 0;
while(low <= high) {
mid = (low + high) / 2;
if(numbers[mid] < a) low = mid + 1;
else if(numbers[mid] > a) high = mid - 1;
else {
return new int[] {i+1, mid+1};
}
}
}
return null;
}
}
| true |
3be1c989f1eec39cf4a6878123310cb1349ed243 | Java | zyfncg/compilerLabs | /src/lexer/DFA.java | UTF-8 | 1,261 | 3.046875 | 3 | [] | no_license | package lexer;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* Created by st0001 on 2016/10/27.
*/
public class DFA {
private static int STATE_NUM = 0;
private int stateID = 0;
private Set<NFANode> nfaStates = new HashSet<>();
private String dfaName;
boolean accept = false;
private DFA(){
stateID = STATE_NUM;
STATE_NUM++;
}
public static DFA getDFAFromNFASet(Set<NFANode> nfaSet){
DFA dfa = new DFA();
Iterator<NFANode> it = nfaSet.iterator();
while (it.hasNext()){
NFANode nfa = it.next();
dfa.nfaStates.add(nfa);
if(nfa.isTerminal()){
dfa.accept = true;
dfa.dfaName = nfa.getNodeName();
}
}
return dfa;
}
public Set<NFANode> getNfaStates() {
return nfaStates;
}
public boolean hasNFAStates(Set<NFANode> nfaSet){
if(nfaStates.equals(nfaSet)){
return true;
}
return false;
}
public int getStateID() {
return stateID;
}
public String getDfaName() {
return dfaName;
}
public void setDfaName(String dfaName) {
this.dfaName = dfaName;
}
}
| true |
65cd892415e3b3c24edd00bab05265bc2f688adb | Java | cryptomator/siv-mode | /src/main/java9/org.cryptomator.siv/ThreadLocals.java | UTF-8 | 232 | 2.09375 | 2 | [
"MIT"
] | permissive | package org.cryptomator.siv;
import java.util.function.Supplier;
class ThreadLocals {
private ThreadLocals() {
}
static <S> ThreadLocal<S> withInitial(Supplier<S> supplier) {
return ThreadLocal.withInitial(supplier);
}
}
| true |
6e0cff4d802fc7b476e85e291d09b26ca7771b66 | Java | edmsvche/railway-station | /src/main/java/com/example/railwaystation/service/impl/TicketServiceImpl.java | UTF-8 | 2,192 | 2.21875 | 2 | [] | no_license | package com.example.railwaystation.service.impl;
import com.example.railwaystation.model.Ticket;
import com.example.railwaystation.repository.TicketRepository;
import com.example.railwaystation.service.TicketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class TicketServiceImpl implements TicketService {
private final TicketRepository ticketRepository;
@Autowired
public TicketServiceImpl(TicketRepository ticketRepository) {
this.ticketRepository = ticketRepository;
}
@Override
public void create(Ticket ticket) {
ticketRepository.save(ticket);
}
@Override
public List<Ticket> readAll() {
return ticketRepository.findAll();
}
@Override
public Ticket read(long id) {
if(ticketRepository.existsById(id))
return ticketRepository.findById(id).get();
else return null;
}
@Override
public boolean update(Ticket ticketOrig, long id) {
if(ticketRepository.existsById(id)){
Optional<Ticket> found = ticketRepository.findById(id);
if(found.isPresent()){
Ticket ticket = found.get();
ticket.setId(id);
if(ticketOrig.getPrice() == null){
ticket.setPrice(ticketOrig.getPrice());
}
if(ticketOrig.getPurchaseMethod() == null){
ticket.setPurchaseMethod(ticketOrig.getPurchaseMethod());
}
if(ticketOrig.getTicketStatus() == null){
ticket.setTicketStatus(ticketOrig.getTicketStatus());
}
ticketRepository.save(ticket);
return true;
}
}
return false;
}
/*@Override
public Ticket readBySchedule(long id) {
if ()
return null;
}*/
@Override
public boolean delete(long id) {
if(ticketRepository.existsById(id)){
ticketRepository.deleteById(id);
return true;
}
return false;
}
}
| true |
d3521c0e70323002fd39a5010a8ec7a7a0fa4e69 | Java | zhengqingya/java-workspace | /SpringCloud系列/02-Sentinel 1.8.4 规则持久化到Nacos/sentinel-dashboard-1.8.4-nacos/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/nacos/NacosConfig.java | UTF-8 | 1,286 | 1.96875 | 2 | [
"MIT"
] | permissive | package com.alibaba.csp.sentinel.dashboard.rule.nacos;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigFactory;
import com.alibaba.nacos.api.config.ConfigService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Properties;
@Configuration
public class NacosConfig {
@Value("${nacos.server-addr}")
private String serverAddr;
@Value("${nacos.namespace}")
private String namespace;
@Value("${nacos.group}")
public String group;
@Value("${nacos.username}")
private String username;
@Value("${nacos.password}")
private String password;
@Bean
public ConfigService nacosConfigService() throws Exception {
Properties properties = new Properties();
properties.put(PropertyKeyConst.SERVER_ADDR, this.serverAddr);
properties.put(PropertyKeyConst.NAMESPACE, this.namespace);
// properties.put(PropertyKeyConst.GROUP, this.group);
properties.put(PropertyKeyConst.USERNAME, this.username);
properties.put(PropertyKeyConst.PASSWORD, this.password);
return ConfigFactory.createConfigService(properties);
}
}
| true |
becc6d7d49083eeecbbaeccedc56c8def481057b | Java | Namikon/TecTech | /src/main/java/com/github/technus/tectech/compatibility/thaumcraft/definitions/iElementalAspect.java | UTF-8 | 189 | 1.609375 | 2 | [
"MIT"
] | permissive | package com.github.technus.tectech.compatibility.thaumcraft.definitions;
/**
* Created by Tec on 21.05.2017.
*/
public interface iElementalAspect {
Object materializeIntoAspect();
}
| true |
7e1d383bbe8c9449619c09d281ca9cad829ca5fc | Java | fnuecke/Circuity | /src/main/java/li/cil/lib/api/CapabilitiesAPI.java | UTF-8 | 1,169 | 2.578125 | 3 | [
"CC0-1.0",
"MIT",
"LicenseRef-scancode-public-domain"
] | permissive | package li.cil.lib.api;
import li.cil.lib.api.capabilities.WrapperProvider;
import net.minecraftforge.common.capabilities.Capability;
/**
* Access to capability wrappers.
*/
public interface CapabilitiesAPI {
/**
* Register a new capability wrapper for the specified capability.
*
* @param capability the capability to register the wrapper for.
* @param wrapperProvider the wrapper to register.
* @param <T> the generic type of the capability.
*/
<T> void register(final Capability<T> capability, final WrapperProvider<T> wrapperProvider);
/**
* Get a wrapped version of a list of capability instances.
* <p>
* If no {@link WrapperProvider} is registered for the capability, the first
* instance in the list is returned.
*
* @param capability the capability to get a wrapper for.
* @param instances the instances to wrap.
* @param <T> the generic type of the capability.
* @return a wrapper for the passed instances if possible; the first instance otherwise.
*/
<T> T getWrapper(final Capability<T> capability, final Iterable<T> instances);
}
| true |
1db60861f01c06bd4d988213f3513c5055f98a5e | Java | Kanchana009/kanchanaOOPsAssignmentSolution | /HrDepartment.java | UTF-8 | 616 | 2.734375 | 3 | [] | no_license | package com.gl.projectone.java;
public class HrDepartment
{
public HrDepartment()
{
System.out.println("Welcome to Hr Department");
}
public String departmentName()
{
return "Hr Department";
}
public String getTodaysWork()
{
return "Fill today's worksheet and mark your attendance";
}
public String getWorkDeadline()
{
return "Complete by EOD";
}
public String doActivity()
{
return "team Lunch";
}
public String isTodayHoliday()
{
return "Today is not a holiday";
}
}
| true |
43ce2457b6a67fc7240858092aad5ebf617db80c | Java | vineetsemwal/cg-javareact-2021-ls | /spring/bootschoolmswithjpa/src/main/java/com/cg/apps/bootschoolmswithjpa/dao/StudentDaoImpl.java | UTF-8 | 1,164 | 2.8125 | 3 | [] | no_license | package com.cg.apps.bootschoolmswithjpa.dao;
import java.util.*;
import com.cg.apps.bootschoolmswithjpa.entities.Student;
import com.cg.apps.bootschoolmswithjpa.exceptions.StudentNotFoundException;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
@Repository
public class StudentDaoImpl implements IStudentDao {
//@Autowired
@PersistenceContext
private EntityManager entityManager;
@Override
public void add(Student student) {
entityManager.persist(student);
}
@Override
public Student findById(int id) {
Student student=entityManager.find(Student.class,id);
if(student==null){
throw new StudentNotFoundException("student doesn't exist for id="+id);
}
return student;
}
@Override
public List<Student> findAll() {
String ql="from Student";
TypedQuery<Student> query=entityManager.createQuery(ql,Student.class);
List<Student>students=query.getResultList();
return students;
}
@Override
public Student update(Student student) {
student=entityManager.merge(student);
return student;
}
}
| true |
12b72fbffcda203ca564774e4fd6056b3813dcaf | Java | the-lazy-val/leetcode-premium | /google-prep/arrays-strings/849_Maximize_Distance_to_Closest_Person.java | UTF-8 | 4,260 | 3.796875 | 4 | [] | no_license | /**
My solution: 2 ms
beats 74%
*/
class Solution {
public int checkMax(int currmax, int[] seats, int start, int end){
int max = currmax;
if(start == end){
if(1 > max){
max = 1;
}
}else if(start == 0){
if(end-start+1 > max){
max = end-start+1;
}
}else if(end == seats.length-1){
if(end-start+1 > max){
max = end-start+1;
}
}else{
int distance = (end-start)/2;
if(distance+1 > max){
max = distance+1;
}
}
return max;
}
public int maxDistToClosest(int[] seats) {
int max = -1;
int start = -1;
int end = -1;
boolean flag = false;
for(int i=0; i<seats.length; i++){
if(!flag && seats[i] == 0){
flag = true;
start = i;
}else{
if(flag && seats[i] == 0){
end = i;
}
if(flag && seats[i] == 1){
flag = false;
end = i-1;
max = checkMax(max, seats, start, end);
}
}
}
if(flag){
max = checkMax(max, seats, start, end);
}
return max;
}
}
/**
LC solution:
Approach #1: Next Array
Let left[i] be the distance from seat i to the closest person sitting to the left of i. Similarly, let right[i] be the distance to the closest person sitting to the right of i. This is motivated by the idea that the closest person in seat i sits a distance min(left[i], right[i]) away.
Algorithm
To construct left[i], notice it is either left[i-1] + 1 if the seat is empty, or 0 if it is full. right[i] is constructed in a similar way.
Time Complexity: O(N), where N is the length of seats.
Space Complexity: O(N), the space used by left and right.
*/
class Solution {
public int maxDistToClosest(int[] seats) {
int N = seats.length;
int[] left = new int[N], right = new int[N];
Arrays.fill(left, N);
Arrays.fill(right, N);
for (int i = 0; i < N; ++i) {
if (seats[i] == 1) left[i] = 0;
else if (i > 0) left[i] = left[i-1] + 1;
}
for (int i = N-1; i >= 0; --i) {
if (seats[i] == 1) right[i] = 0;
else if (i < N-1) right[i] = right[i+1] + 1;
}
int ans = 0;
for (int i = 0; i < N; ++i)
if (seats[i] == 0)
ans = Math.max(ans, Math.min(left[i], right[i]));
return ans;
}
}
/**
LC solution
Approach #2: Two Pointer
Intuition
As we iterate through seats, we'll update the closest person sitting to our left, and closest person sitting to our right.
Algorithm
Keep track of prev, the filled seat at or to the left of i, and future, the filled seat at or to the right of i.
Then at seat i, the closest person is min(i - prev, future - i), with one exception. i - prev should be considered infinite if there is no person to the left of seat i, and similarly future - i is infinite if there is no one to the right of seat i.
Time Complexity: O(N), where NNN is the length of seats.
Space Complexity: O(1)
*/
class Solution {
public int maxDistToClosest(int[] seats) {
int N = seats.length;
int prev = -1, future = 0;
int ans = 0;
for (int i = 0; i < N; ++i) {
if (seats[i] == 1) {
prev = i;
} else {
while (future < N && seats[future] == 0 || future < i)
future++;
int left = prev == -1 ? N : i - prev;
int right = future == N ? N : future - i;
ans = Math.max(ans, Math.min(left, right));
}
}
return ans;
}
}
/**
LC solution
Approach #3: Group by Zero
My approach
*/
| true |
18737b01779cc952e1e6086a57ea9766f79b5a9a | Java | jeromeSamson/Pizzeria | /src/main/java/fr/pizzeria/ihm/menu/option/UpdatePizza.java | UTF-8 | 2,924 | 2.90625 | 3 | [] | no_license | package fr.pizzeria.ihm.menu.option;
import static fr.pizzeria.ihm.utils.VerificationSaisie.verifCate;
import static fr.pizzeria.ihm.utils.VerificationSaisie.verifSaisiePrix;
import java.sql.SQLException;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Locale;
import java.util.Scanner;
import javax.persistence.EntityManagerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.pizzeria.dao.IPizzaDao;
import fr.pizzeria.dao.exception.PizzaUpdate;
import fr.pizzeria.model.CategoriePizza;
import fr.pizzeria.model.Pizza;
public class UpdatePizza extends OptionMenu {
String libelle = "3. Modifier une pizza";
Scanner saisie = new Scanner(System.in);
private static final Logger LOG = LoggerFactory.getLogger(UpdatePizza.class);
public UpdatePizza(IPizzaDao dao) {
super(dao);
}
@Override
public String getLibelle() {
return libelle;
}
/**
* Mise a jour d'une pizza On verifie si la liste des pizzas n'est pas vide
* On demande le code de la pizza � modifier On v�rifie que le code saisi
* existe Si non on redemande une saisie Si oui on demande le nouveau nom,
* le nouveau code qui peut �tre identique que celui saisi pr�cedemment mais
* différent d'un déja présent dans la liste le nouveau Prix (on verifie la
* saisie) la nouvelle categorie (on verifie la saisie)
*
* @throws SQLException
* @throws ClassNotFoundException
*/
@Override
public boolean execute(EntityManagerFactory emf) throws PizzaUpdate, SQLException, ClassNotFoundException {
double prix;
saisie.useLocale(Locale.US);
List<Pizza> pizzas = daoPizza.findAllPizzas();
if (pizzas.isEmpty()) {
LOG.info("Aucune pizza dans la base de données.\n Veuillez en ajouter une. ");
return false;
}
LOG.info("Veuillez saisir le code de la pizza à modifier (quit pour quitter) : ");
String code = saisie.next();
if ("QUIT".equalsIgnoreCase(code)) {
return false;
}
while (!daoPizza.pizzaExist(code.toUpperCase())) {
LOG.info("Erreur le code saisi n'existe pas ");
LOG.info("Veuillez saisir le code de la pizza à modifier (quit pour quitter) : ");
code = saisie.next();
if ("QUIT".equalsIgnoreCase(code)) {
return false;
}
}
LOG.info("Veuillez saisir le nouvau nom de la pizza : ");
String nom = saisie.next();
if ("QUIT".equalsIgnoreCase(nom)) {
return false;
}
CategoriePizza cate;
cate = verifCate();
if (cate == null)
return false;
try {
prix = verifSaisiePrix();
if (Math.abs(prix - 0.0D) <= 0) {
return false;
}
daoPizza.updatePizza(code.toUpperCase(), new Pizza(nom, code.toUpperCase(), prix, cate));
LOG.info("Pizza modifier");
return true;
} catch (InputMismatchException e1) {
LOG.info(
"Erreur a la saisie veuillez mettre un point entre la partie entière et la partie décimal (exemple : 12.5) ",
e1);
}
return false;
}
}
| true |
7c6574c21b9f3ad379dcd9046843b889f1b0fee4 | Java | Jacques-Fry/HuaLianTou | /src/main/java/com/transo/hualiantou/pojo/ClassifyRealm.java | UTF-8 | 1,408 | 2.0625 | 2 | [] | no_license | package com.transo.hualiantou.pojo;
import com.fasterxml.jackson.annotation.JsonBackReference;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.io.Serializable;
import java.util.*;
@Entity
@Table(name = "classify_realm")
@ApiModel(value = "领域模型")
@Getter
@Setter
public class ClassifyRealm implements Serializable {
@Id
@Column(name = "cr_unid", columnDefinition = "bigint COMMENT'领域主键id'")
@GeneratedValue(strategy = GenerationType.IDENTITY)
@ApiModelProperty(value = "领域主键id")
private long id;
@Column(name = "cr_code", length = 6, columnDefinition = "varchar(255) COMMENT'领域编码'")
@ApiModelProperty(value = "领域编码")
private String code;
@Column(name = "cr_name", columnDefinition = "varchar(255) COMMENT'领域名称'")
@ApiModelProperty(value = "领域名称")
private String name;
@Column(name = "cr_create_time", columnDefinition = "timestamp COMMENT'创建时间'")
@Temporal(TemporalType.TIMESTAMP)
@ApiModelProperty(value = "创建时间")
private Date createTime;
@JsonBackReference
@OneToMany(targetEntity = ClassifyTag.class)
@JoinColumn(name = "ct_realm_code", referencedColumnName = "cr_code")
private List<ClassifyTag> tags = new ArrayList<>();
}
| true |
f94dc03b0c06fed5ab7cfd87f86da9820219e8cb | Java | MondayIsSun/J2SE | /J2SE/src/designPatterns/proxyP/imook/staticProxy/Car_Time_Proxy.java | GB18030 | 1,093 | 3.671875 | 4 | [] | no_license | package designPatterns.proxyP.imook.staticProxy;
public class Car_Time_Proxy implements Moveable {
@Override
public void move() {
/**
* ʹͨķʽʵֵļ¼ʻʱ
*/
/**
* дĴ̫ά
*
* ԺҪ¼IJ̹ʻʱ
*
* Ҫʻ֮ǰһЩİȫȵһЩ
*/
/**
* ʹü̳еķʽ
*
* ʹþۺϵķʽ
*
*/
long starttime = System.currentTimeMillis();
System.out.println("ʼʻ...");
// ʵֿ
try {
System.out.println("ʻ...");
// Thread.sleep(new Random().nextInt(1000));
// new Random().nextInt(1000010ڵ)
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
long endtime = System.currentTimeMillis();
System.out.println("ʻ...");
System.out.println("ʻʱ:" + (endtime - starttime) + "!");
}
}
| true |
1ca2fe94abfa736b9043aa775f190d3ffc448b59 | Java | thenghiapham/w2vcomp | /w2vcomp/src/utils/DiagonalCompositionHeatmap.java | UTF-8 | 1,665 | 2.5 | 2 | [] | no_license | package utils;
import javax.swing.JFrame;
import org.ejml.simple.SimpleMatrix;
import common.HeatMapPanel;
import demo.TestConstants;
//import space.DiagonalCompositionSemanticSpace;
import space.NewDiagonalCompositionSemanticSpace;
public class DiagonalCompositionHeatmap {
public static void main(String[] args) {
// String compSpaceFile = "/home/thenghiapham/work/project/mikolov/output/wbnc.cmp";
String compSpaceFile = TestConstants.S_COMPOSITION_FILE;
// String construction = "VP VB NP";
// String construction = "NP NN NN";
String construction = "NP NN NN";
// String construction = "NP JJ NN";
// String construction = "S NP VP";
NewDiagonalCompositionSemanticSpace space = NewDiagonalCompositionSemanticSpace.loadCompositionSpace(compSpaceFile, true);
SimpleMatrix vector = space.getConstructionMatrix(construction);
SimpleMatrix diaMatrix = SimpleMatrix.diag(vector.getMatrix().data);
System.out.println(diaMatrix.extractMatrix(0, 10, 0, 10));
int numCols = diaMatrix.numCols();
int aThirdCols = numCols / 3;
System.out.println(diaMatrix.extractMatrix(aThirdCols, aThirdCols + 10, aThirdCols, aThirdCols + 10));
System.out.println(diaMatrix.extractMatrix(aThirdCols * 2, aThirdCols * 2 + 10, aThirdCols * 2, aThirdCols * 2 + 10));
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new HeatMapPanel(diaMatrix));
f.setSize(diaMatrix.numCols() * 12, diaMatrix.numRows() * 12);
f.setLocation(200,200);
f.setVisible(true);
}
}
| true |
f69033d6936b48b50989e99c60e7e825ab0d96d9 | Java | Vukky97/Algorithms | /src/co/btksoftware/fibonacci/Fibonacci.java | UTF-8 | 529 | 3.859375 | 4 | [] | no_license | package co.btksoftware.fibonacci;
import java.util.Scanner;
public class Fibonacci {
public static void main(String[] args) {
System.out.print("Length of Fibonacci sequence: ");
Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();
int fib = Fibo(number);
System.out.println("Result: " + fib);
}
private static int Fibo(int n) {
if (n > 1) {
return Fibo(n - 1) + Fibo(n - 2);
} else {
return n;
}
}
}
| true |
a718eebd8b6e141f1dccdad53cc5c581692f34d4 | Java | abertero/wisc3-project | /common-wisc/src/main/java/cl/wisc3/enums/EvaluationType.java | UTF-8 | 315 | 2.578125 | 3 | [] | no_license | package cl.wisc3.enums;
public enum EvaluationType {
EXECUTION, VERBAL;
public static EvaluationType getByName(String typeStr) {
for (EvaluationType type : values()) {
if (type.name().equals(typeStr)) {
return type;
}
}
return null;
}
}
| true |
3dd3da15fa5c826a21983f1e844aa20c9c127fa6 | Java | shendejun/springcloud | /51CTO/04/microservice-simple-provider-user/src/main/java/com/itmuch/cloud/microservicesimpleprovideruser/repository/UserRepository.java | UTF-8 | 332 | 1.625 | 2 | [] | no_license | package com.itmuch.cloud.microservicesimpleprovideruser.repository;
import com.itmuch.cloud.microservicesimpleprovideruser.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User,Long> {
}
| true |
66c4326359b50f9a5c80c56aaeecdb87d7866557 | Java | persesvilhena/gev | /src/br/com/projeto/dao/FuncionarioDao.java | UTF-8 | 5,840 | 2.328125 | 2 | [] | no_license | package br.com.projeto.dao;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import br.com.projeto.bean.CidadeBean;
import br.com.projeto.bean.FuncionarioBean;
import br.com.projeto.conexao.Conexao;
public class FuncionarioDao {
List<FuncionarioBean> listafuncionario = null;
public FuncionarioBean consultarFuncionarioTodos(String nome) throws SQLException,
ClassNotFoundException {
FuncionarioBean funcionarioBean = null;
String sql = "SELECT * FROM funcionarios";
PreparedStatement comandoSql = Conexao.getInstance().prepareStatement(sql);
comandoSql.setString(1, "%" + nome + "%");
ResultSet rs = comandoSql.executeQuery();
if (rs.next()) {
funcionarioBean = new FuncionarioBean();
funcionarioBean.setCodigo(rs.getInt("CodCli"));
funcionarioBean.setNome(rs.getString("NomCli"));
funcionarioBean.setEndereco(rs.getString("EndCli"));
funcionarioBean.setNumero(rs.getString("NumCli"));
funcionarioBean.setBairro(rs.getString("BaiCli"));
funcionarioBean.setCep(rs.getString("CepCli"));
CidadeBean cidade = new CidadeBean();
cidade.setCodCid(rs.getInt("CodCid"));
cidade.setNomCid(rs.getString("NomCid"));
cidade.setUfCid(rs.getString("UfCid"));
funcionarioBean.setEstado(rs.getString("EstCli"));
funcionarioBean.setTelefone(rs.getString("TelCli"));
funcionarioBean.setEmail(rs.getString("EmaCli"));
funcionarioBean.setCpf(rs.getString("CpfCli"));
funcionarioBean.setRg(rs.getString("RgCli"));
Date dataNasc = new java.util.Date(rs.getDate("DatUsu").getTime());
funcionarioBean.setNascimento(dataNasc);
funcionarioBean.setCidade(cidade);
}
return funcionarioBean;
}
public List<FuncionarioBean> consultarFuncionario(String nome) throws SQLException,ClassNotFoundException {
String sql = "SELECT * FROM funcionarios INNER JOIN cidade ON funcionarios.CidFun = cidade.CodCid WHERE NomFun LIKE ?";
PreparedStatement comandoSql = Conexao.getInstance().prepareStatement(sql);
comandoSql.setString(1, "%" + nome + "%");
ResultSet rs = comandoSql.executeQuery();
listafuncionario = new ArrayList<FuncionarioBean>();
while (rs.next()) {
FuncionarioBean funcionario = new FuncionarioBean();;
funcionario.setCodigo(rs.getInt("CodFun"));
funcionario.setNome(rs.getString("NomFun"));
funcionario.setEndereco(rs.getString("EndFun"));
funcionario.setNumero(rs.getString("NumFun"));
funcionario.setBairro(rs.getString("BaiFun"));
funcionario.setCep(rs.getString("CepFun"));
CidadeBean cidade = new CidadeBean();
cidade.setCodCid(rs.getInt("CodCid"));
cidade.setNomCid(rs.getString("NomCid"));
cidade.setUfCid(rs.getString("UfCid"));
funcionario.setEstado(rs.getString("EstFun"));
funcionario.setTelefone(rs.getString("TelFun"));
funcionario.setEmail(rs.getString("EmaFun"));
funcionario.setCpf(rs.getString("CpfFun"));
funcionario.setRg(rs.getString("RgFun"));
Date dataNasc = new java.util.Date(rs.getDate("NasFun").getTime());
funcionario.setNascimento(dataNasc);
funcionario.setCidade(cidade);
listafuncionario.add(funcionario);
}
return listafuncionario;
}
public void cadastrarFuncionario(FuncionarioBean funcionario) throws SQLException, ClassNotFoundException {
String sql = "INSERT INTO funcionarios (NomFun, EndFun, NumFun, BaiFun, CepFun, CidFun, EstFun, TelFun, EmaFun, CpfFun, RgFun, NasFun) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement comandoSql = Conexao.getInstance().prepareStatement(sql);
comandoSql.setString(1, funcionario.getNome());
comandoSql.setString(2, funcionario.getEndereco());
comandoSql.setString(3, funcionario.getNumero());
comandoSql.setString(4, funcionario.getBairro());
comandoSql.setString(5, funcionario.getCep());
comandoSql.setInt(6, funcionario.getCidade().getCodCid());
comandoSql.setString(7, funcionario.getEstado());
comandoSql.setString(8, funcionario.getTelefone());
comandoSql.setString(9, funcionario.getEmail());
comandoSql.setString(10, funcionario.getCpf());
comandoSql.setString(11, funcionario.getRg());
comandoSql.setDate(12, new java.sql.Date(funcionario.getNascimento().getTime()));
comandoSql.execute();
Conexao.getInstance().commit();
}
public void alterarFuncionario(FuncionarioBean funcionario) throws SQLException, ClassNotFoundException {
String sql = "UPDATE funcionarios SET NomFun = ?, EndFun = ?, NumFun = ?, BaiFun = ?, CepFun = ?, CidFun = ?,EstFun = ?, TelFun = ?, EmaFun = ?, CpfFun = ?, RgFun = ?, NasFun = ? WHERE CodFun = ?";
PreparedStatement comandoSql = Conexao.getInstance().prepareStatement(sql);
comandoSql.setString(1, funcionario.getNome());
comandoSql.setString(2, funcionario.getEndereco());
comandoSql.setString(3, funcionario.getNumero());
comandoSql.setString(4, funcionario.getBairro());
comandoSql.setString(5, funcionario.getCep());
comandoSql.setInt(6, funcionario.getCidade().getCodCid());
comandoSql.setString(7, funcionario.getEstado());
comandoSql.setString(8, funcionario.getTelefone());
comandoSql.setString(9, funcionario.getEmail());
comandoSql.setString(10, funcionario.getCpf());
comandoSql.setString(11, funcionario.getRg());
comandoSql.setDate(12, new java.sql.Date(funcionario.getNascimento().getTime()));
comandoSql.setInt(13, funcionario.getCodigo());
comandoSql.execute();
Conexao.getInstance().commit();
}
public void excluirFuncionario(int codigo) throws SQLException, ClassNotFoundException {
String sql = "DELETE FROM funcionarios WHERE CodFun = ?";
PreparedStatement comandoSql = Conexao.getInstance().prepareStatement(sql);
comandoSql.setInt(1, codigo);
comandoSql.execute();
Conexao.getInstance().commit();
}
} | true |