repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
wavefancy/Exome-Java | BIDMC/src/shortestPath/edu/princeton/cs/algs4/Edge.java | 4875 | /******************************************************************************
* Compilation: javac Edge.java
* Execution: java Edge
* Dependencies: StdOut.java
*
* Immutable weighted edge.
*
******************************************************************************/
package shortestPath.edu.princeton.cs.algs4;
/**
* The {@code Edge} class represents a weighted edge in an
* {@link EdgeWeightedGraph}. Each edge consists of two integers
* (naming the two vertices) and a real-value weight. The data type
* provides methods for accessing the two endpoints of the edge and
* the weight. The natural order for this data type is by
* ascending order of weight.
* <p>
* For additional documentation, see <a href="http://algs4.cs.princeton.edu/43mst">Section 4.3</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class Edge implements Comparable<Edge> {
private final int v;
private final int w;
private final double weight;
/**
* Initializes an edge between vertices {@code v} and {@code w} of
* the given {@code weight}.
*
* @param v one vertex
* @param w the other vertex
* @param weight the weight of this edge
* @throws IllegalArgumentException if either {@code v} or {@code w}
* is a negative integer
* @throws IllegalArgumentException if {@code weight} is {@code NaN}
*/
public Edge(int v, int w, double weight) {
if (v < 0) throw new IllegalArgumentException("vertex index must be a nonnegative integer");
if (w < 0) throw new IllegalArgumentException("vertex index must be a nonnegative integer");
if (Double.isNaN(weight)) throw new IllegalArgumentException("Weight is NaN");
this.v = v;
this.w = w;
this.weight = weight;
}
/**
* Returns the weight of this edge.
*
* @return the weight of this edge
*/
public double weight() {
return weight;
}
/**
* Returns either endpoint of this edge.
*
* @return either endpoint of this edge
*/
public int either() {
return v;
}
/**
* Returns the endpoint of this edge that is different from the given vertex.
*
* @param vertex one endpoint of this edge
* @return the other endpoint of this edge
* @throws IllegalArgumentException if the vertex is not one of the
* endpoints of this edge
*/
public int other(int vertex) {
if (vertex == v) return w;
else if (vertex == w) return v;
else throw new IllegalArgumentException("Illegal endpoint");
}
/**
* Compares two edges by weight.
* Note that {@code compareTo()} is not consistent with {@code equals()},
* which uses the reference equality implementation inherited from {@code Object}.
*
* @param that the other edge
* @return a negative integer, zero, or positive integer depending on whether
* the weight of this is less than, equal to, or greater than the
* argument edge
*/
@Override
public int compareTo(Edge that) {
return Double.compare(this.weight, that.weight);
}
/**
* Returns a string representation of this edge.
*
* @return a string representation of this edge
*/
public String toString() {
return String.format("%d-%d %.5f", v, w, weight);
}
/**
* Unit tests the {@code Edge} data type.
*
* @param args the command-line arguments
*/
// public static void main(String[] args) {
// Edge e = new Edge(12, 34, 5.67);
// StdOut.println(e);
// }
}
/******************************************************************************
* Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/
| mit |
SKToukir/celeb | app/src/main/java/com/vumobile/celeb/ui/EditPostActivity.java | 17739 | package com.vumobile.celeb.ui;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.squareup.picasso.Picasso;
import com.vumobile.Config.Api;
import com.vumobile.celeb.R;
import com.vumobile.celeb.Utils.AndroidMultipartEntity;
import com.vumobile.celeb.Utils.ScalingUtilities;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class EditPostActivity extends AppCompatActivity implements View.OnClickListener {
private RelativeLayout imgVdoLayout;
private Toolbar toolbar;
private Button btnPost, btnClose, btnChoose;
private EditText etEditPost;
private ImageView imgPost;
private VideoView vdoPost;
private String postId, post, isImage, postUrls;
public static final int IMAGE_PICKER_SELECT = 1;
private Uri uri;
private String filePath = null;
private MediaController mediaControls;
private ProgressBar progressBar;
private TextView txtPercentage;
long totalSize = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_post);
toolbar = (Toolbar) findViewById(R.id.toolbar_edit_posts);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed(); // Implemented by activity
}
});
postId = getIntent().getStringExtra("id");
post = getIntent().getStringExtra("post");
postUrls = getIntent().getStringExtra("post_urls");
isImage = getIntent().getStringExtra("isImage");
Log.d("extras", postId + " " + post + " " + postUrls + " " + isImage);
initUI();
}
private void initUI() {
imgVdoLayout = (RelativeLayout) findViewById(R.id.imgVdoLayout);
txtPercentage = (TextView) findViewById(R.id.txtPercentage);
progressBar = (ProgressBar) findViewById(R.id.prog);
btnPost = (Button) findViewById(R.id.btnPost);
btnClose = (Button) findViewById(R.id.btn_close_edit);
etEditPost = (EditText) findViewById(R.id.etEditPost);
imgPost = (ImageView) findViewById(R.id.imgEdit);
vdoPost = (VideoView) findViewById(R.id.vdoViewEdit);
btnChoose = (Button) findViewById(R.id.btnChoose);
btnPost.setOnClickListener(this);
btnClose.setOnClickListener(this);
etEditPost.setOnClickListener(this);
imgPost.setOnClickListener(this);
vdoPost.setOnClickListener(this);
btnChoose.setOnClickListener(this);
etEditPost.setText(post);
if (!postUrls.equals("")){
imgVdoLayout.setVisibility(View.VISIBLE);
btnChoose.setVisibility(View.VISIBLE);
}
if (isImage.equals("1")) {
vdoPost.setVisibility(View.GONE);
imgPost.setVisibility(View.VISIBLE);
setImage(postUrls);
} else if (isImage.equals("2")) {
vdoPost.setVisibility(View.VISIBLE);
imgPost.setVisibility(View.GONE);
setVideo(postUrls);
}
}
private void setVideo(String postUrls) {
Uri uri = Uri.parse(postUrls); //Declare your url here.
vdoPost.setVideoURI(uri);
vdoPost.start();
vdoPost.seekTo(3000);
vdoPost.pause();
}
private void setImage(String postUrls) {
try {
Picasso.with(getApplicationContext()).load(postUrls).into(imgPost);
}catch (IllegalArgumentException e){
e.printStackTrace();
}
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnPost:
progressBar.setVisibility(View.VISIBLE);
btnClose.setVisibility(View.GONE);
btnChoose.setVisibility(View.GONE);
btnPost.setVisibility(View.GONE);
String comment = etEditPost.getText().toString();
if (filePath == null || filePath.equals(null) || filePath.equals("")) {
String change = "0";
// if there is no change on image or video
postEdit(Api.URL_EDIT_POST, postId, comment, isImage, postUrls, change);
//new UploadFileToServer().execute(postId,comment,isimage,postUrls,change);
} else {
String change = "1";
new UploadFileToServer().execute(postId, comment, isImage, filePath, change);
}
break;
case R.id.btn_close_edit:
imgPost.setImageResource(0);
vdoPost.setVideoURI(null);
imgPost.setVisibility(View.GONE);
vdoPost.setVisibility(View.GONE);
break;
case R.id.etEditPost:
Log.d("filepath", "l" + filePath);
Log.d("filepath", "l" + postUrls);
break;
case R.id.imgEdit:
break;
case R.id.vdoViewEdit:
break;
case R.id.btnChoose:
choose_from_gallery();
break;
}
}
private void postEdit(String editPost, String postId, String comment, String isimage, String postUrls, String urlEditPost) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, editPost,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("FromServer", response.toString());
try {
JSONObject object = new JSONObject(response);
String log = object.getString("result");
showAlert(log);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("FromServer", "" + error.getMessage());
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("Change", urlEditPost);
Log.d("whatthehell",urlEditPost);
params.put("post", comment);
Log.d("whatthehell",comment);
params.put("postId", postId);
Log.d("whatthehell",postId);
params.put("IsImage", isimage);
Log.d("whatthehell",isimage);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void choose_from_gallery() {
Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickIntent.setType("image/* video/*");
startActivityForResult(pickIntent, IMAGE_PICKER_SELECT);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
imgVdoLayout.setVisibility(View.VISIBLE);
if (resultCode == RESULT_OK) {
Uri selectedMediaUri = data.getData();
if (selectedMediaUri.toString().contains("images")) {
postUrls = "null";
//handle image
Toast.makeText(getApplicationContext(), "This is a image", Toast.LENGTH_LONG).show();
uri = data.getData();
filePath = decodeFile(getRealPathFromURI(EditPostActivity.this, uri));
decodeFile(filePath);
imgPost.setImageResource(0);
vdoPost.setVideoURI(null);
imgPost.setVisibility(View.VISIBLE);
vdoPost.setVisibility(View.GONE);
previewMedia("1", filePath);
} else if (selectedMediaUri.toString().contains("video")) {
postUrls = "null";
//handle video
Toast.makeText(getApplicationContext(), "This is a video", Toast.LENGTH_LONG).show();
Uri uri = data.getData();
filePath = getRealPathFromURI(getApplicationContext(), uri);
previewMedia("2", filePath);
}
}
}
private void previewMedia(String isimage, String filePath) {
if (isimage.equals("1")) {
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
imgPost.setImageBitmap(bitmap);
} else {
if (mediaControls == null) {
mediaControls = new MediaController(EditPostActivity.this);
}
imgPost.setVisibility(View.GONE);
vdoPost.setVisibility(View.VISIBLE);
vdoPost.setVideoPath(filePath);
vdoPost.setMediaController(mediaControls);
// start playing
vdoPost.start();
}
}
// this method call for get video file uri
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = {MediaStore.Images.Media.DATA};
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
public String decodeFile(String path) {
String strMyImagePath = null;
Bitmap scaledBitmap = null;
try {
// Part 1: Decode image
Bitmap unscaledBitmap = ScalingUtilities.decodeFile(path, 80, 80, ScalingUtilities.ScalingLogic.FIT);
if (!(unscaledBitmap.getWidth() <= 800 && unscaledBitmap.getHeight() <= 800)) {
// Part 2: Scale image
scaledBitmap = ScalingUtilities.createScaledBitmap(unscaledBitmap, 80, 80, ScalingUtilities.ScalingLogic.FIT);
} else {
unscaledBitmap.recycle();
return path;
}
// Store to tmp file
String extr = Environment.getExternalStorageDirectory().toString();
File mFolder = new File(extr + "/myTmpDir");
if (!mFolder.exists()) {
mFolder.mkdir();
}
String s = "tmp.png";
File f = new File(mFolder.getAbsolutePath(), s);
strMyImagePath = f.getAbsolutePath();
FileOutputStream fos = null;
try {
fos = new FileOutputStream(f);
scaledBitmap.compress(Bitmap.CompressFormat.PNG, 5, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
scaledBitmap.recycle();
} catch (Throwable e) {
}
if (strMyImagePath == null) {
return path;
}
return strMyImagePath;
}
/**
* Uploading the file to server
*/
private class UploadFileToServer extends AsyncTask<String, Integer, String> {
@Override
protected void onPreExecute() {
// setting progress bar to zero
progressBar.setProgress(0);
super.onPreExecute();
}
@Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
progressBar.setVisibility(View.VISIBLE);
txtPercentage.setVisibility(View.VISIBLE);
// updating progress bar value
progressBar.setProgress(progress[0]);
// updating percentage value
txtPercentage.setText(String.valueOf(progress[0]) + "%");
}
@Override
protected String doInBackground(String... params) {
String postId = params[0];
String comment = params[1];
String isImage = params[2];
String filePath = params[3];
String change = params[4];
return uploadFile(postId, comment, isImage, filePath, change);
}
@SuppressWarnings("deprecation")
private String uploadFile(String postId, String comment, String isImage, String filePath, String change) {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Api.URL_EDIT_POST);
try {
AndroidMultipartEntity entity = new AndroidMultipartEntity(
new AndroidMultipartEntity.ProgressListener() {
@Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(filePath);
// Adding file data to http body
Log.d("data", postId + " " + comment + " " + isImage + " " + filePath + " " + change);
entity.addPart("image", new FileBody(sourceFile));
entity.addPart("IsImage", new StringBody(isImage));
entity.addPart("postId", new StringBody(postId));
entity.addPart("Change", new StringBody(change));
entity.addPart("post", new StringBody(comment));
// entity.addPart("Name",new StringBody("my name"));
Log.d("Image", sourceFile.toString());
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
@Override
protected void onPostExecute(String result) {
Log.e("FromServer", "Response from server: " + result);
// showing the server response in an alert dialog
showAlert(result);
super.onPostExecute(result);
}
}
//
// /**
// * Method to show alert dialog
// */
private void showAlert(String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(EditPostActivity.this);
builder.setMessage(message)
.setCancelable(false)
.setPositiveButton("Done", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
| mit |
acl-services/ax-datasource-connector | MainSource/plugins/com.acl.ax.datasource.mapsdk/src/com/acl/ax/datasource/mapsdk/xml/binding/REPEAT.java | 3193 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.0.5-b02-fcs
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2008.06.17 at 03:33:40 PM PDT
//
package com.acl.ax.datasource.mapsdk.xml.binding;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.NormalizedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"filter"
})
@XmlRootElement(name = "REPEAT")
public class REPEAT {
@XmlAttribute(name = "TYPE")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
protected String type;
@XmlAttribute(name = "INTERVAL")
@XmlJavaTypeAdapter(NormalizedStringAdapter.class)
protected String interval;
@XmlElement(name = "FILTER")
protected List<FILTER> filter;
/**
* Gets the value of the type property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTYPE() {
return type;
}
/**
* Sets the value of the type property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTYPE(String value) {
this.type = value;
}
/**
* Gets the value of the interval property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getINTERVAL() {
return interval;
}
/**
* Sets the value of the interval property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setINTERVAL(String value) {
this.interval = value;
}
/**
* Gets the value of the filter property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the filter property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getFILTER().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link FILTER }
*
*
*/
public List<FILTER> getFILTER() {
if (filter == null) {
filter = new ArrayList<FILTER>();
}
return this.filter;
}
}
| mit |
maxml/AutoTimeHelper | previous/ex/drawer/entity/Point.java | 426 | package userEntity;
public class Point {
private double x;
private double y;
public Point(double x, double y) {
super();
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
@Override
public String toString() {
return "Point [x=" + x + ", y=" + y + "]";
}
}
| mit |
ulisesbocchio/jasypt-spring-boot | jasypt-spring-boot/src/main/java/com/ulisesbocchio/jasyptspringboot/encryptor/PooledStringEncryptor.java | 1959 | package com.ulisesbocchio.jasyptspringboot.encryptor;
import org.jasypt.encryption.StringEncryptor;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.IntStream;
public class PooledStringEncryptor implements StringEncryptor {
private final int size;
private final StringEncryptor[] pool;
private final AtomicInteger roundRobin;
public PooledStringEncryptor(int size, Supplier<StringEncryptor> encryptorFactory) {
this.size = size;
this.pool = IntStream.range(0, this.size).boxed().map(v -> {
StringEncryptor encryptor = encryptorFactory.get();
if (encryptor instanceof ThreadSafeStringEncryptor) {
return encryptor;
}
return new ThreadSafeStringEncryptor(encryptor);
}).toArray(StringEncryptor[]::new);
this.roundRobin = new AtomicInteger();
}
private <T> T robin(Function<StringEncryptor, T> producer) {
int position = this.roundRobin.getAndUpdate(value -> (value + 1) % this.size);
return producer.apply(this.pool[position]);
}
@Override
public String encrypt(String message) {
return robin(e -> e.encrypt(message));
}
@Override
public String decrypt(String encryptedMessage) {
return robin(e -> e.decrypt(encryptedMessage));
}
public static class ThreadSafeStringEncryptor implements StringEncryptor {
private final StringEncryptor delegate;
public ThreadSafeStringEncryptor(StringEncryptor delegate) {
this.delegate = delegate;
}
@Override
public synchronized String encrypt(String message) {
return delegate.encrypt(message);
}
@Override
public synchronized String decrypt(String encryptedMessage) {
return delegate.decrypt(encryptedMessage);
}
}
}
| mit |
JairAviles/devopsbuddy | src/main/java/com/devopsbuddy/backend/persistance/repositories/PlanRepository.java | 257 | package com.devopsbuddy.backend.persistance.repositories;
import com.devopsbuddy.backend.persistance.domain.backend.Plan;
import org.springframework.data.repository.CrudRepository;
public interface PlanRepository extends CrudRepository<Plan, Integer> {
}
| mit |
a-r-d/java-1-class-demos | collections-and-generics/week10/MoreListExamples.java | 603 | package week10;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class MoreListExamples {
public static void main(String[] args) {
List<String> strings = new LinkedList<>();
strings.add("I am a string!");
strings.add("another string");
String secondElement = strings.get(1);
System.out.println("2nd elem: " + secondElement);
System.out.println("size of list: " + strings.size());
strings.remove(0);
System.out.println("Size of list: " + strings.size());
System.out.println("1st element: " + strings.get(0));
}
}
| mit |
sunshinezxf/Selling | src/main/java/selling/sunshine/dispatcher/SellingDispatcher.java | 452 | package selling.sunshine.dispatcher;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Created by sunshine on 4/8/16.
*/
public class SellingDispatcher extends DispatcherServlet {
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
super.doDispatch(request, response);
}
}
| mit |
haihaio/AndroidPractice | ShareDialogDemo/app/src/main/java/aaronyi/sharedialogdemo/weibo/WeiboShareConstants.java | 1875 | package aaronyi.sharedialogdemo.weibo;
/**
* Created by yihaimen on 16/12/22.
*/
public class WeiboShareConstants {
/**
* 当前 DEMO 应用的 APP_KEY,第三方应用应该使用自己的 APP_KEY 替换该 APP_KEY
*/
public static final String APP_KEY = "1571931807";
/**
* 当前 DEMO 应用的回调页,第三方应用可以使用自己的回调页。
*
* <p>
* 注:关于授权回调页对移动客户端应用来说对用户是不可见的,所以定义为何种形式都将不影响,
* 但是没有定义将无法使用 SDK 认证登录。
* 建议使用默认回调页:https://api.weibo.com/oauth2/default.html
* </p>
*/
public static final String REDIRECT_URL = "https://api.weibo.com/oauth2/default.html";
/**
* Scope 是 OAuth2.0 授权机制中 authorize 接口的一个参数。通过 Scope,平台将开放更多的微博
* 核心功能给开发者,同时也加强用户隐私保护,提升了用户体验,用户在新 OAuth2.0 授权页中有权利
* 选择赋予应用的功能。
*
* 我们通过新浪微博开放平台-->管理中心-->我的应用-->接口管理处,能看到我们目前已有哪些接口的
* 使用权限,高级权限需要进行申请。
*
* 目前 Scope 支持传入多个 Scope 权限,用逗号分隔。
*
* 有关哪些 OpenAPI 需要权限申请,请查看:http://open.weibo.com/wiki/%E5%BE%AE%E5%8D%9AAPI
* 关于 Scope 概念及注意事项,请查看:http://open.weibo.com/wiki/Scope
*/
public static final String SCOPE =
"email,direct_messages_read,direct_messages_write,"
+ "friendships_groups_read,friendships_groups_write,statuses_to_me_read,"
+ "follow_app_official_microblog," + "invitation_write";
}
| mit |
Trolez/Minesweeper-Ultra-Deluxe | Main.java | 7433 | import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.util.Date;
public class Main extends JFrame implements ComponentListener, ItemListener {
static final long serialVersionUID = 1L;
// Default board values
public int xCells = 30;
public int yCells = 16;
public int mines = 99;
// The dimensions of the board
public double width, height;
// Default values for cell sizes
public static double cellWidth = 30, cellHeight = 30;
// Highscore manager
private ScoreManager scoreManager = new ScoreManager();
private Board board;
private boolean enterFlag = false;
KeyAdapter keyAdapter = new KeyAdapter() {
public void keyPressed(KeyEvent arg0) {
// Not needed
}
public void keyReleased(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_SPACE:
restartGame();
break;
case KeyEvent.VK_ENTER:
if (!enterFlag)
resetGame();
else
enterFlag = false;
break;
case KeyEvent.VK_ESCAPE:
System.exit(0);
case KeyEvent.VK_F:
setExtendedState(JFrame.MAXIMIZED_BOTH);
break;
}
}
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
};
public Main(String[] args) {
// Change the board values if args are set
try {
if (args.length > 0) {
xCells = Integer.parseInt(args[0]);
}
if (args.length > 1) {
yCells = Integer.parseInt(args[1]);
}
if (args.length > 2) {
mines = Integer.parseInt(args[2]);
}
} catch (NumberFormatException e) {
System.out.println("Invalid number format");
}
// Make sure the amount of mines doesn't mess things up
verifyCells();
System.setProperty("awt.useSystemAAFontSettings", "on");
System.setProperty("swing.aatext", "true");
setTitle("Minesweeper Ultra Deluxe (v1.1)");
setDefaultCloseOperation(EXIT_ON_CLOSE);
// Set custom window title
if (args.length > 3) {
String newTitle = "";
for (int i = 3; i < args.length; i++) {
if (i > 3) {
newTitle += " ";
}
newTitle += args[i];
}
setTitle(newTitle);
}
setVisible(true);
setLayout(new BorderLayout());
Menu menu = new Menu(this);
setJMenuBar(menu.menuBar);
try {
// Set cross-platform Java L&F (also called "Metal")
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (UnsupportedLookAndFeelException e) {
// handle exception
} catch (ClassNotFoundException e) {
// handle exception
} catch (InstantiationException e) {
// handle exception
} catch (IllegalAccessException e) {
// handle exception
}
board = new Board(this);
board.setPreferredSize(new Dimension((int) width, (int) height + 75)); // +75 for the gui
setMinimumSize(new Dimension((int) width, (int) height + 75));
board.placeMines();
this.addKeyListener(keyAdapter);
this.add(board, BorderLayout.CENTER);
board.addComponentListener(this);
pack();
this.repaint();
}
public static void main(String[] args) {
new Main(args);
}
public void restartGame() {
verifyCells();
board.resetCounter();
this.remove(board);
board = new Board(this);
Board.dead = false;
Board.won = false;
Board.firstClick = true;
board.setPreferredSize(new Dimension((int) width, (int) height + 75));
setMinimumSize(new Dimension((int) width, (int) height + 75));
board.placeMines();
this.add(board, BorderLayout.CENTER);
board.addComponentListener(this);
pack();
this.repaint();
board.paint(getGraphics());
}
public void resetGame() {
// Resets the game with the mines in the same location
if (Board.firstClick) {
return;
}
Board.dead = false;
Board.won = false;
board.remainingMines = mines;
board.remainingCells = xCells * yCells - mines;
board.resetCounter();
// Reset the state of the cells
for (int i = 0; i < xCells; i++) {
for (int j = 0; j < yCells; j++) {
board.cells[i][j].processed = false;
board.cells[i][j].marked = false;
board.cells[i][j].enqueued = false;
}
}
this.repaint();
}
// Used to save the current screen in a buffered image to be blurred
public BufferedImage getScreenShot(Component component) {
BufferedImage image = new BufferedImage((int) width, (int) height + 75, BufferedImage.TYPE_INT_RGB);
component.paint(image.getGraphics());
return image;
}
public void ShowHighscoreDialog() {
enterFlag = true;
// Disable highscore for custom difficulties
if (Board.difficulty == Difficulty.CUSTOM) {
return;
}
// Only show highscore prompt if the score qualifies for the list
if (Counter.count < scoreManager.GetLowestScore(Board.difficulty)
|| scoreManager.getScores(Board.difficulty).size() < 10) {
Date date = new Date();
String scoreName = (String) JOptionPane.showInputDialog(this, "Please enter your name for the highscore",
"You made the highscore!", JOptionPane.PLAIN_MESSAGE, null, null, System.getProperty("user.name"));
if (scoreName != null && scoreName != "") {
scoreManager.addScore(scoreName, Counter.count, Board.difficulty, date);
}
}
}
public void showCustomWindow() {
new CustomWindow(this, true, this);
}
public void showHighscore() {
new HighscoreTable(this, true);
}
@Override
public void componentHidden(ComponentEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void componentMoved(ComponentEvent arg0) {
// TODO Auto-generated method stub
}
public void componentResized(ComponentEvent e) {
width = e.getComponent().getWidth();
height = e.getComponent().getHeight() - 75;
cellWidth = width / xCells;
cellHeight = height / yCells;
// Redo the gradient for all cells
for (int i = 0; i < xCells; i++) {
for (int j = 0; j < yCells; j++) {
board.cells[i][j].resize();
}
}
// Generate a new game over screen
if (Board.dead || Board.won) {
board.img = null;
board.img = getScreenShot(board);
repaint();
}
board.setPreferredSize(new Dimension((int) width, (int) height + 75));
pack();
}
private void verifyCells() {
if (xCells < 9) {
xCells = 9;
}
if (yCells < 9) {
yCells = 9;
}
if (mines > xCells * yCells - 20) {
mines = xCells * yCells - 20;
}
if (mines < 0) {
mines = 0;
}
width = (int) (xCells * cellWidth);
height = (int) (yCells * cellHeight);
}
@Override
public void componentShown(ComponentEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void itemStateChanged(ItemEvent arg0) {
// TODO Auto-generated method stub
}
}
| mit |
ScifestJoensuu/theater-robot | RobotStories/app/src/main/java/fi/tiedeseura/robotstories/StagePoint.java | 2901 | package fi.tiedeseura.robotstories;
/**
* Created by mikko on 6.8.15.
*/
public class StagePoint {
private Stage stage;
private float screen_x;
private float screen_y;
private float stage_x;
private float stage_y;
public StagePoint(Stage stage) {
this.stage = stage;
this.screen_x = -1;
this.screen_y = -1;
this.stage_x = -1;
this.stage_x = -1;
}
public StagePoint(Stage stage, float screen_x, float screen_y) {
this.stage = stage;
setScreenX(screen_x);
setScreenY(screen_y);
}
public StagePoint(Stage stage, float screen_x, float screen_y, float stage_x, float stage_y) {
this.stage = stage;
this.screen_x = screen_x;
this.screen_y = screen_y;
this.stage_x = stage_x;
this.stage_y = stage_y;
}
public void setStageX(float x) {
this.stage_x = x;
this.screen_x = calculateScreenXFromStageX(x);
}
public void setStageY(float y) {
this.stage_y = y;
this.screen_y = calculateScreenYFromStageY(y);
}
public float getStageX() {
return this.stage_x;
}
public float getStageY() {
return this.stage_y;
}
public void setScreenX(float x) {
this.screen_x = x;
this.stage_x = calculateStageXFromScreenX(x);
}
public void setScreenY(float y) {
this.screen_y = y;
this.stage_y = calculateStageYFromScreenY(y);
}
public float getScreenX() {
return this.screen_x;
}
public float getScreenY() {
return this.screen_y;
}
public int calculateStageXFromScreenX(float x) {
int stageWidth = stage.getWidth();
int stageWidthPx = stage.getStageWidthPx();
float m = (float)stageWidthPx / (float)stageWidth;
return (int)((x - stage.getTopLeft().getScreenX()) / m);
}
public int calculateStageYFromScreenY(float y) {
int stageHeight = stage.getHeight();
int stageHeightPx = stage.getStageHeightPx();
float m = (float)stageHeightPx / (float)stageHeight;
return (int)((y - stage.getTopLeft().getScreenX()) / m);
}
public float calculateScreenXFromStageX(float x) {
int stageWidth = stage.getWidth();
int stageWidthPx = stage.getStageWidthPx();
float m = (float)stageWidthPx / (float)stageWidth;
return stage.getTopLeft().getScreenX() + x * m;
}
public float calculateScreenYFromStageY(float y) {
int stageHeight = stage.getHeight();
int stageHeightPx = stage.getStageHeightPx();
float m = (float)stageHeightPx / (float)stageHeight;
return stage.getTopLeft().getScreenY() + y * m;
}
public Stage getStage() {
return this.stage;
}
public String toString() {
return this.getStageX() + ", " + this.getStageY();
}
}
| mit |
kmchugh/Goliath.UI | src/Goliath/Interfaces/UI/Controls/Implementations/IControlImpl.java | 5681 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Goliath.Interfaces.UI.Controls.Implementations;
import Goliath.Collections.List;
import Goliath.Constants.EventType;
import Goliath.Graphics.Dimension;
import Goliath.Graphics.Point;
import Goliath.Interfaces.UI.Controls.IContainer;
import Goliath.Interfaces.UI.Controls.IControl;
import Goliath.UI.Controls.ControlImplementationType;
import java.awt.Color;
/**
*
* @author kmchugh
*/
public interface IControlImpl
{
/**
* Gets the Goliath.UI.Control class that this Implementation is to be used for
* @return the class that is supported by this implementation
*/
Class getSupportedClass();
/**
* Creates the implemented control and sets the base control to this control for communication
* between the logic and the implementation
* @param toControlBase the base control
* @return the newly created implementation of the control
*/
IImplementedControl createControl(IControl toControlBase);
/**
* Gets the render types that this control supports
* @return a list of types that this implementation knows how to handle
*/
List<ControlImplementationType> getSupportedTypes();
/**
* Renders the compent as required.
* @param toRenderCanvas is the canvas to render to, this could be a string, a graphics object, or a file, depending
* on the specific implementation. It is up to the implementation to know what this object is
* @param toControl the control to render
*/
void renderComponent(java.lang.Object toRenderCanvas, IImplementedControl toControl);
void setVisible(boolean tlVisible, IImplementedControl toControl);
boolean setSize(Dimension toSize, IImplementedControl toControl);
void setSelectable(boolean tlSelectable, IImplementedControl toControl);
void setName(String tcName, IImplementedControl toControl);
void setMinSize(Dimension toSize, IImplementedControl toControl);
void setMaxSize(Dimension toSize, IImplementedControl toControl);
void setLocation(Point toLocation, IImplementedControl toControl);
void setEnabled(boolean tlEnabled, IImplementedControl toControl);
boolean isVisible(IImplementedControl toControl);
void setFocus(IImplementedControl toControl);
/**
* Forces rendering of the control after the specified delay. The re render will occur at
* toPoint and will redraw the area within toDimension
* @param toControl the control to re paint
* @param tnDelayMillis the delay before the repaint
* @param toPoint the point to start the repaint at
* @param toDimension the area of the repaint
*/
void forceRender(IImplementedControl toControl, long tnDelayMillis, Point toPoint, Dimension toDimension);
void setFontSize(float tnSize, IImplementedControl toControl);
/**
* Checks if this controls is actually showing on the screen
* @return true if the control is on screen
*/
boolean isShowing(IImplementedControl toControl);
boolean isSelectable(IImplementedControl toControl);
boolean isEnabled(IImplementedControl toControl);
Dimension getSize(IImplementedControl toControl);
Dimension getPreferredSize(IImplementedControl toControl);
String getName(IImplementedControl toControl);
String getTooltip(IImplementedControl toControl);
void setTooltip(String tcTooltip, IImplementedControl toControl);
Dimension getMinSize(IImplementedControl toControl);
Dimension getMaxSize(IImplementedControl toControl);
Point getLocation(IImplementedControl toControl);
void addEventListener(EventType toEvent, IImplementedControl toControl);
void invalidate(IImplementedControl toControl);
void update(IImplementedControl toControl);
boolean isDisplayable(IImplementedControl toControl);
void setEditable(boolean tlVisible, IImplementedControl toControl);
boolean isEditable(IImplementedControl toControl);
IContainer getParent(IImplementedControl toControl);
void setBorderSize(float tnTop, float tnRight, float tnBottom, float tnLeft, IImplementedControl toControl);
void setColour(Color toColour, IImplementedControl toControl);
Color getColour(IImplementedControl toControl);
void setOpacity(float tnOpacity, IImplementedControl toControl);
float getOpacity(IImplementedControl toControl);
/**
* Sets the background image for this control
* @param toBackground the new background image for the control
*/
void setBackground(Goliath.Graphics.Image toBackground, IImplementedControl toControl);
/**
* Sets the background image for this control
* @param toBackground the new background colour for the control
*/
void setBackground(Color toBackground, IImplementedControl toControl);
/**
* Gets the background image for this control
* @return the background image, this could be null
*/
Goliath.Graphics.Image getBackgroundImage(IImplementedControl toControl);
/**
* Gets the background colour for this control
* @return the background colour, this could be null
*/
Color getBackgroundColour(IImplementedControl toControl);
/**
* Sets if the controls background is opaque or transparent
* @param tlOpaque true if this should be opaque
*/
void setOpaque(boolean tlOpaque, IImplementedControl toControl);
/**
* Checks if the controls background is opaque or transparent
* @return true if opaque
*/
boolean isOpaque(IImplementedControl toControl);
}
| mit |
vego1mar/JDP | src/main/java/pl/designpatterns/behavioral/visitor/Wing.java | 344 | package pl.designpatterns.behavioral.visitor;
public class Wing implements Elemental {
private String identity;
public Wing() {
identity = this.toString();
}
@Override
public void accept(Visitable visitor) {
visitor.visit(this);
}
public String getIdentity() {
return identity;
}
}
| mit |
ISKU/Algorithm | BOJ/1100/Main.java | 632 | /*
* Author: Kim Min-Ho (ISKU)
* Date: 2016.08.01
* email: minho1a@hanmail.net
*
* https://github.com/ISKU/Algorithm
* https://www.acmicpc.net/problem/1100
*/
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int numberOfChessPiece = 0;
for (int line = 0; line < 8; line++) {
String onTheLine = input.next();
int location = (line % 2 == 0) ? 0 : 1;
while (location < 8) {
if (onTheLine.charAt(location) == 'F')
numberOfChessPiece++;
location = location + 2;
}
}
System.out.println(numberOfChessPiece);
}
} | mit |
dvsa/mot | mot-selenium/src/test/java/uk/gov/dvsa/data/SiteData.java | 1380 | package uk.gov.dvsa.data;
import com.google.common.base.Optional;
import uk.gov.dvsa.domain.model.Site;
import uk.gov.dvsa.domain.model.mot.MotTest;
import uk.gov.dvsa.domain.service.SiteService;
import org.joda.time.DateTime;
import uk.gov.dvsa.domain.service.StatisticsService;
import java.io.IOException;
public class SiteData extends SiteService{
private StatisticsService statisticsService = new StatisticsService();
private AeData aeData = new AeData();
public SiteData() {}
public Site createNewSite(int aeId, String name) throws IOException {
return createSite(Optional.of(aeId), name);
}
public Site createSite() throws IOException {
return createSite(Optional.of(aeData.createAeWithDefaultValues().getId()), "default");
}
public Site createSite(String name) throws IOException {
return createSite(Optional.of(aeData.createAeWithDefaultValues().getId()), name);
}
public Site createSiteWithoutAe(String name) throws IOException {
return createSite(Optional.<Integer>absent(), name);
}
public Site createSiteWithStartSiteOrgLinkDate(int aeId, String name, DateTime startDate) throws IOException {
return createSiteWithStartSiteOrgLinkDate(Optional.of(aeId), name, startDate);
}
public void clearAllCachedStatistics(){
statisticsService.clearCache();
}
}
| mit |
Web-of-Building-Data/Ifc2Rdf | software/drumbeat-ifc2rdf-1.4.0/net.linkedbuildingdata.common/src/net/linkedbuildingdata/common/config/ComplexProcessorConfiguration.java | 639 | package net.linkedbuildingdata.common.config;
import java.util.ArrayList;
import java.util.List;
public class ComplexProcessorConfiguration extends ConfigurationItem {
private List<ProcessorConfiguration> processorConfigurations;
public ComplexProcessorConfiguration() {
processorConfigurations = new ArrayList<>();
}
public List<ProcessorConfiguration> getProcessorConfigurations() {
return processorConfigurations;
}
public void add(ProcessorConfiguration configuration) {
processorConfigurations.add(configuration);
}
public int size() {
return processorConfigurations.size();
}
}
| mit |
reasm/reasm-m68k | src/main/java/org/reasm/m68k/assembly/internal/EquSetDirective.java | 1597 | package org.reasm.m68k.assembly.internal;
import javax.annotation.Nonnull;
import javax.annotation.concurrent.Immutable;
import org.reasm.SymbolContext;
import org.reasm.SymbolType;
import org.reasm.messages.DirectiveRequiresLabelErrorMessage;
/**
* The <code>EQU</code>, <code>SET</code> and <code>=</code> directives.
*
* @author Francis Gagné
*/
@Immutable
class EquSetDirective extends Mnemonic {
@Nonnull
static final EquSetDirective EQU = new EquSetDirective(Mnemonics.EQU, SymbolType.CONSTANT);
@Nonnull
static final EquSetDirective SET = new EquSetDirective(Mnemonics.SET, SymbolType.VARIABLE);
@Nonnull
static final EquSetDirective EQUALS = new EquSetDirective(Mnemonics.EQUALS, SymbolType.VARIABLE);
@Nonnull
private final String directiveName;
@Nonnull
private final SymbolType symbolType;
private EquSetDirective(@Nonnull String directiveName, @Nonnull SymbolType symbolType) {
this.directiveName = directiveName;
this.symbolType = symbolType;
}
@Override
void assemble(M68KAssemblyContext context) {
context.sizeNotAllowed();
if (context.numberOfLabels == 0) {
context.addMessage(new DirectiveRequiresLabelErrorMessage(this.directiveName));
} else {
if (context.requireNumberOfOperands(1)) {
context.defineSymbols(SymbolContext.VALUE, this.symbolType, evaluateExpressionOperand(context, 0));
}
}
}
@Override
void defineLabels(M68KAssemblyContext context) {
// Don't define any labels.
}
}
| mit |
Lugribossk/dropwizard-experiment | common/common-server/src/main/java/bo/gotthardt/model/EmailVerification.java | 1256 | package bo.gotthardt.model;
import com.avaje.ebean.annotation.EnumValue;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.UUID;
/**
* @author Bo Gotthardt
*/
@Entity
@Getter
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class EmailVerification {
@Id
private String token;
@Setter
private LocalDateTime expirationDate;
private Type type;
@ManyToOne
@JsonIgnore
private User user;
public EmailVerification(User user, Duration duration, Type type) {
this.token = UUID.randomUUID().toString();
this.expirationDate = LocalDateTime.now().plus(duration);
this.user = user;
this.type = type;
}
@JsonIgnore
public boolean isValid() {
return expirationDate.isAfter(LocalDateTime.now());
}
public String getUrl() {
return "http://localhost:8080/#verify/" + this.token;
}
public static enum Type {
@EnumValue("P")
PASSWORD_RESET
}
}
| mit |
motokito/jabref | src/main/java/net/sf/jabref/gui/maintable/MainTable.java | 28443 | /* Copyright (C) 2003-2015 JabRef contributors.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package net.sf.jabref.gui.maintable;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JViewport;
import javax.swing.TransferHandler;
import javax.swing.plaf.TableUI;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumnModel;
import net.sf.jabref.Globals;
import net.sf.jabref.gui.BasePanel;
import net.sf.jabref.gui.EntryMarker;
import net.sf.jabref.gui.GUIGlobals;
import net.sf.jabref.gui.JabRefFrame;
import net.sf.jabref.gui.groups.EntryTableTransferHandler;
import net.sf.jabref.gui.groups.GroupMatcher;
import net.sf.jabref.gui.renderer.CompleteRenderer;
import net.sf.jabref.gui.renderer.GeneralRenderer;
import net.sf.jabref.gui.renderer.IncompleteRenderer;
import net.sf.jabref.gui.search.matchers.SearchMatcher;
import net.sf.jabref.gui.util.comparator.FirstColumnComparator;
import net.sf.jabref.gui.util.comparator.IconComparator;
import net.sf.jabref.gui.util.comparator.RankingFieldComparator;
import net.sf.jabref.logic.TypedBibEntry;
import net.sf.jabref.logic.bibtex.comparator.FieldComparator;
import net.sf.jabref.model.EntryTypes;
import net.sf.jabref.model.entry.BibEntry;
import net.sf.jabref.model.entry.BibtexSingleField;
import net.sf.jabref.model.entry.EntryType;
import net.sf.jabref.model.entry.FieldName;
import net.sf.jabref.model.entry.SpecialFields;
import net.sf.jabref.preferences.JabRefPreferences;
import ca.odell.glazedlists.EventList;
import ca.odell.glazedlists.SortedList;
import ca.odell.glazedlists.event.ListEventListener;
import ca.odell.glazedlists.matchers.Matcher;
import ca.odell.glazedlists.swing.DefaultEventSelectionModel;
import ca.odell.glazedlists.swing.GlazedListsSwing;
import ca.odell.glazedlists.swing.TableComparatorChooser;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* The central table which displays the bibtex entries.
*
* User: alver
* Date: Oct 12, 2005
* Time: 10:29:39 PM
*
*/
public class MainTable extends JTable {
private static final Log LOGGER = LogFactory.getLog(MainTable.class);
private final MainTableFormat tableFormat;
private final BasePanel panel;
private final boolean tableColorCodes;
private final DefaultEventSelectionModel<BibEntry> localSelectionModel;
private final TableComparatorChooser<BibEntry> comparatorChooser;
private final JScrollPane pane;
// needed to activate/deactivate the listener
private final PersistenceTableColumnListener tableColumnListener;
private final MainTableDataModel model;
// Enum used to define how a cell should be rendered.
private enum CellRendererMode {
REQUIRED,
OPTIONAL,
OTHER
}
private static GeneralRenderer defRenderer;
private static GeneralRenderer reqRenderer;
private static GeneralRenderer optRenderer;
private static GeneralRenderer grayedOutRenderer;
private static GeneralRenderer veryGrayedOutRenderer;
private static List<GeneralRenderer> markedRenderers;
private static IncompleteRenderer incRenderer;
private static CompleteRenderer compRenderer;
private static CompleteRenderer grayedOutNumberRenderer;
private static CompleteRenderer veryGrayedOutNumberRenderer;
private static List<CompleteRenderer> markedNumberRenderers;
static {
MainTable.updateRenderers();
}
public MainTable(MainTableFormat tableFormat, MainTableDataModel model, JabRefFrame frame,
BasePanel panel) {
super();
this.model = model;
addFocusListener(Globals.getFocusListener());
setAutoResizeMode(Globals.prefs.getInt(JabRefPreferences.AUTO_RESIZE_MODE));
this.tableFormat = tableFormat;
this.panel = panel;
setModel(GlazedListsSwing
.eventTableModelWithThreadProxyList(model.getTableRows(), tableFormat));
tableColorCodes = Globals.prefs.getBoolean(JabRefPreferences.TABLE_COLOR_CODES_ON);
localSelectionModel = (DefaultEventSelectionModel<BibEntry>) GlazedListsSwing
.eventSelectionModelWithThreadProxyList(model.getTableRows());
setSelectionModel(localSelectionModel);
pane = new JScrollPane(this);
pane.setBorder(BorderFactory.createEmptyBorder());
pane.getViewport().setBackground(Globals.prefs.getColor(JabRefPreferences.TABLE_BACKGROUND));
setGridColor(Globals.prefs.getColor(JabRefPreferences.GRID_COLOR));
if (Globals.prefs.getBoolean(JabRefPreferences.TABLE_SHOW_GRID)) {
setShowGrid(true);
} else {
setShowGrid(false);
setIntercellSpacing(new Dimension(0, 0));
}
this.setTableHeader(new PreventDraggingJTableHeader(this, tableFormat));
comparatorChooser = this.createTableComparatorChooser(this, model.getSortedForUserDefinedTableColumnSorting(),
TableComparatorChooser.MULTIPLE_COLUMN_KEYBOARD);
this.tableColumnListener = new PersistenceTableColumnListener(this);
// set table header render AFTER creation of comparatorChooser (this enables sort arrow rendering)
this.getTableHeader().setDefaultRenderer(new MainTableHeaderRenderer(this.getTableHeader().getDefaultRenderer()));
// TODO: Figure out, whether this call is needed.
getSelected();
// enable DnD
setDragEnabled(true);
TransferHandler xfer = new EntryTableTransferHandler(this, frame, panel);
setTransferHandler(xfer);
pane.setTransferHandler(xfer);
setupComparatorChooser();
model.updateMarkingState(Globals.prefs.getBoolean(JabRefPreferences.FLOAT_MARKED_ENTRIES));
setWidths();
addKeyListener(new TableKeyListener());
}
public void addSelectionListener(ListEventListener<BibEntry> listener) {
getSelected().addListEventListener(listener);
}
public JScrollPane getPane() {
return pane;
}
public MainTableDataModel getTableModel() {
return model;
}
@Override
public String getToolTipText(MouseEvent e) {
// Set tooltip text for all columns which are not fully displayed
String toolTipText = null;
Point p = e.getPoint();
int col = columnAtPoint(p);
int row = rowAtPoint(p);
Component comp = prepareRenderer(getCellRenderer(row, col), row, col);
Rectangle bounds = getCellRect(row, col, false);
Dimension d = comp.getPreferredSize();
if ((d != null) && (d.width > bounds.width) && (getValueAt(row, col) != null)) {
toolTipText = getValueAt(row, col).toString();
}
return toolTipText;
}
@Override
public TableCellRenderer getCellRenderer(int row, int column) {
int score = -3;
DefaultTableCellRenderer renderer = MainTable.defRenderer;
CellRendererMode status = getCellStatus(row, column);
if ((model.getSearchState() != MainTableDataModel.DisplayOption.FLOAT)
|| matches(row, SearchMatcher.INSTANCE)) {
score++;
}
if ((model.getGroupingState() != MainTableDataModel.DisplayOption.FLOAT)
|| matches(row, GroupMatcher.INSTANCE)) {
score += 2;
}
// Now, a grayed out renderer is for entries with -1, and
// a very grayed out one for entries with -2
if (score < -1) {
if (column == 0) {
MainTable.veryGrayedOutNumberRenderer.setNumber(row);
renderer = MainTable.veryGrayedOutNumberRenderer;
} else {
renderer = MainTable.veryGrayedOutRenderer;
}
}
else if (score == -1) {
if (column == 0) {
MainTable.grayedOutNumberRenderer.setNumber(row);
renderer = MainTable.grayedOutNumberRenderer;
} else {
renderer = MainTable.grayedOutRenderer;
}
}
else if (column == 0) {
if (isComplete(row)) {
MainTable.compRenderer.setNumber(row);
int marking = isMarked(row);
if (marking > 0) {
marking = Math.min(marking, EntryMarker.MARK_COLOR_LEVELS);
renderer = MainTable.markedNumberRenderers.get(marking - 1);
MainTable.markedNumberRenderers.get(marking - 1).setNumber(row);
} else {
renderer = MainTable.compRenderer;
}
} else {
// Return a renderer with red background if the entry is incomplete.
MainTable.incRenderer.setNumber(row);
renderer = MainTable.incRenderer;
}
renderer.setHorizontalAlignment(JLabel.CENTER);
} else if (tableColorCodes) {
if (status == CellRendererMode.REQUIRED) {
renderer = MainTable.reqRenderer;
} else if (status == CellRendererMode.OPTIONAL) {
renderer = MainTable.optRenderer;
}
}
// For MARKED feature:
int marking = isMarked(row);
if ((column != 0) && (marking > 0)) {
marking = Math.min(marking, EntryMarker.MARK_COLOR_LEVELS);
renderer = MainTable.markedRenderers.get(marking - 1);
}
return renderer;
}
private void setWidths() {
// Setting column widths:
int ncWidth = Globals.prefs.getInt(JabRefPreferences.NUMBER_COL_WIDTH);
List<String> widthsFromPreferences = Globals.prefs.getStringList(JabRefPreferences.COLUMN_WIDTHS);
TableColumnModel cm = getColumnModel();
cm.getColumn(0).setPreferredWidth(ncWidth);
for (int i = 1; i < cm.getColumnCount(); i++) {
MainTableColumn mainTableColumn = tableFormat.getTableColumn(cm.getColumn(i).getModelIndex());
if (SpecialFields.FIELDNAME_RANKING.equals(mainTableColumn.getColumnName())) {
cm.getColumn(i).setPreferredWidth(GUIGlobals.WIDTH_ICON_COL_RANKING);
cm.getColumn(i).setMinWidth(GUIGlobals.WIDTH_ICON_COL_RANKING);
cm.getColumn(i).setMaxWidth(GUIGlobals.WIDTH_ICON_COL_RANKING);
} else if (mainTableColumn.isIconColumn()) {
cm.getColumn(i).setPreferredWidth(GUIGlobals.WIDTH_ICON_COL);
cm.getColumn(i).setMinWidth(GUIGlobals.WIDTH_ICON_COL);
cm.getColumn(i).setMaxWidth(GUIGlobals.WIDTH_ICON_COL);
} else {
List<String> allColumns = Globals.prefs.getStringList(JabRefPreferences.COLUMN_NAMES);
// find index of current mainTableColumn in allColumns
for (int j = 0; j < allColumns.size(); j++) {
if (allColumns.get(j).equalsIgnoreCase(mainTableColumn.getDisplayName())) {
try {
// set preferred width by using found index j in the width array
cm.getColumn(i).setPreferredWidth(Integer.parseInt(widthsFromPreferences.get(j)));
} catch (NumberFormatException e) {
LOGGER.info("Exception while setting column widths. Choosing default.", e);
cm.getColumn(i).setPreferredWidth(BibtexSingleField.DEFAULT_FIELD_LENGTH);
}
break;
}
}
}
}
}
public BibEntry getEntryAt(int row) {
return model.getTableRows().get(row);
}
/**
* @return the return value is never null
*/
public List<BibEntry> getSelectedEntries() {
return new ArrayList<>(getSelected());
}
private List<Boolean> getCurrentSortOrder() {
List<Boolean> order = new ArrayList<>();
List<Integer> sortCols = comparatorChooser.getSortingColumns();
for (Integer i : sortCols) {
order.add(comparatorChooser.isColumnReverse(i));
}
return order;
}
private List<String> getCurrentSortFields() {
List<Integer> sortCols = comparatorChooser.getSortingColumns();
List<String> fields = new ArrayList<>();
for (Integer i : sortCols) {
// TODO check whether this really works
String name = tableFormat.getColumnName(i);
//TODO OLD
// String name = tableFormat.getColumnType(i);
if (name != null) {
fields.add(name.toLowerCase());
}
}
return fields;
}
/**
* This method sets up what Comparators are used for the various table columns.
* The ComparatorChooser enables and disables such Comparators as the user clicks
* columns, but this is where the Comparators are defined. Also, the ComparatorChooser
* is initialized with the sort order defined in Preferences.
*/
private void setupComparatorChooser() {
// First column:
List<Comparator> comparators = comparatorChooser.getComparatorsForColumn(0);
comparators.clear();
comparators.add(new FirstColumnComparator(panel.getBibDatabaseContext()));
for (int i = 1; i < tableFormat.getColumnCount(); i++) {
MainTableColumn tableColumn = tableFormat.getTableColumn(i);
comparators = comparatorChooser.getComparatorsForColumn(i);
comparators.clear();
if (SpecialFields.FIELDNAME_RANKING.equals(tableColumn.getColumnName())) {
comparators.add(new RankingFieldComparator());
} else if (tableColumn.isIconColumn()) {
comparators.add(new IconComparator(tableColumn.getBibtexFields()));
} else {
comparators = comparatorChooser.getComparatorsForColumn(i);
comparators.clear();
comparators.add(new FieldComparator(tableFormat.getColumnName(i).toLowerCase()));
}
}
// Set initial sort columns:
// Default sort order:
String[] sortFields = new String[] {
Globals.prefs.get(JabRefPreferences.TABLE_PRIMARY_SORT_FIELD),
Globals.prefs.get(JabRefPreferences.TABLE_SECONDARY_SORT_FIELD),
Globals.prefs.get(JabRefPreferences.TABLE_TERTIARY_SORT_FIELD)
};
boolean[] sortDirections = new boolean[] {
Globals.prefs.getBoolean(JabRefPreferences.TABLE_PRIMARY_SORT_DESCENDING),
Globals.prefs.getBoolean(JabRefPreferences.TABLE_SECONDARY_SORT_DESCENDING),
Globals.prefs.getBoolean(JabRefPreferences.TABLE_TERTIARY_SORT_DESCENDING)
}; // descending
model.getSortedForUserDefinedTableColumnSorting().getReadWriteLock().writeLock().lock();
try {
for (int i = 0; i < sortFields.length; i++) {
int index = -1;
// TODO where is this prefix set?
// if (!sortFields[i].startsWith(MainTableFormat.ICON_COLUMN_PREFIX))
if (sortFields[i].startsWith("iconcol:")) {
for (int j = 0; j < tableFormat.getColumnCount(); j++) {
if (sortFields[i].equals(tableFormat.getColumnName(j))) {
index = j;
break;
}
}
} else {
index = tableFormat.getColumnIndex(sortFields[i]);
}
if (index >= 0) {
comparatorChooser.appendComparator(index, 0, sortDirections[i]);
}
}
} finally {
model.getSortedForUserDefinedTableColumnSorting().getReadWriteLock().writeLock().unlock();
}
// Add action listener so we can remember the sort order:
comparatorChooser.addSortActionListener(e -> {
// Get the information about the current sort order:
List<String> fields = getCurrentSortFields();
List<Boolean> order = getCurrentSortOrder();
// Update preferences:
int count = Math.min(fields.size(), order.size());
if (count >= 1) {
Globals.prefs.put(JabRefPreferences.TABLE_PRIMARY_SORT_FIELD, fields.get(0));
Globals.prefs.putBoolean(JabRefPreferences.TABLE_PRIMARY_SORT_DESCENDING, order.get(0));
}
if (count >= 2) {
Globals.prefs.put(JabRefPreferences.TABLE_SECONDARY_SORT_FIELD, fields.get(1));
Globals.prefs.putBoolean(JabRefPreferences.TABLE_SECONDARY_SORT_DESCENDING, order.get(1));
} else {
Globals.prefs.put(JabRefPreferences.TABLE_SECONDARY_SORT_FIELD, "");
Globals.prefs.putBoolean(JabRefPreferences.TABLE_SECONDARY_SORT_DESCENDING, false);
}
if (count >= 3) {
Globals.prefs.put(JabRefPreferences.TABLE_TERTIARY_SORT_FIELD, fields.get(2));
Globals.prefs.putBoolean(JabRefPreferences.TABLE_TERTIARY_SORT_DESCENDING, order.get(2));
} else {
Globals.prefs.put(JabRefPreferences.TABLE_TERTIARY_SORT_FIELD, "");
Globals.prefs.putBoolean(JabRefPreferences.TABLE_TERTIARY_SORT_DESCENDING, false);
}
});
}
private CellRendererMode getCellStatus(int row, int col) {
try {
BibEntry be = getEntryAt(row);
Optional<EntryType> type = EntryTypes.getType(be.getType(), panel.getBibDatabaseContext().getMode());
if(type.isPresent()) {
String columnName = getColumnName(col).toLowerCase();
if (columnName.equals(BibEntry.KEY_FIELD) || type.get().getRequiredFieldsFlat().contains(columnName)) {
return CellRendererMode.REQUIRED;
}
if (type.get().getOptionalFields().contains(columnName)) {
return CellRendererMode.OPTIONAL;
}
}
return CellRendererMode.OTHER;
} catch (NullPointerException ex) {
return CellRendererMode.OTHER;
}
}
/**
* Use with caution! If you modify an entry in the table, the selection changes
*
* You can avoid it with
* <code>.getSelected().getReadWriteLock().writeLock().lock()</code>
* and then <code>.unlock()</code>
*/
public EventList<BibEntry> getSelected() {
return localSelectionModel.getSelected();
}
/**
* Selects the given row
*
* @param row the row to select
*/
public void setSelected(int row) {
localSelectionModel.setSelectionInterval(row, row);
}
public int findEntry(BibEntry entry) {
return model.getTableRows().indexOf(entry);
}
/**
* method to check whether a MainTableColumn at the modelIndex refers to the file field (either as a specific
* file extension filter or not)
*
* @param modelIndex model index of the column to check
* @return true if the column shows the "file" field; false otherwise
*/
public boolean isFileColumn(int modelIndex) {
return (tableFormat.getTableColumn(modelIndex) != null) && tableFormat.getTableColumn(modelIndex)
.getBibtexFields().contains(FieldName.FILE);
}
private boolean matches(int row, Matcher<BibEntry> m) {
return m.matches(getBibEntry(row));
}
private boolean isComplete(int row) {
try {
BibEntry entry = getBibEntry(row);
TypedBibEntry typedEntry = new TypedBibEntry(entry, panel.getBibDatabaseContext());
return typedEntry.hasAllRequiredFields();
} catch (NullPointerException ex) {
return true;
}
}
private int isMarked(int row) {
try {
BibEntry be = getBibEntry(row);
return EntryMarker.isMarked(be);
} catch (NullPointerException ex) {
return 0;
}
}
private BibEntry getBibEntry(int row) {
return model.getTableRows().get(row);
}
public void scrollTo(int y) {
JScrollBar scb = pane.getVerticalScrollBar();
scb.setValue(y * scb.getUnitIncrement(1));
}
public void showFloatSearch() {
this.getTableModel().updateSearchState(MainTableDataModel.DisplayOption.FLOAT);
scrollTo(0);
}
/**
* updateFont
*/
public void updateFont() {
setFont(GUIGlobals.currentFont);
setRowHeight(Globals.prefs.getInt(JabRefPreferences.TABLE_ROW_PADDING) + GUIGlobals.currentFont.getSize());
}
public void ensureVisible(int row) {
JScrollBar vert = pane.getVerticalScrollBar();
int y = row * getRowHeight();
if ((y < vert.getValue()) || ((y > (vert.getValue() + vert.getVisibleAmount()))
&& (model.getSearchState() != MainTableDataModel.DisplayOption.FLOAT))) {
scrollToCenter(row, 1);
}
}
public void scrollToCenter(int rowIndex, int vColIndex) {
if (!(this.getParent() instanceof JViewport)) {
return;
}
JViewport viewport = (JViewport) this.getParent();
// This rectangle is relative to the table where the
// northwest corner of cell (0,0) is always (0,0).
Rectangle rect = this.getCellRect(rowIndex, vColIndex, true);
// The location of the view relative to the table
Rectangle viewRect = viewport.getViewRect();
// Translate the cell location so that it is relative
// to the view, assuming the northwest corner of the
// view is (0,0).
rect.setLocation(rect.x - viewRect.x, rect.y - viewRect.y);
// Calculate location of rect if it were at the center of view
int centerX = (viewRect.width - rect.width) / 2;
int centerY = (viewRect.height - rect.height) / 2;
// Fake the location of the cell so that scrollRectToVisible
// will move the cell to the center
if (rect.x < centerX) {
centerX = -centerX;
}
if (rect.y < centerY) {
centerY = -centerY;
}
rect.translate(centerX, centerY);
// Scroll the area into view.
viewport.scrollRectToVisible(rect);
revalidate();
repaint();
}
public static void updateRenderers() {
MainTable.defRenderer = new GeneralRenderer(Globals.prefs.getColor(JabRefPreferences.TABLE_BACKGROUND),
Globals.prefs.getColor(JabRefPreferences.TABLE_TEXT));
Color sel = MainTable.defRenderer.getTableCellRendererComponent
(new JTable(), "", true, false, 0, 0).getBackground();
MainTable.reqRenderer = new GeneralRenderer(Globals.prefs.getColor(JabRefPreferences.TABLE_REQ_FIELD_BACKGROUND), Globals.prefs.getColor(JabRefPreferences.TABLE_TEXT));
MainTable.optRenderer = new GeneralRenderer(Globals.prefs.getColor(JabRefPreferences.TABLE_OPT_FIELD_BACKGROUND), Globals.prefs.getColor(JabRefPreferences.TABLE_TEXT));
MainTable.incRenderer = new IncompleteRenderer();
MainTable.compRenderer = new CompleteRenderer(Globals.prefs.getColor(JabRefPreferences.TABLE_BACKGROUND));
MainTable.grayedOutNumberRenderer = new CompleteRenderer(Globals.prefs.getColor(JabRefPreferences.GRAYED_OUT_BACKGROUND));
MainTable.veryGrayedOutNumberRenderer = new CompleteRenderer(Globals.prefs.getColor(JabRefPreferences.VERY_GRAYED_OUT_BACKGROUND));
MainTable.grayedOutRenderer = new GeneralRenderer(Globals.prefs.getColor(JabRefPreferences.GRAYED_OUT_BACKGROUND),
Globals.prefs.getColor(JabRefPreferences.GRAYED_OUT_TEXT), MainTable.mixColors(Globals.prefs.getColor(JabRefPreferences.GRAYED_OUT_BACKGROUND),
sel));
MainTable.veryGrayedOutRenderer = new GeneralRenderer(Globals.prefs.getColor(JabRefPreferences.VERY_GRAYED_OUT_BACKGROUND),
Globals.prefs.getColor(JabRefPreferences.VERY_GRAYED_OUT_TEXT), MainTable.mixColors(Globals.prefs.getColor(JabRefPreferences.VERY_GRAYED_OUT_BACKGROUND),
sel));
MainTable.markedRenderers = new ArrayList<>(EntryMarker.MARK_COLOR_LEVELS);
MainTable.markedNumberRenderers = new ArrayList<>(EntryMarker.MARK_COLOR_LEVELS);
for (int i = 0; i < EntryMarker.MARK_COLOR_LEVELS; i++) {
Color c = Globals.prefs.getColor(JabRefPreferences.MARKED_ENTRY_BACKGROUND + i);
MainTable.markedRenderers.add(new GeneralRenderer(c, Globals.prefs.getColor(JabRefPreferences.TABLE_TEXT),
MainTable.mixColors(Globals.prefs.getColor(JabRefPreferences.MARKED_ENTRY_BACKGROUND + i), sel)));
MainTable.markedNumberRenderers.add(new CompleteRenderer(c));
}
}
private static Color mixColors(Color one, Color two) {
return new Color((one.getRed() + two.getRed()) / 2, (one.getGreen() + two.getGreen()) / 2,
(one.getBlue() + two.getBlue()) / 2);
}
private TableComparatorChooser<BibEntry> createTableComparatorChooser(JTable table, SortedList<BibEntry> list,
Object sortingStrategy) {
return TableComparatorChooser.install(table, list, sortingStrategy);
}
/**
* KeyEvent handling of Tab
*/
private class TableKeyListener extends KeyAdapter {
private final Set<Integer> pressed = new HashSet<>();
@Override
public void keyPressed(KeyEvent e) {
pressed.add(e.getExtendedKeyCode());
if (pressed.contains(KeyEvent.VK_TAB)) {
int change = pressed.contains(KeyEvent.VK_SHIFT) ? -1 : 1;
setSelected((getSelectedRow() + change + getRowCount()) % getRowCount());
}
}
@Override
public void keyReleased(KeyEvent e) {
pressed.remove(e.getExtendedKeyCode());
}
}
/**
* Morten Alver: This override is a workaround NullPointerException when
* dragging stuff into the table. I found this in a forum, but have no idea
* why it works.
* @param newUI
*/
@Override
public void setUI(TableUI newUI) {
super.setUI(newUI);
TransferHandler handler = getTransferHandler();
setTransferHandler(null);
setTransferHandler(handler);
}
/**
* Find out which column is set as sort column.
* @param number The position in the sort hierarchy (primary, secondary, etc.)
* @return The sort column number.
*/
public int getSortingColumn(int number) {
List<Integer> l = comparatorChooser.getSortingColumns();
if (l.size() <= number) {
return -1;
} else {
return l.get(number);
}
}
public PersistenceTableColumnListener getTableColumnListener() {
return tableColumnListener;
}
public MainTableColumn getMainTableColumn(int modelIndex) {
return tableFormat.getTableColumn(modelIndex);
}
}
| mit |
simokhov/schemas44 | src/main/java/ru/gov/zakupki/oos/types/_1/ZfcsRepCommonInfo.java | 6008 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2019.07.02 at 03:35:23 PM MSK
//
package ru.gov.zakupki.oos.types._1;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* Общая информация в реестровой записи РЕП
*
* <p>Java class for zfcs_repCommonInfo complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="zfcs_repCommonInfo">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="placerOrgInfo" type="{http://zakupki.gov.ru/oos/types/1}zfcs_repPlacerOrgType"/>
* <element name="contractInfo" type="{http://zakupki.gov.ru/oos/types/1}zfcs_repContractInfo"/>
* <element name="contractTerminationInfo" type="{http://zakupki.gov.ru/oos/types/1}zfcs_repContractTerminationInfo" minOccurs="0"/>
* <element name="contractChangeInfo" type="{http://zakupki.gov.ru/oos/types/1}zfcs_repContractChangeInfo" minOccurs="0"/>
* <element name="supplierInfo" type="{http://zakupki.gov.ru/oos/types/1}zfcs_repSupplierInfo"/>
* <element name="modificationInfo" type="{http://zakupki.gov.ru/oos/types/1}zfcs_repModificationInfo" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "zfcs_repCommonInfo", propOrder = {
"placerOrgInfo",
"contractInfo",
"contractTerminationInfo",
"contractChangeInfo",
"supplierInfo",
"modificationInfo"
})
public class ZfcsRepCommonInfo {
@XmlElement(required = true)
protected ZfcsRepPlacerOrgType placerOrgInfo;
@XmlElement(required = true)
protected ZfcsRepContractInfo contractInfo;
protected ZfcsRepContractTerminationInfo contractTerminationInfo;
protected ZfcsRepContractChangeInfo contractChangeInfo;
@XmlElement(required = true)
protected ZfcsRepSupplierInfo supplierInfo;
protected ZfcsRepModificationInfo modificationInfo;
/**
* Gets the value of the placerOrgInfo property.
*
* @return
* possible object is
* {@link ZfcsRepPlacerOrgType }
*
*/
public ZfcsRepPlacerOrgType getPlacerOrgInfo() {
return placerOrgInfo;
}
/**
* Sets the value of the placerOrgInfo property.
*
* @param value
* allowed object is
* {@link ZfcsRepPlacerOrgType }
*
*/
public void setPlacerOrgInfo(ZfcsRepPlacerOrgType value) {
this.placerOrgInfo = value;
}
/**
* Gets the value of the contractInfo property.
*
* @return
* possible object is
* {@link ZfcsRepContractInfo }
*
*/
public ZfcsRepContractInfo getContractInfo() {
return contractInfo;
}
/**
* Sets the value of the contractInfo property.
*
* @param value
* allowed object is
* {@link ZfcsRepContractInfo }
*
*/
public void setContractInfo(ZfcsRepContractInfo value) {
this.contractInfo = value;
}
/**
* Gets the value of the contractTerminationInfo property.
*
* @return
* possible object is
* {@link ZfcsRepContractTerminationInfo }
*
*/
public ZfcsRepContractTerminationInfo getContractTerminationInfo() {
return contractTerminationInfo;
}
/**
* Sets the value of the contractTerminationInfo property.
*
* @param value
* allowed object is
* {@link ZfcsRepContractTerminationInfo }
*
*/
public void setContractTerminationInfo(ZfcsRepContractTerminationInfo value) {
this.contractTerminationInfo = value;
}
/**
* Gets the value of the contractChangeInfo property.
*
* @return
* possible object is
* {@link ZfcsRepContractChangeInfo }
*
*/
public ZfcsRepContractChangeInfo getContractChangeInfo() {
return contractChangeInfo;
}
/**
* Sets the value of the contractChangeInfo property.
*
* @param value
* allowed object is
* {@link ZfcsRepContractChangeInfo }
*
*/
public void setContractChangeInfo(ZfcsRepContractChangeInfo value) {
this.contractChangeInfo = value;
}
/**
* Gets the value of the supplierInfo property.
*
* @return
* possible object is
* {@link ZfcsRepSupplierInfo }
*
*/
public ZfcsRepSupplierInfo getSupplierInfo() {
return supplierInfo;
}
/**
* Sets the value of the supplierInfo property.
*
* @param value
* allowed object is
* {@link ZfcsRepSupplierInfo }
*
*/
public void setSupplierInfo(ZfcsRepSupplierInfo value) {
this.supplierInfo = value;
}
/**
* Gets the value of the modificationInfo property.
*
* @return
* possible object is
* {@link ZfcsRepModificationInfo }
*
*/
public ZfcsRepModificationInfo getModificationInfo() {
return modificationInfo;
}
/**
* Sets the value of the modificationInfo property.
*
* @param value
* allowed object is
* {@link ZfcsRepModificationInfo }
*
*/
public void setModificationInfo(ZfcsRepModificationInfo value) {
this.modificationInfo = value;
}
}
| mit |
jgaltidor/VarJ | analyzed_libs/guava-libraries-read-only/src/com/google/common/collect/ExplicitOrderedImmutableSortedSet.java | 6780 | /*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
/**
* An immutable sorted set consisting of, and ordered by, a list of provided
* elements.
*
* @author Jared Levy
*/
// TODO(jlevy): Create superclass with code shared by this class and
// RegularImmutableSortedSet.
@SuppressWarnings("serial")
@GwtCompatible(serializable = true, emulated = true)
final class ExplicitOrderedImmutableSortedSet<E>
extends ImmutableSortedSet<E> {
static <E> ImmutableSortedSet<E> create(List<E> list) {
ExplicitOrdering<E> ordering = new ExplicitOrdering<E>(list);
if (ordering.rankMap.isEmpty()) {
return emptySet(ordering);
}
// Not using list.toArray() to avoid iterating across the input list twice.
Object[] elements = ordering.rankMap.keySet().toArray();
return new ExplicitOrderedImmutableSortedSet<E>(elements, ordering);
}
private final Object[] elements;
/**
* The index of the first element that's in the sorted set (inclusive
* index).
*/
private final int fromIndex;
/**
* The index after the last element that's in the sorted set (exclusive
* index).
*/
private final int toIndex;
ExplicitOrderedImmutableSortedSet(Object[] elements,
Comparator<? super E> comparator) {
this(elements, comparator, 0, elements.length);
}
ExplicitOrderedImmutableSortedSet(Object[] elements,
Comparator<? super E> comparator, int fromIndex, int toIndex) {
super(comparator);
this.elements = elements;
this.fromIndex = fromIndex;
this.toIndex = toIndex;
}
// create() generates an ImmutableMap<E, Integer> rankMap.
@SuppressWarnings("unchecked")
private ImmutableMap<E, Integer> rankMap() {
return ((ExplicitOrdering) comparator()).rankMap;
}
// create() ensures that every element is an E.
@SuppressWarnings("unchecked")
@Override public UnmodifiableIterator<E> iterator() {
return (UnmodifiableIterator<E>)
Iterators.forArray(elements, fromIndex, size());
}
@Override public boolean isEmpty() {
return false;
}
public int size() {
return toIndex - fromIndex;
}
@Override public boolean contains(Object o) {
Integer index = rankMap().get(o);
return (index != null && index >= fromIndex && index < toIndex);
}
@Override boolean isPartialView() {
return fromIndex != 0 || toIndex != elements.length;
}
@Override public Object[] toArray() {
Object[] array = new Object[size()];
Platform.unsafeArrayCopy(elements, fromIndex, array, 0, size());
return array;
}
// TODO(jlevy): Move to ObjectArrays (same code in ImmutableList).
@Override public <T> T[] toArray(T[] array) {
int size = size();
if (array.length < size) {
array = ObjectArrays.newArray(array, size);
} else if (array.length > size) {
array[size] = null;
}
Platform.unsafeArrayCopy(elements, fromIndex, array, 0, size);
return array;
}
@Override public int hashCode() {
// TODO(jlevy): Cache hash code?
int hash = 0;
for (int i = fromIndex; i < toIndex; i++) {
hash += elements[i].hashCode();
}
return hash;
}
// The factory methods ensure that every element is an E.
@SuppressWarnings("unchecked")
public E first() {
return (E) elements[fromIndex];
}
// The factory methods ensure that every element is an E.
@SuppressWarnings("unchecked")
public E last() {
return (E) elements[toIndex - 1];
}
@Override ImmutableSortedSet<E> headSetImpl(E toElement) {
return createSubset(fromIndex, findSubsetIndex(toElement));
}
// TODO(jlevy): Override subSet to avoid redundant map lookups.
@Override ImmutableSortedSet<E> subSetImpl(E fromElement, E toElement) {
return createSubset(
findSubsetIndex(fromElement), findSubsetIndex(toElement));
}
@Override ImmutableSortedSet<E> tailSetImpl(E fromElement) {
return createSubset(findSubsetIndex(fromElement), toIndex);
}
private int findSubsetIndex(E element) {
Integer index = rankMap().get(element);
if (index == null) {
// TODO(kevinb): Make Ordering.IncomparableValueException public, use it
throw new ClassCastException();
}
if (index <= fromIndex) {
return fromIndex;
} else if (index >= toIndex) {
return toIndex;
} else {
return index;
}
}
private ImmutableSortedSet<E> createSubset(
int newFromIndex, int newToIndex) {
if (newFromIndex < newToIndex) {
return new ExplicitOrderedImmutableSortedSet<E>(elements, comparator,
newFromIndex, newToIndex);
} else {
return emptySet(comparator);
}
}
@Override int indexOf(Object target) {
Integer index = rankMap().get(target);
return (index != null && index >= fromIndex && index < toIndex)
? index - fromIndex : -1;
}
/*
* TODO(jlevy): Modify ImmutableSortedAsList.subList() so it creates a list
* based on an ExplicitOrderedImmutableSortedSet when the original list was
* constructed from one, for faster contains(), indexOf(), and lastIndexOf().
*/
@Override ImmutableList<E> createAsList() {
return new ImmutableSortedAsList<E>(
this, new RegularImmutableList<E>(elements, fromIndex, size()));
}
/*
* Generates an ExplicitOrderedImmutableSortedSet when deserialized, for
* better performance.
*/
private static class SerializedForm<E> implements Serializable {
final Object[] elements;
public SerializedForm(Object[] elements) {
this.elements = elements;
}
@SuppressWarnings("unchecked")
Object readResolve() {
return ImmutableSortedSet.withExplicitOrder(Arrays.asList(elements));
}
private static final long serialVersionUID = 0;
}
private void readObject(ObjectInputStream stream)
throws InvalidObjectException {
throw new InvalidObjectException("Use SerializedForm");
}
@Override Object writeReplace() {
return new SerializedForm<E>(toArray());
}
}
| mit |
xu6148152/binea_project_for_android | MusicPlayer/app/src/androidTest/java/com/zepp/www/musicplayer/ApplicationTest.java | 355 | package com.zepp.www.musicplayer;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | mit |
macbury/ForgE | editor/src/macbury/forge/editor/controllers/UiController.java | 825 | package macbury.forge.editor.controllers;
import com.badlogic.gdx.files.FileHandle;
import macbury.forge.editor.parell.JobManager;
import macbury.forge.editor.parell.jobs.BuildUiJob;
import macbury.forge.editor.reloader.DirectoryWatchJob;
import macbury.forge.editor.reloader.DirectoryWatcher;
import macbury.forge.ui.UIManager;
/**
* Created by macbury on 04.09.15.
*/
public class UiController implements DirectoryWatchJob.DirectoryWatchJobListener {
private final JobManager jobs;
public UiController(DirectoryWatcher directoryWatcher, JobManager jobs) {
directoryWatcher.addListener(BuildUiJob.RAW_UI_IMAGES_PATH, this);
this.jobs = jobs;
}
public void rebuild() {
jobs.enqueue(new BuildUiJob());
}
@Override
public void onFileInDirectoryChange(FileHandle handle) {
rebuild();
}
}
| mit |
zhangqiang110/my4j | pms/src/main/java/com/swfarm/biz/ebay/web/RemoveEbayItemSummaryGroupController.java | 1990 | package com.swfarm.biz.ebay.web;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import org.springframework.web.servlet.view.RedirectView;
import com.swfarm.biz.ebay.bo.AdjustEbayItemSummarysSchedule;
import com.swfarm.biz.ebay.dto.SearchAdjustEbayItemSummarysSchedulesCriteria;
import com.swfarm.biz.ebay.srv.EbayService;
public class RemoveEbayItemSummaryGroupController extends AbstractController {
private EbayService ebayService;
public void setEbayService(EbayService ebayService) {
this.ebayService = ebayService;
}
protected ModelAndView handleRequestInternal(HttpServletRequest req,
HttpServletResponse res) throws Exception {
String idStr = req.getParameter("id");
if (StringUtils.isNotEmpty(idStr)) {
Long ebayItemSummaryGroupId = new Long(idStr);
SearchAdjustEbayItemSummarysSchedulesCriteria criteria = new SearchAdjustEbayItemSummarysSchedulesCriteria();
criteria.setEbayItemSummaryGroupId(ebayItemSummaryGroupId);
List adjustEbayItemSummarysSchedules = this.ebayService
.searchAdjustEbayItemSummarysSchedules(criteria);
if (CollectionUtils.isNotEmpty(adjustEbayItemSummarysSchedules)) {
for (Iterator iter = adjustEbayItemSummarysSchedules.iterator(); iter
.hasNext();) {
AdjustEbayItemSummarysSchedule schedule = (AdjustEbayItemSummarysSchedule) iter
.next();
this.ebayService
.removeAdjustEbayItemSummarysSchedule(schedule
.getId());
}
}
this.ebayService.removeEbayItemSummaryGroup(ebayItemSummaryGroupId);
}
return new ModelAndView(new RedirectView(
"/ebay/search_ebayitemsummarygroups.shtml", true));
}
}
| mit |
ai-ku/langvis | src/edu/cmu/cs/stage3/math/BezierCubic.java | 1449 | /*
* Copyright (c) 1999-2003, Carnegie Mellon University. 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.
*
* 3. Products derived from the software may not be called "Alice",
* nor may "Alice" appear in their name, without prior written
* permission of Carnegie Mellon University.
*
* 4. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes software developed by Carnegie Mellon University"
*/
package edu.cmu.cs.stage3.math;
public class BezierCubic extends BasisMatrixCubic {
private static final javax.vecmath.Matrix4d s_h = new javax.vecmath.Matrix4d( -1,3,-3,1, 3,-6,3,0, -3,3,0,0, 1,0,0,0 );
public BezierCubic( javax.vecmath.Vector4d g ) {
super( s_h, g );
}
public BezierCubic( double g0, double g1, double g2, double g3 ) {
this( new javax.vecmath.Vector4d( g0, g1, g2, g3 ) );
}
}
| mit |
dasfoo/rover-android-client | app/src/main/java/org/dasfoo/rover/android/client/grpc/task/EncodersReadingTask.java | 1636 | package org.dasfoo.rover.android.client.grpc.task;
import org.dasfoo.rover.server.RoverServiceGrpc;
import org.dasfoo.rover.server.ReadEncodersRequest;
import org.dasfoo.rover.server.ReadEncodersResponse;
import io.grpc.StatusRuntimeException;
/**
* Created by Katarina Sheremet on 5/17/16 9:32 PM.
*/
public class EncodersReadingTask extends AbstractGrpcTaskExecutor {
/**
* Send an encoder read request to the rover and wait for result.
*
* @param stub gRPC
* @return response as text
*/
@Override
public String execute(final RoverServiceGrpc.RoverServiceBlockingStub stub) {
try {
final ReadEncodersRequest readEncodersRequest =
ReadEncodersRequest.getDefaultInstance();
ReadEncodersResponse readEncodersResponse = stub.readEncoders(readEncodersRequest);
return String.format(
"Encoders\n" +
"Front left: %d\n" +
"Back left: %d\n" +
"Front right: %d\n" +
"Back right: %d\n",
readEncodersResponse.getLeftFront(),
readEncodersResponse.getLeftBack(),
readEncodersResponse.getRightFront(),
readEncodersResponse.getRightBack()
);
} catch (StatusRuntimeException e) {
switch (e.getStatus().getCode()) {
case UNKNOWN:
return "Unknown error. Try later";
default:
return e.getMessage();
}
}
}
}
| mit |
mitdbg/aurum-datadiscovery | ddprofiler/src/main/java/analysis/AnalyzerFactory.java | 645 | package analysis;
import analysis.modules.EntityAnalyzer;
public class AnalyzerFactory {
public static NumericalAnalysis makeNumericalAnalyzer() {
NumericalAnalyzer na = NumericalAnalyzer.makeAnalyzer();
return na;
}
public static TextualAnalysis makeTextualAnalyzer(EntityAnalyzer ea, int pseudoRandomSeed) {
TextualAnalyzer ta = TextualAnalyzer.makeAnalyzer(ea, pseudoRandomSeed);
return ta;
}
public static TextualAnalysis makeTextualAnalyzer(int pseudoRandomSeed) {
EntityAnalyzer ea = new EntityAnalyzer();
TextualAnalyzer ta = TextualAnalyzer.makeAnalyzer(ea, pseudoRandomSeed);
return ta;
}
}
| mit |
RGaldamez/NewTonelitos | TonelitosNuevo/src/tonelitosnuevo/Arista.java | 1712 | /*
* 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 tonelitosnuevo;
/**
*
* @author rick
*/
public class Arista {
private long distancia;
private Node nodoInicial;
private Node nodoFinal;
private int inicial;
private int finall;
public Arista(long distancia, Node nodoInicial, Node nodoFinal) {
this.distancia = distancia;
this.nodoInicial = nodoInicial;
this.nodoFinal = nodoFinal;
}
public Arista(long distancia, int inicial, int finall) {
this.distancia = distancia;
this.inicial = inicial;
this.finall = finall;
}
public int getInicial() {
return inicial;
}
public void setInicial(int inicial) {
this.inicial = inicial;
}
public int getFinall() {
return finall;
}
public void setFinall(int finall) {
this.finall = finall;
}
public long getDistancia() {
return distancia;
}
public void setDistancia(long distancia) {
this.distancia = distancia;
}
public Node getNodoInicial() {
return nodoInicial;
}
public void setNodoInicial(Node nodoInicial) {
this.nodoInicial = nodoInicial;
}
public Node getNodoFinal() {
return nodoFinal;
}
public void setNodoFinal(Node nodoFinal) {
this.nodoFinal = nodoFinal;
}
@Override
public String toString(){
return ("Inicia: "+nodoInicial.getNombre()+" Termina: "+nodoFinal.getNombre()+" Distancia: "+this.distancia);
}
}
| mit |
zhangqiang110/my4j | pms/src/main/java/com/swfarm/biz/magento/bo/magentoapi/ShoppingCartLicenseEntityArray.java | 1997 | package com.swfarm.biz.magento.bo.magentoapi;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>
* Java class for shoppingCartLicenseEntityArray complex type.
*
* <p>
* The following schema fragment specifies the expected content contained within
* this class.
*
* <pre>
* <complexType name="shoppingCartLicenseEntityArray">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="complexObjectArray" type="{urn:Magento}shoppingCartLicenseEntity" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "shoppingCartLicenseEntityArray", propOrder = { "complexObjectArray" })
public class ShoppingCartLicenseEntityArray {
protected List<ShoppingCartLicenseEntity> complexObjectArray;
/**
* Gets the value of the complexObjectArray property.
*
* <p>
* This accessor method returns a reference to the live list, not a
* snapshot. Therefore any modification you make to the returned list will
* be present inside the JAXB object. This is why there is not a
* <CODE>set</CODE> method for the complexObjectArray property.
*
* <p>
* For example, to add a new item, do as follows:
*
* <pre>
* getComplexObjectArray().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ShoppingCartLicenseEntity }
*
*
*/
public List<ShoppingCartLicenseEntity> getComplexObjectArray() {
if (complexObjectArray == null) {
complexObjectArray = new ArrayList<ShoppingCartLicenseEntity>();
}
return this.complexObjectArray;
}
}
| mit |
znGames/skyroad-magnets | skyroad-magnets/src/com/zngames/skymag/World.java | 8383 | package com.zngames.skymag;
import java.util.Random;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Array.ArrayIterator;
public class World {
SkyMagGame game;
WorldRenderer wr;
Ship ship;
Magnet leftMagnet;
Magnet rightMagnet;
float timeSinceLastCircle;
Array<Hole> holes;
Array<Enemy> enemies;
Array<Coin> coins;
Array<Key> keys;
float globalSpeed;
float muRadius;
float sigmaRadius;
float minDistanceBetweenHoles;
float minDistanceBetweenHolesAndCoins;
Hole pendingHole;
float pendingDistance;
float surplusDistance;
static final float fieldWidth = SkyMagGame.getWidth() * 0.5f;
static final float bridgeWidth = SkyMagGame.getWidth() / 32;
final float maxRadius = fieldWidth * 0.4f;
final float minRadius = fieldWidth / 8;
final float chanceOfCoinGeneration = 0.25f;
final float chanceOfBridgeGeneration = 1f;
public World(SkyMagGame game){
this.game = game;
leftMagnet = new Magnet(new Vector2(SkyMagGame.getWidth() / 9, SkyMagGame.getHeight() / 2), 40, 40);
rightMagnet = new Magnet(new Vector2(8*SkyMagGame.getWidth() / 9, SkyMagGame.getHeight() / 2), 40, 40);
ship = new DiscShip(leftMagnet, rightMagnet);
Gdx.input.setInputProcessor(new InputHandler(this));
timeSinceLastCircle = 0;
holes = new Array<Hole>(false, 16);
enemies = new Array<Enemy>(false, 16);
coins = new Array<Coin>(false, 16);
keys = new Array<Key>(false, 16);
globalSpeed = 60;
muRadius = (maxRadius-minRadius)*0.25f + minRadius;
sigmaRadius = maxRadius*0.50f;
minDistanceBetweenHoles = ship.getWidth();
minDistanceBetweenHolesAndCoins = Coin.coinRadius;
pendingDistance = 0;
surplusDistance = -1;
enemies.add(new ZigzagEnemy());
//enemies.add(new FreezerEnemy(SkyMagGame.getWidth() / 2, SkyMagGame.getHeight() / 3)); // Creating a freezer enemy
}
public void update(float delta){
// Updating the game global speed
updateGlobalSpeed(delta);
// Updating the holes (generating new holes, deleting old holes, etc.)
updateHoles(delta);
// Updating the coins
updateCoins(delta);
// Updating the keys
updateKeys(delta);
// Updating the enemies
updateEnemies(delta);
// Making the ship advance
ship.advance(delta);
}
public void updateGlobalSpeed(float delta){
globalSpeed+=0.3*delta;
}
public void updateHoles(float delta){
timeSinceLastCircle += delta;
if(surplusDistance > 0){
pendingDistance += globalSpeed*delta;
if(pendingDistance >= surplusDistance){
holes.add(pendingHole);
if(pendingHole.isBridged()){
generateKey(pendingHole.x, pendingHole.y);
}
if(MathUtils.randomBoolean(chanceOfCoinGeneration)){
generateCircleOfCoins(pendingHole.x, pendingHole.y, pendingHole.radius);
}
surplusDistance = -1;
pendingDistance = 0;
timeSinceLastCircle = 0;
}
}
// Generating a circle every 2 seconds approximately
else if(MathUtils.random(timeSinceLastCircle) > 1.5){
System.out.println("Generating");
timeSinceLastCircle = 0;
float x;
float y = SkyMagGame.getHeight()+maxRadius;
float radius;
surplusDistance = -1;
x = MathUtils.random(SkyMagGame.getWidth()*0.25f, SkyMagGame.getWidth()*0.25f + fieldWidth);
radius = generateRadius(minRadius, maxRadius);
ArrayIterator<Hole> iter = new ArrayIterator<Hole>(holes);
while(iter.hasNext()){
Hole circle = iter.next();
if(Math.sqrt((circle.x-x)*(circle.x-x) + (circle.y-y)*(circle.y-y)) < radius + minDistanceBetweenHoles + circle.radius){
surplusDistance = (float) Math.sqrt((radius + minDistanceBetweenHoles + circle.radius)*(radius + minDistanceBetweenHoles + circle.radius) - (circle.x-x)*(circle.x-x)) - Math.abs(circle.y-y);
}
}
boolean bridged = MathUtils.randomBoolean(chanceOfBridgeGeneration);
if(surplusDistance <= 0){
holes.add(new Hole(x,y,radius,bridged));
if(bridged){
generateKey(x, y);
}
if(MathUtils.randomBoolean(chanceOfCoinGeneration)){
generateCircleOfCoins(x, y, radius);
}
} else {
pendingHole = new Hole(x,y,radius,bridged);
pendingDistance = 0;
}
}
// Removing old holes and making the current holes advance
ArrayIterator<Hole> iterCircles = new ArrayIterator<Hole>(holes);
while(iterCircles.hasNext()){
Hole circle = iterCircles.next();
if(circle.y + circle.radius < 0){
iterCircles.remove();
}
circle.setPosition(circle.x, circle.y-globalSpeed*delta);
if(circle.isBridged()){
circle.advanceBridge(globalSpeed*delta);
}
}
// Updating the hole generation gaussian parameters
if(muRadius < maxRadius){
muRadius += maxRadius*0.001*delta;
}
else{
sigmaRadius += sigmaRadius*0.0001*delta;
}
}
public void updateEnemies(float delta){
ArrayIterator<Enemy> iterEnemies = new ArrayIterator<Enemy>(enemies);
while(iterEnemies.hasNext()){
Enemy enemy = iterEnemies.next();
enemy.update(this, delta);
// Removing the enemies from the array if they should stop existing
if(enemy.shouldStopExisting(this)){
iterEnemies.remove();
}
enemy.actOn(ship);
}
}
public void updateCoins(float delta){
ArrayIterator<Coin> iterCoins = new ArrayIterator<Coin>(coins);
while(iterCoins.hasNext()){
Coin coin = iterCoins.next();
if(coin.actOn(ship)){
iterCoins.remove();
} else{
coin.setPosition(coin.getX(), coin.getY()-globalSpeed*delta);
}
}
}
public void updateKeys(float delta){
ArrayIterator<Key> iterKeys = new ArrayIterator<Key>(keys);
while(iterKeys.hasNext()){
Key key = iterKeys.next();
if(key.actOn(ship)){
iterKeys.remove();
} else{
key.setPosition(key.getX(), key.getY()-globalSpeed*delta);
}
}
}
public float generateRadius(float min, float max){
float z;
int cpt = 0;
do{
Random random = new Random();
z = (float) random.nextGaussian()*sigmaRadius + muRadius;
cpt++;
if(cpt>100){
return random.nextFloat()*(max - min) + min;
}
}while(z < min || z > max);
return z;
}
public void generateCircleOfCoins(float x, float y, float radius){
float distanceFromHoleCenterToCoinCenter = radius+Coin.coinRadius+this.minDistanceBetweenHolesAndCoins;
int nbCircles = (int) ( (MathUtils.PI*distanceFromHoleCenterToCoinCenter) / Coin.coinRadius );
float leftSpace = 2*( (MathUtils.PI*distanceFromHoleCenterToCoinCenter) % Coin.coinRadius );
float spaceBetweenCircles = leftSpace/nbCircles;
float angleBetweenCircles = (float) (2*Math.atan2(Coin.coinRadius+(spaceBetweenCircles*1.0f/2), distanceFromHoleCenterToCoinCenter));
float currentAngle = 0;
for(int i=0;i<nbCircles;i++){
float xCoordinate = x + distanceFromHoleCenterToCoinCenter*MathUtils.cos(currentAngle);
if(xCoordinate + Coin.coinRadius < World.getRightBorderXCoordinate() && xCoordinate - Coin.coinRadius > World.getLeftBorderXCoordinate()){
coins.add(new Coin(xCoordinate, y + distanceFromHoleCenterToCoinCenter*MathUtils.sin(currentAngle)));
}
currentAngle += angleBetweenCircles;
}
}
public void generateKey(float x, float y){
keys.add(new Key(x,y));
}
public Ship getShip() {
return ship;
}
public void setShip(Ship ship) {
this.ship = ship;
}
public Magnet getLeftMagnet() {
return leftMagnet;
}
public void setLeftMagnet(Magnet leftMagnet) {
this.leftMagnet = leftMagnet;
}
public Magnet getRightMagnet() {
return rightMagnet;
}
public void setRightMagnet(Magnet rightMagnet) {
this.rightMagnet = rightMagnet;
}
public WorldRenderer getRenderer(){
return wr;
}
public void setRenderer(WorldRenderer wr){
this.wr = wr;
}
public Array<Hole> getHoles(){
return holes;
}
public Array<Enemy> getEnemies(){
return enemies;
}
public Array<Coin> getCoins(){
return coins;
}
public Array<Key> getKeys(){
return keys;
}
static public float getFieldWidth(){
return fieldWidth;
}
static public float getLeftBorderXCoordinate(){
return (SkyMagGame.getWidth()-fieldWidth)/2;
}
static public float getRightBorderXCoordinate(){
return (SkyMagGame.getWidth()+fieldWidth)/2;
}
static public float getMiddleBorderXCoordinate(){
return SkyMagGame.getWidth()/2;
}
}
| mit |
umairsair/designpatterns-chessgame | src/pieces/Queen.java | 1251 | package pieces;
import java.awt.Color;
import java.util.List;
import chess.Cell;
/**
* This is the Queen Class inherited from the abstract Piece class
*
*/
public class Queen extends Piece {
private static final String WHITE_QUEEN_IMAGE = "White_Queen.png";
private static final String BLACK_QUEEN_IMAGE = "Black_Queen.png";
// Constructors
public Queen(String i, Color c) {
setId(i);
setImagePath(c.equals(Color.WHITE) ? WHITE_QUEEN_IMAGE
: BLACK_QUEEN_IMAGE);
setColor(c);
}
// Move Function Defined
@Override
public List<Cell> possibleMovesCells(Cell state[][], int x, int y) {
possibleMoves.clear();
possibleMoves.addAll(MoveUtils.getLeftMoves(this, state, x, y));
possibleMoves.addAll(MoveUtils.getRightMoves(this, state, x, y));
possibleMoves.addAll(MoveUtils.getUpwardMoves(this, state, x, y));
possibleMoves.addAll(MoveUtils.getDownwardMoves(this, state, x, y));
possibleMoves.addAll(MoveUtils.getRightUpDiagonalMoves(this, state, x, y));
possibleMoves.addAll(MoveUtils.getRightDownDiagonalMoves(this, state, x, y));
possibleMoves.addAll(MoveUtils.getLeftUpDiagonalMoves(this, state, x, y));
possibleMoves.addAll(MoveUtils.getLeftDownDiagonalMoves(this, state, x, y));
return possibleMoves;
}
} | mit |
speedingdeer/linked-data-visualization-tools | src/main/java/es/upm/fi/dia/oeg/map4rdf/client/event/EditResourceCloseEventHandler.java | 1524 | /**
* Copyright (c) 2011 Ontology Engineering Group,
* Departamento de Inteligencia Artificial,
* Facultad de Informetica, Universidad
* Politecnica de Madrid, Spain
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package es.upm.fi.dia.oeg.map4rdf.client.event;
import com.google.gwt.event.shared.EventHandler;
/**
* @author Filip
*/
public interface EditResourceCloseEventHandler extends EventHandler {
void onEditResourceClose(EditResourceCloseEvent editResourceCloseEvent);
}
| mit |
UrQA/UrQA-Client-Android-Gradle | app/src/main/java/com/urqa/common/JsonObj/ErrorSendData.java | 5593 | package com.urqa.common.JsonObj;
import com.urqa.common.StateData;
import com.urqa.eventpath.EventPath;
import com.urqa.library.model.JsonInterface;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
public class ErrorSendData extends JsonObj implements JsonInterface {
public ErrorSendData() {
// TODO Auto-generated constructor stub
sdkversion = StateData.SDKVersion;
locale = "";
apikey = "";
datetime = "unknown";
device = "unknown";
country = "unknown";
errorname = "";
errorclassname = "";
linenum = -1;
callstack = "";
appversion = "unknown";
osversion = "unknown";
gpson = 0; // int 0 = off ,1 = on
wifion = 0;
mobileon = 0;
scrwidth = -1;
scrheight = -1;
lastactivity = "";
// CallStackFileName = null;
// LogFileName = null;
batterylevel = -1;
availsdcard = -1;
rooted = 0; // int 0 = off ,1 = on
appmemtotal = -1; // mega단위로 int.
appmemfree = -1;
appmemmax = -1;
kernelversion = "";
xdpi = -1;
ydpi = -1;
scrorientation = -1;
sysmemlow = 0; // int 0 = not 1 = ok
tag = "";
rank = -1;
consoleLog = "";
mDeviceId = "";
mCarrierName = "";
}
public String sdkversion;
public String locale;
public String tag;
public int rank;
/**
* CallStack데이터
*/
public String callstack;
/**
* APIKEY
*/
public String apikey;
/**
* 에러 발생 시간
*/
public String datetime;
/**
* 핸드폰 모델 명
*/
public String device;
/**
* 국가명
*/
public String country;
/**
* 에러 이름
*/
public String errorname;
/**
* 에러가 발생한 클래스 이름 ClassName 클래스 이름
*/
public String errorclassname;
/**
* Error Code Line
*/
public int linenum;
/**
* 앱 버젼
*/
public String appversion;
/**
* OS 버젼
*/
public String osversion;
// public String CallStack;
// public String UserLog;
/**
* GPS On/Off
*/
public int gpson;
/**
* WiFi On/Off
*/
public int wifion;
/**
* MobileNetwork(3G) On/Off
*/
public int mobileon;
/**
* 화면 가로 크기
*/
public int scrwidth;
/**
* 화면 세로 크기
*/
public int scrheight;
/**
* 배터리 잔량
*/
public int batterylevel;
/**
* 사용가능한 용량 //mega단위로 int
*/
public int availsdcard;
/**
* 루트 되었는지 안되었는지
*/
public int rooted;
/**
* 사용량
*/
public int appmemtotal;
/**
* 남은량
*/
public int appmemfree;
/**
* 최대량
*/
public int appmemmax;
/**
* 리눅스 커널 버전
*/
public String kernelversion;
/**
* XDPI
*/
public float xdpi;
/**
* YDPI
*/
public float ydpi;
/**
* 0,2 세로 1,3 가로
*/
public int scrorientation;
/**
* 시스템 메모리가 부족한가 안부족한가
*/
public int sysmemlow;
/**
* 통신사
*/
public String mCarrierName;
/**
* id
*/
public String mDeviceId;
/**
* console log
*/
public String consoleLog;
public String lastactivity;
public List<EventPath> eventpaths;
@Override
public String toJson() {
return toJSONObject().toString();
}
@Override
public void fromJson(String JsonString) {
}
@Override
public JSONObject toJSONObject() {
JSONObject object = new JSONObject();
try {
object.put("sdkversion", sdkversion);
object.put("locale", locale);
object.put("tag", tag);
object.put("rank", rank);
object.put("callstack", callstack);
object.put("apikey", apikey);
object.put("datetime", datetime);
object.put("device", device);
object.put("country", country);
object.put("errorname", errorname);
object.put("errorclassname", errorclassname);
object.put("linenum", linenum);
object.put("appversion", appversion);
object.put("osversion", osversion);
object.put("gpson", gpson);
object.put("wifion", wifion);
object.put("mobileon", mobileon);
object.put("scrwidth", scrwidth);
object.put("scrheight", scrheight);
object.put("batterylevel", batterylevel);
object.put("availsdcard", availsdcard);
object.put("rooted", rooted);
object.put("appmemtotal", appmemtotal);
object.put("appmemfree", appmemfree);
object.put("appmemmax", appmemmax);
object.put("kernelversion", kernelversion);
object.put("xdpi", xdpi);
object.put("ydpi", ydpi);
object.put("scrorientation", scrorientation);
object.put("sysmemlow", sysmemlow);
object.put("lastactivity", lastactivity);
object.put("carrier_name", mCarrierName);
object.put("device_id", mDeviceId);
object.put("eventpaths", getEventPath());
} catch (JSONException e) {
}
return object;
}
/**
* Event Path 계산
* @return
*/
private JSONArray getEventPath() throws JSONException {
JSONArray array = new JSONArray();
for (EventPath eventpath : eventpaths) {
JSONObject object = new JSONObject();
object.put("datetime", eventpath.getDatetime());
object.put("classname", eventpath.getClassName());
object.put("methodname", eventpath.getMethodName());
object.put("label", eventpath.getLabel());
object.put("linenum", eventpath.getLine());
array.put(object);
}
return array;
}
}
| mit |
alinebrito/APIDiff | src/main/java/apidiff/internal/analysis/FieldDiff.java | 16030 | package apidiff.internal.analysis;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.jdt.core.dom.AbstractTypeDeclaration;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.FieldDeclaration;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jgit.revwalk.RevCommit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import apidiff.Change;
import apidiff.enums.Category;
import apidiff.internal.analysis.description.FieldDescription;
import apidiff.internal.exception.BindingException;
import apidiff.internal.util.UtilTools;
import apidiff.internal.visitor.APIVersion;
import refdiff.core.api.RefactoringType;
import refdiff.core.rm2.model.refactoring.SDRefactoring;
public class FieldDiff {
private Logger logger = LoggerFactory.getLogger(FieldDiff.class);
private Map<RefactoringType, List<SDRefactoring>> refactorings = new HashMap<RefactoringType, List<SDRefactoring>>();
private List<String> fieldWithPathChanged = new ArrayList<String>();
private List<Change> listChange = new ArrayList<Change>();
private FieldDescription description = new FieldDescription();
private RevCommit revCommit;
public List<Change> detectChange(final APIVersion version1, final APIVersion version2, final Map<RefactoringType, List<SDRefactoring>> refactorings, final RevCommit revCommit){
this.logger.info("Processing Fields...");
this.refactorings = refactorings;
this.revCommit = revCommit;
this.findDefaultValueFields(version1, version2);
this.findChangedTypeFields(version1, version2);
this.findRemoveAndRefactoringFields(version1, version2);
this.findChangedVisibilityFields(version1, version2);
this.findChangedFinal(version1, version2);
this.findAddedFields(version1, version2);
this.findAddedDeprecatedFields(version1, version2);
return this.listChange;
}
private void addChange(final TypeDeclaration type, final FieldDeclaration field, Category category, Boolean isBreakingChange, final String description){
String name = UtilTools.getFieldName(field);
if(name != null){
Change change = new Change();
change.setJavadoc(UtilTools.containsJavadoc(type, field));
change.setDeprecated(this.isDeprecated(field, type));
change.setBreakingChange(this.isDeprecated(field, type) ? false : isBreakingChange);
change.setPath(UtilTools.getPath(type));
change.setElement(name);
change.setCategory(category);
change.setDescription(description);
change.setRevCommit(this.revCommit);
isBreakingChange = this.isDeprecated(field, type) ? false : isBreakingChange;
this.listChange.add(change);
}
else{
this.logger.error("Removing field with null name " + field);
}
}
private List<SDRefactoring> getAllMoveOperations(){
List<SDRefactoring> listMove = new ArrayList<SDRefactoring>();
if(this.refactorings.containsKey(RefactoringType.PULL_UP_ATTRIBUTE)){
listMove.addAll(this.refactorings.get(RefactoringType.PULL_UP_ATTRIBUTE));
}
if(this.refactorings.containsKey(RefactoringType.PUSH_DOWN_ATTRIBUTE)){
listMove.addAll(this.refactorings.get(RefactoringType.PUSH_DOWN_ATTRIBUTE));
}
if(this.refactorings.containsKey(RefactoringType.MOVE_ATTRIBUTE)){
listMove.addAll(this.refactorings.get(RefactoringType.MOVE_ATTRIBUTE));
}
return listMove;
}
private Category getCategory(RefactoringType refactoringType){
switch (refactoringType) {
case PULL_UP_ATTRIBUTE:
return Category.FIELD_PULL_UP;
case PUSH_DOWN_ATTRIBUTE:
return Category.FIELD_PUSH_DOWN;
default:
return Category.FIELD_MOVE;
}
}
private Boolean processMoveField(final FieldDeclaration field, final TypeDeclaration type){
List<SDRefactoring> listMove = this.getAllMoveOperations();
if(listMove != null){
for(SDRefactoring ref : listMove){
String fullNameAndPath = this.getNameAndPath(field, type);
if(fullNameAndPath.equals(ref.getEntityBefore().fullName())){
Boolean isBreakingChange = RefactoringType.PULL_UP_OPERATION.equals(ref.getRefactoringType())? false:true;
Category category = this.getCategory(ref.getRefactoringType());
String description = this.description.refactorField(category, ref);
this.addChange(type, field, category, isBreakingChange, description);
this.fieldWithPathChanged.add(ref.getEntityAfter().fullName());
return true;
}
}
}
return false;
}
/**
* @param field
* @param type
* @return Return Name class + name field (e.g. : org.lib.Math#value)
*/
private String getNameAndPath(final FieldDeclaration field, final TypeDeclaration type){
return UtilTools.getPath(type) + "#" + UtilTools.getFieldName(field);
}
private Boolean processRemoveField(final FieldDeclaration field, final TypeDeclaration type){
String description = this.description.remove( UtilTools.getFieldName(field), UtilTools.getPath(type));
this.addChange(type, field, Category.FIELD_REMOVE, true, description);
return false;
}
private Boolean checkAndProcessRefactoring(final FieldDeclaration field, final TypeDeclaration type){
return this.processMoveField(field, type);
}
/**
* @param fieldInVersion1
* @param fieldInVersion2
* @return True, if there is a difference between the fields.
*/
private Boolean thereAreDifferentDefaultValueField(FieldDeclaration fieldInVersion1, FieldDeclaration fieldInVersion2){
List<VariableDeclarationFragment> variable1Fragments = fieldInVersion1.fragments();
List<VariableDeclarationFragment> variable2Fragments = fieldInVersion2.fragments();
Expression valueVersion1 = variable1Fragments.get(0).getInitializer();
Expression valueVersion2 = variable2Fragments.get(0).getInitializer();
//If default value was removed/changed
if((valueVersion1 == null && valueVersion2 != null) || (valueVersion1 != null && valueVersion2 == null)){
return true;
}
//If fields have default value and they are different
if((valueVersion1 != null && valueVersion2 != null) && (!valueVersion1.toString().equals(valueVersion2.toString()))){
return true;
}
return false;
}
/**
* Searching changed default values
* @param version1
* @param version2
*/
private void findDefaultValueFields(APIVersion version1, APIVersion version2){
for (TypeDeclaration type : version1.getApiAcessibleTypes()) {
if(version2.containsAccessibleType(type)){
for (FieldDeclaration fieldInVersion1 : type.getFields()) {
if(this.isFieldAccessible(fieldInVersion1)){
FieldDeclaration fieldInVersion2 = version2.getVersionField(fieldInVersion1, type);
if(this.isFieldAccessible(fieldInVersion2) && this.thereAreDifferentDefaultValueField(fieldInVersion1, fieldInVersion2)){
String description = this.description.changeDefaultValue(UtilTools.getFieldName(fieldInVersion2), UtilTools.getPath(type));
this.addChange(type, fieldInVersion2, Category.FIELD_CHANGE_DEFAULT_VALUE, true, description);
}
}
}
}
}
}
/**
* Searching changed fields type
* @param version1
* @param version2
*/
private void findChangedTypeFields(APIVersion version1, APIVersion version2) {
for (TypeDeclaration type : version1.getApiAcessibleTypes()) {
if(version2.containsAccessibleType(type)){
for (FieldDeclaration fieldInVersion1 : type.getFields()) {
if(!UtilTools.isVisibilityPrivate(fieldInVersion1) && !UtilTools.isVisibilityDefault(fieldInVersion1)){
FieldDeclaration fieldInVersion2 = version2.getVersionField(fieldInVersion1, type);
if(fieldInVersion2 != null && !UtilTools.isVisibilityPrivate(fieldInVersion2)){
if(!fieldInVersion1.getType().toString().equals(fieldInVersion2.getType().toString())){
String description = this.description.returnType(UtilTools.getFieldName(fieldInVersion2), UtilTools.getPath(type));
this.addChange(type, fieldInVersion2, Category.FIELD_CHANGE_TYPE, true, description);
}
}
}
}
}
}
}
/**
* Finding fields with changed visibility
* @param typeVersion1
* @param fieldVersion1
* @param fieldVersion2
*/
private void checkGainOrLostVisibility(TypeDeclaration typeVersion1, FieldDeclaration fieldVersion1, FieldDeclaration fieldVersion2){
if(fieldVersion2 != null && fieldVersion1!=null){//The method exists in the current version
String visibilityMethod1 = UtilTools.getVisibility(fieldVersion1);
String visibilityMethod2 = UtilTools.getVisibility(fieldVersion2);
if(!visibilityMethod1.equals(visibilityMethod2)){ //The access modifier was changed.
String description = this.description.visibility(UtilTools.getFieldName(fieldVersion1), UtilTools.getPath(typeVersion1), visibilityMethod1, visibilityMethod2);
//Breaking change: public >> private, default, protected || protected >> private, default
if(this.isFieldAccessible(fieldVersion1) && !UtilTools.isVisibilityPublic(fieldVersion2)){
this.addChange(typeVersion1, fieldVersion1, Category.FIELD_LOST_VISIBILITY, true, description);
}
else{
//non-breaking change: private or default --> all modifiers
Category category = UtilTools.isVisibilityDefault(fieldVersion1) && UtilTools.isVisibilityPrivate(fieldVersion2)? Category.FIELD_LOST_VISIBILITY: Category.FIELD_GAIN_VISIBILITY;
this.addChange(typeVersion1, fieldVersion1, category, false, description);
}
}
}
}
/**
* Finding fields with changed visibility
* @param version1
* @param version2
*/
private void findChangedVisibilityFields(APIVersion version1, APIVersion version2) {
for(TypeDeclaration typeVersion1 : version1.getApiAcessibleTypes()){
if(version2.containsAccessibleType(typeVersion1)){
for (FieldDeclaration fieldVersion1 : typeVersion1.getFields()){
FieldDeclaration fieldVersion2 = version2.getVersionField(fieldVersion1, typeVersion1);
this.checkGainOrLostVisibility(typeVersion1, fieldVersion1, fieldVersion2);
}
}
}
}
/**
* Finding deprecated fields
* @param version1
* @param version2
*/
private void findAddedDeprecatedFields(APIVersion version1, APIVersion version2) {
for(TypeDeclaration typeVersion2 : version2.getApiAcessibleTypes()){
for(FieldDeclaration fieldVersion2 : typeVersion2.getFields()){
if(this.isFieldAccessible(fieldVersion2) && this.isDeprecated(fieldVersion2, typeVersion2)){
FieldDeclaration fieldInVersion1 = version1.getVersionField(fieldVersion2, typeVersion2);
if(fieldInVersion1 == null || !this.isDeprecated(fieldInVersion1, version1.getVersionAccessibleType(typeVersion2))){
String description = this.description.deprecate(UtilTools.getFieldName(fieldVersion2), UtilTools.getPath(typeVersion2));
this.addChange(typeVersion2, fieldVersion2, Category.FIELD_DEPRECATED, false, description);
}
}
}
}
}
/**
* Finding added fields
* @param version1
* @param version2
*/
private void findAddedFields(APIVersion version1, APIVersion version2) {
for (TypeDeclaration typeVersion2 : version2.getApiAcessibleTypes()) {
if(version1.containsAccessibleType(typeVersion2)){
for (FieldDeclaration fieldInVersion2 : typeVersion2.getFields()) {
String fullNameAndPath = this.getNameAndPath(fieldInVersion2, typeVersion2);
if(!UtilTools.isVisibilityPrivate(fieldInVersion2) && !UtilTools.isVisibilityDefault(fieldInVersion2) && !this.fieldWithPathChanged.contains(fullNameAndPath)){
FieldDeclaration fieldInVersion1;
fieldInVersion1 = version1.getVersionField(fieldInVersion2, typeVersion2);
if(fieldInVersion1 == null){
String description = this.description.addition(UtilTools.getFieldName(fieldInVersion2), UtilTools.getPath(typeVersion2));
this.addChange(typeVersion2, fieldInVersion2, Category.FIELD_ADD, false, description);
}
}
}
}
}
}
/**
* Finding removed fields. If class was removed, class removal is a breaking change.
* @param version1
* @param version2
*/
private void findRemoveAndRefactoringFields(APIVersion version1, APIVersion version2) {
for (TypeDeclaration type : version1.getApiAcessibleTypes()) {
if(version2.containsAccessibleType(type)){
for (FieldDeclaration fieldInVersion1 : type.getFields()) {
if(!UtilTools.isVisibilityPrivate(fieldInVersion1)){
FieldDeclaration fieldInVersion2 = version2.getVersionField(fieldInVersion1, type);
if(fieldInVersion2 == null){
Boolean refactoring = this.checkAndProcessRefactoring(fieldInVersion1, type);
if(!refactoring){
this.processRemoveField(fieldInVersion1, type);
}
}
}
}
}
}
}
/**
* @param field
* @param type
* @return true, type is deprecated or field is deprecated
*/
private Boolean isDeprecated(FieldDeclaration field, AbstractTypeDeclaration type){
Boolean isFieldDeprecated = this.isDeprecatedField(field);
Boolean isTypeDeprecated = (type != null && type.resolveBinding() != null && type.resolveBinding().isDeprecated()) ? true: false;
return isFieldDeprecated || isTypeDeprecated;
}
/**
* Checking deprecated fields
* @param field
* @return
*/
private Boolean isDeprecatedField(FieldDeclaration field){
if(field != null){
List<VariableDeclarationFragment> variableFragments = field.fragments();
for (VariableDeclarationFragment variableDeclarationFragment : variableFragments) {
if(variableDeclarationFragment.resolveBinding() != null && variableDeclarationFragment.resolveBinding().isDeprecated()){
return true;
}
}
}
return false;
}
/**
* @param field
* @return true, if is a accessible field by external systems
*/
private boolean isFieldAccessible(FieldDeclaration field){
return field != null && (UtilTools.isVisibilityProtected(field) || UtilTools.isVisibilityPublic(field))?true:false;
}
/**
* Finding change in final modifier
* @param fieldVersion1
* @param fieldVersion2
* @throws BindingException
*/
private void diffModifierFinal(TypeDeclaration typeVersion1, FieldDeclaration fieldVersion1, FieldDeclaration fieldVersion2){
//There is not change.
if((UtilTools.isFinal(fieldVersion1) && UtilTools.isFinal(fieldVersion2)) || ((!UtilTools.isFinal(fieldVersion1) && !UtilTools.isFinal(fieldVersion2)))){
return;
}
String description = "";
//Gain "final"
if((!UtilTools.isFinal(fieldVersion1) && UtilTools.isFinal(fieldVersion2))){
description = this.description.modifierFinal(UtilTools.getFieldName(fieldVersion2), UtilTools.getPath(typeVersion1), true);
this.addChange(typeVersion1, fieldVersion2, Category.FIELD_ADD_MODIFIER_FINAL, true, description);
}
else{
//Lost "final"
description = this.description.modifierFinal(UtilTools.getFieldName(fieldVersion2), UtilTools.getPath(typeVersion1), false);
this.addChange(typeVersion1, fieldVersion2, Category.FIELD_REMOVE_MODIFIER_FINAL, false, description);
}
}
/**
* Finding change in final modifier
*
* @param version1
* @param version2
*/
private void findChangedFinal(APIVersion version1, APIVersion version2) {
for (TypeDeclaration typeInVersion1 : version1.getApiAcessibleTypes()) {
if(version2.containsType(typeInVersion1)){//Se type ainda existe.
for(FieldDeclaration fieldVersion1: typeInVersion1.getFields()){
FieldDeclaration fieldVersion2 = version2.getVersionField(fieldVersion1, typeInVersion1);
if(this.isFieldAccessible(fieldVersion1) && (fieldVersion2 != null)){
this.diffModifierFinal(typeInVersion1, fieldVersion1, fieldVersion2);
}
}
}
}
}
}
| mit |
hsch/bcpg-simple | src/main/java/io/trbl/bcpg/SecretKey.java | 272 | package io.trbl.bcpg;
import java.io.IOException;
public interface SecretKey extends Key {
PublicKey getPublicKey();
SecretTransform signEncryptFor(String publicKey) throws IOException;
SecretTransform decryptVerifyFrom(String publicKey) throws IOException;
}
| mit |
DeveloperDavo/DesignPatterns | src/main/java/state/blurayplayer/PlayingState.java | 814 | package state.blurayplayer;
import java.util.logging.Level;
import java.util.logging.Logger;
public class PlayingState implements BluRayPlayerState {
private static final Logger LOGGER = Logger.getLogger(PlayingState.class.getSimpleName());
private final BluRayPlayer player;
public PlayingState(BluRayPlayer player) {
this.player = player;
}
@Override
public void insertBluRay() {
LOGGER.log(Level.SEVERE, "The Blu-ray is playing!");
}
@Override
public void pressPlay() {
LOGGER.log(Level.WARNING, "The Blu-ray is already playing.");
}
@Override
public void pressStop() {
LOGGER.log(Level.INFO, "The Blu-ray player now is stopped.");
player.setState(player.getStoppedState());
}
@Override
public void ejectBluRay() {
LOGGER.log(Level.SEVERE, "The Blu-ray is playing!");
}
}
| mit |
SpongePowered/Sponge | src/main/java/org/spongepowered/common/event/tracking/context/transaction/inventory/DropFromPlayerInventoryTransaction.java | 4231 | /*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.common.event.tracking.context.transaction.inventory;
import net.minecraft.server.level.ServerPlayer;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.api.entity.Entity;
import org.spongepowered.api.event.Cause;
import org.spongepowered.api.event.EventContext;
import org.spongepowered.api.event.EventContextKeys;
import org.spongepowered.api.event.SpongeEventFactory;
import org.spongepowered.api.event.cause.entity.SpawnTypes;
import org.spongepowered.api.event.item.inventory.ChangeInventoryEvent;
import org.spongepowered.api.item.inventory.Inventory;
import org.spongepowered.api.item.inventory.Slot;
import org.spongepowered.api.item.inventory.entity.PlayerInventory;
import org.spongepowered.api.item.inventory.equipment.EquipmentTypes;
import org.spongepowered.api.item.inventory.transaction.SlotTransaction;
import org.spongepowered.common.event.tracking.PhaseContext;
import org.spongepowered.common.event.tracking.TrackingUtil;
import java.util.List;
import java.util.Optional;
public class DropFromPlayerInventoryTransaction extends InventoryBasedTransaction {
private final ServerPlayer player;
private final boolean dropAll;
private final @Nullable Slot slot;
public DropFromPlayerInventoryTransaction(final ServerPlayer player, final boolean dropAll) {
super((Inventory) player.inventory);
this.player = player;
this.dropAll = dropAll;
this.slot = ((PlayerInventory) player.inventory).equipment().slot(EquipmentTypes.MAIN_HAND).orElse(null);
}
@Override
Optional<ChangeInventoryEvent> createInventoryEvent(final List<SlotTransaction> slotTransactions,
final List<Entity> entities, final PhaseContext<@NonNull ?> context,
final Cause currentCause) {
TrackingUtil.setCreatorReference(entities, this.player);
final Cause causeWithSpawnType = Cause.builder().from(currentCause).build(
EventContext.builder().from(currentCause.context()).add(
EventContextKeys.SPAWN_TYPE,
SpawnTypes.DROPPED_ITEM.get()
).build());
if (this.dropAll) {
return Optional.of(SpongeEventFactory.createChangeInventoryEventDropFull(causeWithSpawnType,
entities, this.inventory, this.slot, slotTransactions));
}
return Optional.of(SpongeEventFactory.createChangeInventoryEventDropSingle(causeWithSpawnType,
entities, this.inventory, this.slot, slotTransactions));
}
@Override
public void restore(final PhaseContext<@NonNull ?> context, final ChangeInventoryEvent event) {
this.handleEventResults(this.player, event);
}
@Override
public void postProcessEvent(PhaseContext<@NonNull ?> context, ChangeInventoryEvent event) {
this.handleEventResults(this.player, event);
}
}
| mit |
Jovtcho/JavaFundamentals | JavaOOP Advanced/08.DependensyInversionInterfaceSegregation-Lab/p04_recharge/RobotAdapter.java | 377 | package p04_recharge;
public class RobotAdapter implements Rechargeable {
private Robot robot;
private int currentPower;
public RobotAdapter(Robot robot) {
this.robot = robot;
}
@Override
public void recharge() {
this.currentPower += 100;
this.robot.setCurrentPower(this.currentPower);
this.robot.recharge();
}
}
| mit |
shivam091/Java-Security | crypt/src/main/java/org/security/crypt/pbe/PBES1EncryptionScheme.java | 2796 | package org.security.crypt.pbe;
import javax.crypto.spec.SecretKeySpec;
import org.security.crypt.digest.DigestAlgorithm;
import org.security.crypt.pkcs.PBEParameter;
import org.security.crypt.pkcs.PBES1Algorithm;
import org.security.crypt.symmetric.SymmetricAlgorithm;
/**
* Implements the PBES1 encryption scheme defined in PKCS#5v2.
*
* @author shivam
*
*/
public class PBES1EncryptionScheme extends AbstractEncryptionScheme {
/** Number of bytes (octets) in derived key. */
public static final int KEY_LENGTH = 8;
/** Number of bytes (octets) in IV. */
public static final int IV_LENGTH = 8;
/** Derived key bit length. */
private static final int DKEY_BIT_LENGTH = (KEY_LENGTH + IV_LENGTH) * 8;
/** Key generator. */
private KeyGenerator generator;
/**
* Creates a new instance with the given parameters.
*
* @param alg
* Describes hash/algorithm pair suitable for PBES1 scheme.
* @param params
* Key generation function salt and iteration count.
*/
public PBES1EncryptionScheme(final PBES1Algorithm alg,
final PBEParameter params) {
setCipher(SymmetricAlgorithm.newInstance(alg.getSpec()));
generator = new PBKDF1KeyGenerator(alg.getDigest(), params.getSalt(),
params.getIterationCount());
}
/**
* Creates a new instance with the given parameters.
*
* @param alg
* Symmetric algorithm used for encryption/decryption.
* @param digest
* Key generation function digest.
* @param params
* Key generation function salt and iteration count.
*/
public PBES1EncryptionScheme(final SymmetricAlgorithm alg,
final DigestAlgorithm digest, final PBEParameter params) {
boolean valid = false;
for (PBES1Algorithm a : PBES1Algorithm.values()) {
if (a.getDigest().getAlgorithm().equals(digest.getAlgorithm())
&& a.getSpec().getName().equals(alg.getAlgorithm())
&& a.getSpec().getMode().equals(alg.getMode())
&& a.getSpec().getPadding().equals(alg.getPadding())) {
valid = true;
break;
}
}
if (!valid) {
throw new IllegalArgumentException(
"Invalid digest/cipher combination.");
}
setCipher(alg);
generator = new PBKDF1KeyGenerator(digest, params.getSalt(),
params.getIterationCount());
}
/** {@inheritDoc} */
protected void initCipher(final char[] password) {
final byte[] derivedKey = generator.generate(password, DKEY_BIT_LENGTH);
final byte[] keyBytes = new byte[KEY_LENGTH];
System.arraycopy(derivedKey, 0, keyBytes, 0, KEY_LENGTH);
cipher.setKey(new SecretKeySpec(keyBytes, cipher.getAlgorithm()));
if (!cipher.hasIV()) {
// Use the generated IV value
final byte[] ivBytes = new byte[IV_LENGTH];
System.arraycopy(derivedKey, KEY_LENGTH, ivBytes, 0, IV_LENGTH);
cipher.setIV(ivBytes);
}
}
} | mit |
Team254/FRC-2015 | src/com/team254/frc2015/subsystems/MotorPeacock.java | 2044 | package com.team254.frc2015.subsystems;
import com.team254.frc2015.subsystems.controllers.TimedOpenLoopController;
import com.team254.lib.util.*;
public class MotorPeacock extends Subsystem implements Loopable {
CheesySpeedController m_left_motor;
CheesySpeedController m_right_motor;
Controller m_controller = null;
public static final boolean s_using_peacock = true;
public MotorPeacock(CheesySpeedController left_motor, CheesySpeedController right_motor) {
super("MotorPeacock");
m_left_motor = left_motor;
m_right_motor = right_motor;
}
public void setUnsafeLeftRightPower(double left, double right) {
// left positive down
// right negative down
// input positive down
if (s_using_peacock) {
m_left_motor.set(left);
m_right_motor.set(right);
} else {
m_left_motor.set(0);
m_right_motor.set(0);
}
}
public synchronized void setPowerTimeSetpoint(double start_power, double time_start_power, double end_power, double time_to_decel) {
setUnsafeLeftRightPower(start_power, start_power); // power immediately!
m_controller = new TimedOpenLoopController(start_power, time_start_power, end_power, time_to_decel);
}
public synchronized void disableControlLoop() {
m_controller = null;
setUnsafeLeftRightPower(0, 0);
}
public void setOpenLoop(double left, double right) {
m_controller = null;
setUnsafeLeftRightPower(left, right);
}
@Override
public void reloadConstants() {
}
@Override
public void getState(StateHolder states) {
states.put("left_pwm", m_left_motor.get());
}
@Override
public synchronized void update() {
if (m_controller instanceof TimedOpenLoopController) {
TimedOpenLoopController c = (TimedOpenLoopController) m_controller;
double power = c.update();
setUnsafeLeftRightPower(power, power);
}
}
}
| mit |
the-james-burton/the-turbine | turbine-engine-hall/turbine-condenser/src/main/java/org/jimsey/projects/turbine/condenser/domain/indicators/volume/AccumulationDistribution.java | 1981 | /**
* The MIT License
* Copyright (c) ${project.inceptionYear} the-james-burton
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jimsey.projects.turbine.condenser.domain.indicators.volume;
import org.jimsey.projects.turbine.condenser.domain.indicators.BaseIndicator;
import org.jimsey.projects.turbine.condenser.domain.indicators.IndicatorInstance;
import eu.verdelhan.ta4j.TimeSeries;
import eu.verdelhan.ta4j.indicators.simple.ClosePriceIndicator;
import eu.verdelhan.ta4j.indicators.volume.AccumulationDistributionIndicator;
/**
* @author the-james-burton
*/
public class AccumulationDistribution extends BaseIndicator {
public AccumulationDistribution(IndicatorInstance instance, TimeSeries series, ClosePriceIndicator closePriceIndicator) {
super(instance, series, closePriceIndicator);
}
@Override
protected void init() {
validateNone();
indicator = new AccumulationDistributionIndicator(series);
}
}
| mit |
fdorothy/dinopocalypse | core/src/com/fdorothy/dinopox/Bullet.java | 422 | package com.fdorothy.dinopox;
import com.badlogic.gdx.math.Vector3;
public class Bullet {
public boolean inplay;
public Vector3 pos, dir;
Bullet() {
pos = new Vector3();
dir = new Vector3();
inplay = false;
}
void shoot(Vector3 position, Vector3 direction) {
if (!inplay) {
pos.x = position.x;
pos.y = position.y + 32.0f;
dir.set(direction);
inplay = true;
}
}
}
| mit |
fernandezpablo85/scribe-java | scribejava-apis/src/test/java/com/github/scribejava/apis/examples/Foursquare2Example.java | 3037 | package com.github.scribejava.apis.examples;
import java.util.Scanner;
import com.github.scribejava.core.builder.ServiceBuilder;
import com.github.scribejava.apis.Foursquare2Api;
import com.github.scribejava.core.model.OAuth2AccessToken;
import com.github.scribejava.core.model.OAuthRequest;
import com.github.scribejava.core.model.Response;
import com.github.scribejava.core.model.Verb;
import com.github.scribejava.core.oauth.OAuth20Service;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
public class Foursquare2Example {
private static final String PROTECTED_RESOURCE_URL
= "https://api.foursquare.com/v2/users/self/friends?oauth_token=";
private Foursquare2Example() {
}
@SuppressWarnings("PMD.SystemPrintln")
public static void main(String... args) throws IOException, InterruptedException, ExecutionException {
// Replace these with your own api key and secret
final String apiKey = "your client id";
final String apiSecret = "your client secret";
final OAuth20Service service = new ServiceBuilder(apiKey)
.apiSecret(apiSecret)
.callback("http://localhost:9000/")
.build(Foursquare2Api.instance());
final Scanner in = new Scanner(System.in);
System.out.println("=== Foursquare2's OAuth Workflow ===");
System.out.println();
// Obtain the Authorization URL
System.out.println("Fetching the Authorization URL...");
final String authorizationUrl = service.getAuthorizationUrl();
System.out.println("Got the Authorization URL!");
System.out.println("Now go and authorize ScribeJava here:");
System.out.println(authorizationUrl);
System.out.println("And paste the authorization code here");
System.out.print(">>");
final String code = in.nextLine();
System.out.println();
// Trade the Request Token and Verfier for the Access Token
System.out.println("Trading the Request Token for an Access Token...");
final OAuth2AccessToken accessToken = service.getAccessToken(code);
System.out.println("Got the Access Token!");
System.out.println("(The raw response looks like this: " + accessToken.getRawResponse() + "')");
System.out.println();
// Now let's go and ask for a protected resource!
System.out.println("Now we're going to access a protected resource...");
final OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL + accessToken.getAccessToken());
service.signRequest(accessToken, request);
final Response response = service.execute(request);
System.out.println("Got it! Lets see what we found...");
System.out.println();
System.out.println(response.getCode());
System.out.println(response.getBody());
System.out.println();
System.out.println("Thats it man! Go and build something awesome with ScribeJava! :)");
}
}
| mit |
yht-fand/cardone-platform-authority | consumer-bak/src/test/java/top/cardone/func/v1/authority/rolePermission/M0002FuncTest.java | 3283 | package top.cardone.func.v1.authority.rolePermission;
import com.google.common.base.Charsets;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import top.cardone.CardoneConsumerApplication;
import lombok.extern.log4j.Log4j2;
import lombok.val;
import org.apache.commons.io.FileUtils;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.CollectionUtils;
import top.cardone.context.ApplicationContextHolder;
import java.util.Map;
@Log4j2
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = CardoneConsumerApplication.class, value = {"spring.profiles.active=test"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class M0002FuncTest {
@Value("http://localhost:${server.port:8765}${server.servlet.context-path:}/v1/authority/rolePermission/m0002.json")
private String funcUrl;
@Value("file:src/test/resources/top/cardone/func/v1/authority/rolePermission/M0002FuncTest.func.input.json")
private Resource funcInputResource;
@Value("file:src/test/resources/top/cardone/func/v1/authority/rolePermission/M0002FuncTest.func.output.json")
private Resource funcOutputResource;
@Test
public void func() throws Exception {
if (!funcInputResource.exists()) {
FileUtils.write(funcInputResource.getFile(), "{}", Charsets.UTF_8);
}
val input = FileUtils.readFileToString(funcInputResource.getFile(), Charsets.UTF_8);
Map<String, Object> parametersMap = ApplicationContextHolder.getBean(Gson.class).fromJson(input, Map.class);
Assert.assertFalse("输入未配置", CollectionUtils.isEmpty(parametersMap));
Map<String, Object> output = Maps.newLinkedHashMap();
for (val parametersEntry : parametersMap.entrySet()) {
val body = ApplicationContextHolder.getBean(Gson.class).toJson(parametersEntry.getValue());
val headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
headers.set("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE);
headers.set("collectionStationCodeForToken", parametersEntry.getKey().split(":")[0]);
headers.set("token", ApplicationContextHolder.getBean(org.apache.shiro.authc.credential.PasswordService.class).encryptPassword(headers.get("collectionStationCodeForToken").get(0)));
val httpEntity = new HttpEntity<>(body, headers);
val json = new org.springframework.boot.test.web.client.TestRestTemplate().postForObject(funcUrl, httpEntity, String.class);
val value = ApplicationContextHolder.getBean(Gson.class).fromJson(json, Map.class);
output.put(parametersEntry.getKey(), value);
}
FileUtils.write(funcOutputResource.getFile(), ApplicationContextHolder.getBean(Gson.class).toJson(output), Charsets.UTF_8);
}
} | mit |
aurelieateba/cd-formation-072016 | pizzeria-console-objet/src/main/java/fr/pizzeria/console/PizzeriaAdminConsoleApp.java | 1597 | package fr.pizzeria.console;
import java.util.Calendar;
import java.util.ResourceBundle;
import java.util.Scanner;
import org.apache.commons.lang3.time.DateFormatUtils;
import fr.pizzeria.ihm.IhmHelper;
import fr.pizzeria.ihm.Menu;
import fr.pizzeria.model.Client;
import fr.pizzeria.model.Pizza;
import fr.pizzeria.service.Stockage;
import fr.pizzeria.service.StockageClientMap;
import fr.pizzeria.service.StockagePizzaMap;
public class PizzeriaAdminConsoleApp {
public static void main(String[] args) throws ClassNotFoundException ,InstantiationException,IllegalAccessException{
Scanner scanner = new Scanner(System.in);
ResourceBundle bundle = ResourceBundle.getBundle("application");
String classeStockagePizza = bundle.getString("stockage.pizza");
System.out.println(classeStockagePizza);
Class<? > classePizza = Class.forName(classeStockagePizza);
Stockage<Pizza> stockage = (Stockage<Pizza>) classePizza.newInstance();
Stockage<Pizza> stockagePizza = new StockagePizzaMap();
Stockage<Client> stockageClient = new StockageClientMap();
IhmHelper helper = new IhmHelper(stockagePizza, stockageClient, scanner);
//Afficher la date
Calendar calendardate = Calendar.getInstance();
DateFormatUtils.format(calendardate, "dd/MM '-' HH:mm ");
System.out.println(DateFormatUtils.format(calendardate, "dd/MM '-' HH:mm "));
// Afficher le Menu
Menu listMenu = new Menu(helper);
listMenu.start();
scanner.close();
}
}
| mit |
AgeOfWar/Telejam | src/main/java/io/github/ageofwar/telejam/inline/InlineQueryResultCachedDocument.java | 4390 | package io.github.ageofwar.telejam.inline;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import io.github.ageofwar.telejam.replymarkups.InlineKeyboardMarkup;
import io.github.ageofwar.telejam.text.Text;
import java.util.Objects;
import java.util.Optional;
/**
* Represents a link to a file stored on the Telegram servers.
* By default, this file will be sent by the user with an optional caption.
* Alternatively, you can use {@link #inputMessageContent} to send a message with
* the specified content instead of the file.
*
* @author Michi Palazzo
*/
public class InlineQueryResultCachedDocument extends InlineQueryResult {
static final String TITLE_FIELD = "title";
static final String DOCUMENT_FILE_ID_FIELD = "document_file_id";
static final String DESCRIPTION_FIELD = "description";
static final String CAPTION_FIELD = "caption";
static final String REPLY_MARKUP_FIELD = "reply_markup";
static final String INPUT_MESSAGE_CONTENT_FIELD = "input_message_content";
static final String PARSE_MODE_FIELD = "parse_mode";
@Expose
@SerializedName(TYPE_FIELD)
static final String TYPE = "document";
@Expose
@SerializedName(PARSE_MODE_FIELD)
private static final String PARSE_MODE = "HTML";
/**
* Title for the result.
*/
@SerializedName(TITLE_FIELD)
private final String title;
/**
* A valid file identifier for the file.
*/
@SerializedName(DOCUMENT_FILE_ID_FIELD)
private final String documentFileId;
/**
* Short description of the result.
*/
@SerializedName(DESCRIPTION_FIELD)
private final String description;
/**
* Caption of the document to be sent, 0-200 characters.
*/
@SerializedName(CAPTION_FIELD)
private final String caption;
/**
* Inline keyboard attached to the message.
*/
@SerializedName(REPLY_MARKUP_FIELD)
private final InlineKeyboardMarkup replyMarkup;
/**
* Content of the message to be sent instead of the file.
*/
@SerializedName(INPUT_MESSAGE_CONTENT_FIELD)
private final InputMessageContent inputMessageContent;
public InlineQueryResultCachedDocument(String id,
String title,
String documentFileId,
String description,
Text caption,
InlineKeyboardMarkup replyMarkup,
InputMessageContent inputMessageContent) {
super(id);
this.title = Objects.requireNonNull(title);
this.documentFileId = Objects.requireNonNull(documentFileId);
this.description = description;
this.caption = caption != null ? caption.toHtmlString() : null;
this.replyMarkup = replyMarkup;
this.inputMessageContent = inputMessageContent;
}
public InlineQueryResultCachedDocument(String id, String title, String documentFileId) {
this(id, title, documentFileId, null, null, null, null);
}
/**
* Getter for property {@link #title}.
*
* @return value for property {@link #title}
*/
public String getTitle() {
return title;
}
/**
* Getter for property {@link #documentFileId}.
*
* @return value for property {@link #documentFileId}
*/
public String getDocumentFileId() {
return documentFileId;
}
/**
* Getter for property {@link #description}.
*
* @return optional value for property {@link #description}
*/
public Optional<String> getDescription() {
return Optional.ofNullable(description);
}
/**
* Getter for property {@link #caption}.
*
* @return optional value for property {@link #caption}
*/
public Optional<Text> getCaption() {
return caption != null ? Optional.of(Text.parseHtml(caption)) : Optional.empty();
}
/**
* Getter for property {@link #replyMarkup}.
*
* @return optional value for property {@link #replyMarkup}
*/
public Optional<InlineKeyboardMarkup> getReplyMarkup() {
return Optional.ofNullable(replyMarkup);
}
/**
* Getter for property {@link #inputMessageContent}.
*
* @return optional value for property {@link #inputMessageContent}
*/
public Optional<InputMessageContent> getInputMessageContent() {
return Optional.ofNullable(inputMessageContent);
}
}
| mit |
concord-consortium/energy3d | src/main/java/org/concord/energy3d/gui/PopupMenuForFloor.java | 10498 | package org.concord.energy3d.gui;
import org.concord.energy3d.model.*;
import org.concord.energy3d.scene.Scene;
import org.concord.energy3d.scene.SceneManager;
import org.concord.energy3d.undo.ChangeFloorTypeCommand;
import org.concord.energy3d.undo.ChangeRoofTypeCommand;
import org.concord.energy3d.undo.ChangeTextureCommand;
import org.concord.energy3d.util.Config;
import org.concord.energy3d.util.Util;
import javax.swing.*;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
import java.awt.*;
import java.awt.event.InputEvent;
import java.awt.event.ItemEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
class PopupMenuForFloor extends PopupMenuFactory {
private static JPopupMenu popupMenuForFloor;
static JPopupMenu getPopupMenu(final MouseEvent mouseEvent) {
if (mouseEvent.isShiftDown()) {
SceneManager.getTaskManager().update(() -> {
Scene.getInstance().pasteToPickedLocationOnFloor();
return null;
});
Scene.getInstance().setEdited(true);
return null;
}
if (popupMenuForFloor == null) {
final JMenuItem miInfo = new JMenuItem("Floor");
miInfo.setEnabled(false);
miInfo.setOpaque(true);
miInfo.setBackground(Config.isMac() ? Color.BLACK : Color.GRAY);
miInfo.setForeground(Color.WHITE);
final JMenuItem miPaste = new JMenuItem("Paste");
miPaste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, Config.isMac() ? KeyEvent.META_MASK : InputEvent.CTRL_MASK));
miPaste.addActionListener(e -> {
SceneManager.getTaskManager().update(() -> {
Scene.getInstance().pasteToPickedLocationOnFloor();
return null;
});
Scene.getInstance().setEdited(true);
});
final JMenuItem miClear = new JMenuItem("Clear");
miClear.addActionListener(event -> {
SceneManager.getTaskManager().update(() -> {
Scene.getInstance().removeAllChildren(SceneManager.getInstance().getSelectedPart());
return null;
});
Scene.getInstance().setEdited(true);
});
final JMenu typeMenu = new JMenu("Type");
final ButtonGroup typeGroup = new ButtonGroup();
final JRadioButtonMenuItem rbmiSolid = new JRadioButtonMenuItem("Solid");
rbmiSolid.addItemListener(event -> {
if (event.getStateChange() == ItemEvent.SELECTED) {
final HousePart selectedPart = SceneManager.getInstance().getSelectedPart();
if (selectedPart instanceof Floor) {
final Floor floor = (Floor) selectedPart;
SceneManager.getTaskManager().update(() -> {
final ChangeFloorTypeCommand c = new ChangeFloorTypeCommand(floor);
floor.setType(Floor.SOLID);
floor.draw();
SceneManager.getInstance().refresh();
EventQueue.invokeLater(() -> {
Scene.getInstance().setEdited(true);
SceneManager.getInstance().getUndoManager().addEdit(c);
});
return null;
});
}
}
});
typeMenu.add(rbmiSolid);
typeGroup.add(rbmiSolid);
final JRadioButtonMenuItem rbmiTransparent = new JRadioButtonMenuItem("Transparent");
rbmiTransparent.addItemListener(event -> {
if (event.getStateChange() == ItemEvent.SELECTED) {
final HousePart selectedPart = SceneManager.getInstance().getSelectedPart();
if (selectedPart instanceof Floor) {
final Floor floor = (Floor) selectedPart;
SceneManager.getTaskManager().update(() -> {
final ChangeFloorTypeCommand c = new ChangeFloorTypeCommand(floor);
floor.setType(Floor.TRANSPARENT);
floor.draw();
SceneManager.getInstance().refresh();
EventQueue.invokeLater(() -> {
Scene.getInstance().setEdited(true);
SceneManager.getInstance().getUndoManager().addEdit(c);
});
return null;
});
}
}
});
typeMenu.add(rbmiTransparent);
typeGroup.add(rbmiTransparent);
typeMenu.addMenuListener(new MenuListener() {
@Override
public void menuSelected(final MenuEvent e) {
final HousePart selectedPart = SceneManager.getInstance().getSelectedPart();
if (selectedPart instanceof Floor) {
final Floor floor = (Floor) selectedPart;
switch (floor.getType()) {
case Floor.SOLID:
Util.selectSilently(rbmiSolid, true);
break;
case Floor.TRANSPARENT:
Util.selectSilently(rbmiTransparent, true);
break;
}
}
}
@Override
public void menuDeselected(final MenuEvent e) {
typeMenu.setEnabled(true);
}
@Override
public void menuCanceled(final MenuEvent e) {
typeMenu.setEnabled(true);
}
});
final JMenu textureMenu = new JMenu("Texture");
final ButtonGroup textureGroup = new ButtonGroup();
final JRadioButtonMenuItem rbmiTextureNone = createTextureMenuItem(Floor.TEXTURE_NONE, null);
final JRadioButtonMenuItem rbmiTextureEdge = createTextureMenuItem(Floor.TEXTURE_EDGE, null);
final JRadioButtonMenuItem rbmiTexture01 = createTextureMenuItem(Floor.TEXTURE_01, "icons/floor_01.png");
textureGroup.add(rbmiTextureNone);
textureGroup.add(rbmiTextureEdge);
textureGroup.add(rbmiTexture01);
textureMenu.add(rbmiTextureNone);
textureMenu.add(rbmiTextureEdge);
textureMenu.addSeparator();
textureMenu.add(rbmiTexture01);
textureMenu.addMenuListener(new MenuListener() {
@Override
public void menuSelected(final MenuEvent e) {
final HousePart selectedPart = SceneManager.getInstance().getSelectedPart();
if (!(selectedPart instanceof Floor)) {
return;
}
final Floor floor = (Floor) selectedPart;
switch (floor.getTextureType()) {
case Floor.TEXTURE_EDGE:
Util.selectSilently(rbmiTextureEdge, true);
break;
case Floor.TEXTURE_NONE:
Util.selectSilently(rbmiTextureNone, true);
break;
case Floor.TEXTURE_01:
Util.selectSilently(rbmiTexture01, true);
break;
default:
textureGroup.clearSelection();
}
}
@Override
public void menuDeselected(final MenuEvent e) {
textureMenu.setEnabled(true);
}
@Override
public void menuCanceled(final MenuEvent e) {
textureMenu.setEnabled(true);
}
});
popupMenuForFloor = createPopupMenu(false, false, () -> {
final HousePart copyBuffer = Scene.getInstance().getCopyBuffer();
miPaste.setEnabled(copyBuffer instanceof SolarPanel || copyBuffer instanceof Rack || copyBuffer instanceof Human);
});
popupMenuForFloor.add(miPaste);
popupMenuForFloor.add(miClear);
popupMenuForFloor.addSeparator();
popupMenuForFloor.add(typeMenu);
popupMenuForFloor.add(textureMenu);
popupMenuForFloor.add(colorAction);
}
return popupMenuForFloor;
}
private static JRadioButtonMenuItem createTextureMenuItem(final int type, final String imageFile) {
final JRadioButtonMenuItem m;
if (type == HousePart.TEXTURE_NONE) {
m = new JRadioButtonMenuItem("No Texture");
} else if (type == HousePart.TEXTURE_EDGE) {
m = new JRadioButtonMenuItem("Edge Texture");
} else {
m = new JRadioButtonMenuItem(new ImageIcon(MainPanel.class.getResource(imageFile)));
m.setText("Texture #" + type);
}
m.addItemListener(e -> {
if (e.getStateChange() == ItemEvent.SELECTED) {
final HousePart selectedPart = SceneManager.getInstance().getSelectedPart();
if (!(selectedPart instanceof Floor)) {
return;
}
final Floor floor = (Floor) selectedPart;
SceneManager.getTaskManager().update(() -> {
final ChangeTextureCommand c = new ChangeTextureCommand(floor);
floor.setTextureType(type);
floor.draw();
SceneManager.getInstance().refresh();
EventQueue.invokeLater(() -> {
Scene.getInstance().setEdited(true);
if (MainPanel.getInstance().getEnergyButton().isSelected()) {
MainPanel.getInstance().getEnergyButton().setSelected(false);
}
SceneManager.getInstance().getUndoManager().addEdit(c);
});
return null;
});
}
});
return m;
}
} | mit |
vsvankhede/meets-android | meets/src/main/java/com/theagilemonkeys/meets/magento/methods/ShoppingCartPaymentList.java | 494 | package com.theagilemonkeys.meets.magento.methods;
import com.theagilemonkeys.meets.magento.SoapApiMethod;
import com.theagilemonkeys.meets.models.base.MeetsFactory;
/**
* Android Meets SDK
* Original work Copyright (c) 2014 [TheAgileMonkeys]
*
* @author Álvaro López Espinosa
*/
public class ShoppingCartPaymentList extends SoapApiMethod {
public ShoppingCartPaymentList() {
super(MeetsFactory.get().getApiMethodCollectionResponseClasses().paymentMethodsList());
}
}
| mit |
dbermbach/web-api-bench | src/de/tuberlin/ise/dbe/pingability/Starter.java | 3043 | /**
*
*/
package de.tuberlin.ise.dbe.pingability;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* @author Dave
*
*/
public class Starter {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
GlobalErrorLogger.open();
if (args.length < 4) {
System.out
.println("Start with location of config files as parameters: 1) ping 2) http get 3) https get 4) cipherscan");
return;
}
System.out.println("Starting IsAliveServer");
IsAliveServer.startServer();
List<String> pingTargets = readConfigFile(args[0]);
List<String> httpTargets = readConfigFile(args[1]);
List<String> httpsTargets = readConfigFile(args[2]);
List<String> cipherscanTargets = readConfigFile(args[3]);
ArrayList<PingRunner> pingRunners = new ArrayList<>();
ArrayList<HttpGetRunner> httpGetRunners = new ArrayList<>();
ArrayList<HttpsGetRunner> httpsGetRunners = new ArrayList<>();
CipherscanRunner cipherscanrunner = new CipherscanRunner(
cipherscanTargets);
new Thread(cipherscanrunner).start();
Thread.sleep(60000);
for (String target : pingTargets) {
PingRunner pr = new PingRunner(target);
new Thread(pr).start();
pingRunners.add(pr);
}
Thread.sleep(60000);
for (String target : httpTargets) {
HttpGetRunner hgr = new HttpGetRunner(target);
new Thread(hgr).start();
httpGetRunners.add(hgr);
}
Thread.sleep(60000);
for (String target : httpsTargets) {
HttpsGetRunner hgr = new HttpsGetRunner(target);
new Thread(hgr).start();
httpsGetRunners.add(hgr);
}
System.out.println("Benchmarks are running now.");
System.out.println("Type \"exit\" to terminate.");
Scanner scan = new Scanner(System.in);
while (!scan.nextLine().equals("exit")) {
System.out.println("Type \"exit\" to terminate.");
}
for (PingRunner pr : pingRunners)
pr.terminate();
for (HttpGetRunner hgr : httpGetRunners)
hgr.terminate();
for (HttpsGetRunner hgr : httpsGetRunners)
hgr.terminate();
cipherscanrunner.terminate();
System.out
.println("All Runners have been asked to terminate, waiting for 15s now...");
GlobalErrorLogger.close();
try {
Thread.sleep(15000);
} catch (InterruptedException e) {
}
PingCSVLogger.LOGGER.terminate();
HttpGetCSVLogger.LOGGER.terminate();
HttpsGetCSVLogger.LOGGER.terminate();
scan.close();
IsAliveServer.stopServer();
System.out.println("Byebye.");
}
private static List<String> readConfigFile(String filename) {
List<String> result = new ArrayList<>();
try {
BufferedReader br = new BufferedReader(new FileReader(filename));
String line;
while ((line = br.readLine()) != null) {
if (!(line.trim().length() == 0||line.trim().startsWith("#"))) {
result.add(line.trim());
}
}
br.close();
} catch (Exception e) {
System.out.println("Could not read config file " + filename
+ ", terminating now:\n" + e);
System.exit(-1);
}
return result;
}
}
| mit |
cuongdtnguyen/wpi-bannerweb | app/src/main/java/com/cuongnd/wpibannerweb/simplepage/MailboxPage.java | 3619 | package com.cuongnd.wpibannerweb.simplepage;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.cuongnd.wpibannerweb.ConnectionManager;
import com.cuongnd.wpibannerweb.R;
import com.cuongnd.wpibannerweb.helper.Utils;
import org.json.JSONException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
/**
* Represents the Mailbox page model.
*
* @author Cuong Nguyen
*/
public class MailboxPage extends SimplePage {
public static final String PAGE_NAME = MailboxPage.class.getSimpleName();
public static final String JSON_BOX = "box";
public static final String JSON_NUM1 = "num1";
public static final String JSON_NUM2 = "num2";
public static final String JSON_NUM3 = "num3";
@Override
public String getName() {
return PAGE_NAME;
}
@Override
public int getLayoutResource() {
return R.layout.fragment_dashboard_card_mailbox;
}
@Override
public String getUrl() {
return "https://bannerweb.wpi.edu/pls/prod/hwwkboxs.P_ViewBoxs";
}
@Override
public boolean dataLoaded() {
return mData.has(JSON_BOX);
}
/**
* Parses a HTML string representing the Mailbox page.
*
* @param html the HTML string to be parsed
* @throws NullPointerException
*/
@Override
public void parse(String html) {
Document doc = Jsoup.parse(html, ConnectionManager.BASE_URI);
Element body = doc.body();
Element boxE1 = body.getElementsContainingOwnText("You have been assigned").first();
Element boxE2 = boxE1.getElementsByTag("B").first();
String box = boxE2.text();
Elements steps = body.getElementsContainingOwnText("Rotate the knob");
String num1 = "";
String num2 = "";
String num3 = "";
if (steps != null && steps.size() >= 3) {
Elements step1 = steps.get(0).getElementsByTag("B");
num1 = step1.get(1).text();
Elements step2 = steps.get(1).getElementsByTag("B");
num2 = step2.get(1).text();
Elements step3 = steps.get(2).getElementsByTag("B");
num3 = step3.get(1).text();
}
try {
mData.put(JSON_BOX, box)
.put(JSON_NUM1, num1)
.put(JSON_NUM2, num2)
.put(JSON_NUM3, num3);
} catch (JSONException e) {
Log.e(PAGE_NAME, "JSON exception occurred!", e);
}
}
/**
* Updates the view hierarchy that displays the Mailbox page.
*
* @param context the Context of the application
* @param v the view hierarchy to be updated.
*/
@Override
public void updateView(Context context, View v) {
try {
TextView text = (TextView) v.findViewById(R.id.text_box);
text.setText(mData.getString(JSON_BOX));
text = (TextView) v.findViewById(R.id.text_step1);
text.setText(mData.getString(JSON_NUM1));
text = (TextView) v.findViewById(R.id.text_step2);
text.setText(mData.getString(JSON_NUM2));
text = (TextView) v.findViewById(R.id.text_step3);
text.setText(mData.getString(JSON_NUM3));
} catch (JSONException e) {
Log.e(PAGE_NAME, "Cannot find data!");
} catch (NullPointerException e) {
Log.e(PAGE_NAME, "Cannot update view!", e);
}
}
}
| mit |
MetacoSA/metaco-java-client | src/main/java/com/metaco/api/MetacoClient.java | 8264 | package com.metaco.api;
import com.metaco.api.contracts.*;
import com.metaco.api.exceptions.MetacoClientException;
import java.util.List;
public interface MetacoClient {
/**
* Register an account on Metaco
* Sends an SMS to the provided phone number
*
* If you are a wallet registering accounts for your clients, don't forget to set the provider_id with your Name/ID.
*
* If you are in debug mode, this request will return a HTTP header X-Metaco-DebugData with the validation code, it won't be send by SMS
*
* @return The initial account settings
* @throws MetacoClientException
* @see <a href="http://docs.metaco.apiary.io/#reference/account/account-management/register-an-account">Online Documentation</a>
*/
AccountRegistrationResult registerAccount(RegisterAccountRequest request) throws MetacoClientException;
/**
* Requires Authentication
* Return the details of an account (API Id, KYC Status and remaining trading amount)
*
* @return The account details
* @throws MetacoClientException
* @see <a href="http://docs.metaco.apiary.io/#reference/account/account-management/get-account-status">Online Documentation</a>
*/
AccountStatus getAccountStatus() throws MetacoClientException;
/**
* Requires Authentication
* Validate the authenticated account, throws an exception if there is an error
*
* @throws MetacoClientException
* @see <a href="http://docs.metaco.apiary.io/#reference/account/confirm-a-registration/confirm-a-phone-number">Online Documentation</a>
*/
void confirmPhoneNumber(ValidateAccountRequest request) throws MetacoClientException;
/**
* Returns all the available Assets and their details
*
* @return The assets array
* @throws MetacoClientException
* @see <a href="http://docs.metaco.apiary.io/#reference/assets/assets-list/list-all-assets">Online Documentation</a>
*/
Asset[] getAssets() throws MetacoClientException;
/**
* Returns the selected Asset if it exists and its details
*
* @return The asset object
* @throws MetacoClientException
* @see <a href="http://docs.metaco.apiary.io/#reference/assets/asset-information/retrieve-an-asset">Online Documentation</a>
*/
Asset getAsset(String ticker) throws MetacoClientException;
/**
* Returns the history for all the available assets according to the given criteria
*
* @return The history object
* @throws MetacoClientException
* @see <a href="http://docs.metaco.apiary.io/#reference/assets/assets-history/retrieve-history-of-all-assets">Online Documentation</a>
*/
AssetsHistoryResult getAssetsHistory(HistoryCriteria criteria) throws MetacoClientException;
/**
* Returns the history for the provided assets according to the given criteria
* Assets must be given using this format : USD,XAU,etc..
*
* @return The history object
* @throws MetacoClientException
* @see <a href="http://docs.metaco.apiary.io/#reference/assets/assets-history/retrieve-history-of-all-assets">Online Documentation</a>
*/
AssetsHistoryResult getAssetsHistory(HistoryCriteria criteria, List<String> tickers) throws MetacoClientException;
/**
* Requires Authentication
* Create an order using the provided parameters
* This order will be processed in our system
* It will require your signature later when the trade state will be Signing
*
* @throws MetacoClientException
* @see <a href="http://docs.metaco.apiary.io/#reference/orders/orders-management/request-an-order">Online Documentation</a>
*/
Order createOrder(NewOrder createOrder) throws MetacoClientException;
/**
* Requires Authentication
* Returns the user's orders, you will get the 500 first results
*
* @return The orders array
* @throws MetacoClientException
* @see <a href="http://docs.metaco.apiary.io/#reference/orders/orders-management/list-all-orders">Online Documentation</a>
*/
OrderResultPage getOrders() throws MetacoClientException;
/**
* Requires Authentication
* Returns the user's orders, according to the pageCriteria settings (the page size is limited to 500)
*
* @return The orders array
* @throws MetacoClientException
* @see <a href="http://docs.metaco.apiary.io/#reference/orders/orders-management/list-all-orders">Online Documentation</a>
*/
OrderResultPage getOrders(PageCriteria pageCriteria) throws MetacoClientException;
/**
* Requires Authentication
* Returns the specified user's order
*
* @return The order object
* @throws MetacoClientException
* @see <a href="http://docs.metaco.apiary.io/#reference/orders/order-information/retreive-an-order">Online Documentation</a>
*/
Order getOrder(String id) throws MetacoClientException;
/**
* Requires Authentication
* Submit a signed order
* You have to sign each of your inputs of the selected order (you will get those details by fetching the orders)
* Then encode the transaction in hexadecimal and send it here
*
* @throws MetacoClientException
* @see <a href="http://docs.metaco.apiary.io/#reference/orders/order-information/submit-a-signed-order">Online Documentation</a>
*/
Order submitSignedOrder(String id, RawTransaction rawTransaction) throws MetacoClientException;
/**
* Requires Authentication
* Cancel the specified order
*
* @throws MetacoClientException
* @see <a href="http://docs.metaco.apiary.io/#reference/orders/order-information/cancel-an-order">Online Documentation</a>
*/
void cancelOrder(String id) throws MetacoClientException;
/**
* Requires Authentication
* Create a Transaction using the provided parameters
*
* @throws MetacoClientException
* @see <a href="http://docs.metaco.apiary.io/#reference/transactions/raw-transaction/get-a-raw-transaction">Online Documentation</a>
*/
TransactionToSign createTransaction(NewTransaction newTransaction) throws MetacoClientException;
/**
* Requires Authentication
* Submit a signed transaction
* You have to sign each of your inputs of the selected transaction (you will get those details when creating the transaction through Metaco)
* Then encode the transaction in hexadecimal and send it here
*
* @throws MetacoClientException
* @see <a href="http://docs.metaco.apiary.io/#reference/transactions/transaction-broadcast/broadcast-a-transaction">Online Documentation</a>
*/
TransactionBroadcastResult broadcastTransaction(RawTransaction rawTransaction) throws MetacoClientException;
/**
* Requires Authentication
* Returns the current wallet state
* The transaction history is paginated, you will get the 500 first results
* Contains the current balances, the values and the transaction history
*
* @throws MetacoClientException
* @see <a href="http://docs.metaco.apiary.io/#reference/transactions/transaction-broadcast/fetch-wallet-information">Online Documentation</a>
*/
WalletDetails getWalletDetails(String address) throws MetacoClientException;
/**
* Requires Authentication
* Returns the current wallet state
* The transaction history is paginated, you can choose your page using the pageCriteria parameter (the page size is limited to 500)
* Contains the current balances, the values and the transaction history
*
* @throws MetacoClientException
* @see <a href="http://docs.metaco.apiary.io/#reference/transactions/transaction-broadcast/fetch-wallet-information">Online Documentation</a>
*/
WalletDetails getWalletDetails(String address, PageCriteria pageCriteria) throws MetacoClientException;
/**
* For testing purposes only
* On some requests, when you use the TestingMode of the client, you will get a DebugData, which will simplify the testing of the API and the client
* As an example, a debugData could be the fake validationCode when your register an account.
*/
String getLatestDebugData();
}
| mit |
archimatetool/archi | com.archimatetool.hammer/src/com/archimatetool/hammer/validation/Validator.java | 7095 | /**
* This program and the accompanying materials
* are made available under the terms of the License
* which accompanies this distribution in the file LICENSE.txt
*/
package com.archimatetool.hammer.validation;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.jface.preference.IPreferenceStore;
import com.archimatetool.hammer.ArchiHammerPlugin;
import com.archimatetool.hammer.preferences.IPreferenceConstants;
import com.archimatetool.hammer.validation.checkers.DuplicateElementChecker;
import com.archimatetool.hammer.validation.checkers.EmptyViewsChecker;
import com.archimatetool.hammer.validation.checkers.IChecker;
import com.archimatetool.hammer.validation.checkers.InvalidRelationsChecker;
import com.archimatetool.hammer.validation.checkers.JunctionsChecker;
import com.archimatetool.hammer.validation.checkers.NestedElementsChecker;
import com.archimatetool.hammer.validation.checkers.UnusedElementsChecker;
import com.archimatetool.hammer.validation.checkers.UnusedRelationsChecker;
import com.archimatetool.hammer.validation.checkers.ViewpointChecker;
import com.archimatetool.hammer.validation.issues.AdviceCategory;
import com.archimatetool.hammer.validation.issues.AdviceType;
import com.archimatetool.hammer.validation.issues.ErrorType;
import com.archimatetool.hammer.validation.issues.ErrorsCategory;
import com.archimatetool.hammer.validation.issues.IIssue;
import com.archimatetool.hammer.validation.issues.IIssueCategory;
import com.archimatetool.hammer.validation.issues.OKType;
import com.archimatetool.hammer.validation.issues.WarningType;
import com.archimatetool.hammer.validation.issues.WarningsCategory;
import com.archimatetool.model.IArchimateDiagramModel;
import com.archimatetool.model.IArchimateElement;
import com.archimatetool.model.IArchimateModel;
import com.archimatetool.model.IArchimateRelationship;
/**
* Validator
*
* @author Phillip Beauvoir
*/
public class Validator {
private IArchimateModel fModel;
private List<IArchimateElement> fElements;
private List<IArchimateRelationship> fRelations;
private List<IArchimateDiagramModel> fViews;
private List<ErrorType> fErrorList;
private List<WarningType> fWarningList;
private List<AdviceType> fAdviceList;
public Validator(IArchimateModel model) {
fModel = model;
}
/**
* @return The list of Issue Categories and Issues
*/
public List<Object> validate() {
if(fModel == null) {
return null;
}
// Collect interesting objects
fElements = new ArrayList<IArchimateElement>();
fRelations = new ArrayList<IArchimateRelationship>();
fViews = new ArrayList<IArchimateDiagramModel>();
for(Iterator<EObject> iter = fModel.eAllContents(); iter.hasNext();) {
EObject eObject = iter.next();
if(eObject instanceof IArchimateRelationship) {
fRelations.add((IArchimateRelationship)eObject);
}
else if(eObject instanceof IArchimateElement) {
fElements.add((IArchimateElement)eObject);
}
else if(eObject instanceof IArchimateDiagramModel) {
fViews.add((IArchimateDiagramModel)eObject);
}
}
// Analyse
List<Object> result = new ArrayList<Object>();
fErrorList = new ArrayList<ErrorType>();
fWarningList = new ArrayList<WarningType>();
fAdviceList = new ArrayList<AdviceType>();
// ------------------ Checkers -----------------------------
IPreferenceStore store = ArchiHammerPlugin.INSTANCE.getPreferenceStore();
// Invalid Relations
if(store.getBoolean(IPreferenceConstants.PREFS_HAMMER_CHECK_INVALID_RELATIONS)) {
collectIssues(new InvalidRelationsChecker(getArchimateRelationships()));
}
// Unused Elements
if(store.getBoolean(IPreferenceConstants.PREFS_HAMMER_CHECK_UNUSED_ELEMENTS)) {
collectIssues(new UnusedElementsChecker(getArchimateElements()));
}
// Unused Relations
if(store.getBoolean(IPreferenceConstants.PREFS_HAMMER_CHECK_UNUSED_RELATIONS)) {
collectIssues(new UnusedRelationsChecker(getArchimateRelationships()));
}
// Empty Views
if(store.getBoolean(IPreferenceConstants.PREFS_HAMMER_CHECK_EMPTY_VIEWS)) {
collectIssues(new EmptyViewsChecker(getArchimateViews()));
}
// Components in wrong Viewpoints
if(store.getBoolean(IPreferenceConstants.PREFS_HAMMER_CHECK_VIEWPOINT)) {
collectIssues(new ViewpointChecker(getArchimateViews()));
}
// Nested elements
if(store.getBoolean(IPreferenceConstants.PREFS_HAMMER_CHECK_NESTING)) {
collectIssues(new NestedElementsChecker(getArchimateViews()));
}
// Possible Duplicates
if(store.getBoolean(IPreferenceConstants.PREFS_HAMMER_CHECK_DUPLICATE_ELEMENTS)) {
collectIssues(new DuplicateElementChecker(getArchimateElements()));
}
// Junctions
if(store.getBoolean(IPreferenceConstants.PREFS_HAMMER_CHECK_JUNCTIONS)) {
collectIssues(new JunctionsChecker(getArchimateElements()));
}
// ----------------------------------------------------------
if(!fErrorList.isEmpty()) {
IIssueCategory category = new ErrorsCategory(fErrorList);
result.add(category);
}
if(!fWarningList.isEmpty()) {
IIssueCategory category = new WarningsCategory(fWarningList);
result.add(category);
}
if(!fAdviceList.isEmpty()) {
IIssueCategory category = new AdviceCategory(fAdviceList);
result.add(category);
}
if(result.isEmpty()) {
result.add(new OKType());
}
return result;
}
void collectIssues(IChecker checker) {
for(IIssue issue : checker.getIssues()) {
if(issue instanceof ErrorType) {
fErrorList.add((ErrorType)issue);
}
if(issue instanceof WarningType) {
fWarningList.add((WarningType)issue);
}
if(issue instanceof AdviceType) {
fAdviceList.add((AdviceType)issue);
}
}
}
public IArchimateModel getModel() {
return fModel;
}
public List<IArchimateElement> getArchimateElements() {
return new ArrayList<IArchimateElement>(fElements); // copy
}
public List<IArchimateRelationship> getArchimateRelationships() {
return new ArrayList<IArchimateRelationship>(fRelations); // copy
}
public List<IArchimateDiagramModel> getArchimateViews() {
return new ArrayList<IArchimateDiagramModel>(fViews); // copy
}
}
| mit |
wolfgangimig/joa | java/joa/src-gen/com/wilutions/mslib/office/impl/GridLinesImpl.java | 2544 | /* ** GENEREATED FILE - DO NOT MODIFY ** */
package com.wilutions.mslib.office.impl;
import com.wilutions.com.*;
@SuppressWarnings("all")
@CoClass(guid="{C09B8E4E-A463-DB41-5DAE-69E7A5F7FCBC}")
public class GridLinesImpl extends Dispatch implements com.wilutions.mslib.office.GridLines {
@DeclDISPID(110) public String getName() throws ComException {
final Object obj = this._dispatchCall(110,"Name", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
return (String)obj;
}
@DeclDISPID(235) public Object Select() throws ComException {
final Object obj = this._dispatchCall(235,"Select", DISPATCH_METHOD,null);
if (obj == null) return null;
return (Object)obj;
}
@DeclDISPID(150) public IDispatch getParent() throws ComException {
final Object obj = this._dispatchCall(150,"Parent", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
return (IDispatch)obj;
}
@DeclDISPID(128) public com.wilutions.mslib.office.IMsoBorder getBorder() throws ComException {
final Object obj = this._dispatchCall(128,"Border", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
return Dispatch.as(obj, com.wilutions.mslib.office.impl.IMsoBorderImpl.class);
}
@DeclDISPID(117) public Object Delete() throws ComException {
final Object obj = this._dispatchCall(117,"Delete", DISPATCH_METHOD,null);
if (obj == null) return null;
return (Object)obj;
}
@DeclDISPID(1610743813) public com.wilutions.mslib.office.IMsoChartFormat getFormat() throws ComException {
final Object obj = this._dispatchCall(1610743813,"Format", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
return Dispatch.as(obj, com.wilutions.mslib.office.impl.IMsoChartFormatImpl.class);
}
@DeclDISPID(148) public IDispatch getApplication() throws ComException {
final Object obj = this._dispatchCall(148,"Application", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
return (IDispatch)obj;
}
@DeclDISPID(149) public Integer getCreator() throws ComException {
final Object obj = this._dispatchCall(149,"Creator", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
return (Integer)obj;
}
public GridLinesImpl(String progId) throws ComException {
super(progId, "{000C1725-0000-0000-C000-000000000046}");
}
protected GridLinesImpl(long ndisp) {
super(ndisp);
}
public String toString() {
return "[GridLinesImpl" + super.toString() + "]";
}
}
| mit |
jefryhdz/Lab3_Colaboracion | Lab3_JEfryHernandez_DElmerESpinal/src/lab3_jefryhernandez_delmerespinal/Dragones.java | 755 | /*
* 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 lab3_jefryhernandez_delmerespinal;
/**
*
* @author Jefry Hernandez
*/
public class Dragones extends Bestia{
private double longitud;
public Dragones(double logitud, int garra, String veneno, int vida) {
super(garra, veneno, vida);
this.longitud = logitud;
}
public double getLongitud() {
return longitud;
}
public void setLongitud(double longitud) {
this.longitud = longitud;
}
@Override
public String toString() {
return "Dragones{" + "longitud=" + longitud + '}';
}
}
| mit |
sebastian-janisch/skill-view-core | src/test/java/org/sjanisch/skillview/core/analysis/impl/ContributionAnalysisImplTest.java | 18476 | package org.sjanisch.skillview.core.analysis.impl;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.number.IsCloseTo.*;
import static org.junit.Assert.assertThat;
import java.time.Instant;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.Test;
import org.sjanisch.skillview.core.analysis.api.ContributionScore;
import org.sjanisch.skillview.core.analysis.api.ContributionScorerDefinition;
import org.sjanisch.skillview.core.analysis.api.ContributionScorerDefinitions;
import org.sjanisch.skillview.core.analysis.api.ContributorUniverse;
import org.sjanisch.skillview.core.analysis.api.DetailedContributionScore;
import org.sjanisch.skillview.core.analysis.api.ScoreOriginator;
import org.sjanisch.skillview.core.analysis.api.SkillTag;
import org.sjanisch.skillview.core.analysis.api.Weighting;
import org.sjanisch.skillview.core.analysis.api.WeightingScheme;
import org.sjanisch.skillview.core.contribution.api.Contributor;
import org.sjanisch.skillview.core.contribution.api.ContributionId;
import org.sjanisch.skillview.core.contribution.api.Project;
/**
*
* @author sebastianjanisch
*
*/
public class ContributionAnalysisImplTest {
@Test
public void testAllMethods_EmptyAnalysis_ExpectEmptyResults() {
ContributionAnalysisImpl analysis = new ContributionAnalysisImpl(Collections.emptySet(),
WeightingScheme.of(Collections.emptySet()), ContributionScorerDefinitions.of(Collections.emptySet()), contributorUniverse());
assertThat(analysis.getStartTime().isPresent(), is(false));
assertThat(analysis.getEndTime().isPresent(), is(false));
assertThat(analysis.getScores().isEmpty(), is(true));
assertThat(analysis.getScores(DetailedContributionScore::getContributor).isEmpty(), is(true));
assertThat(analysis.getNormalisedScores(DetailedContributionScore::getContributor).isEmpty(), is(true));
}
@Test
public void testGetStartEndTime_GivenScores_ExpectMinAndMax() {
Instant min = Instant.now().minusSeconds(60);
Instant max = Instant.now();
DetailedContributionScore score1 = createScore("JAVA", 5.0, min, "SkillView", "sjanisch", "O1");
DetailedContributionScore score2 = createScore("JAVA", 1.0, max, "SkillView", "sjanisch", "O1");
HashSet<DetailedContributionScore> scores = new HashSet<>(Arrays.asList(score1, score2));
WeightingScheme weightingScheme = singleWeightingScheme("JAVA", "O1");
ContributionScorerDefinitions contributionScorerDefinitions = singleContributionScorer("JAVA", "O1", 0.0);
ContributionAnalysisImpl analysis = new ContributionAnalysisImpl(scores, weightingScheme,
contributionScorerDefinitions, contributorUniverse("sjanisch"));
assertThat(analysis.getStartTime().isPresent(), is(true));
assertThat(analysis.getEndTime().isPresent(), is(true));
assertThat(analysis.getStartTime().get(), equalTo(min));
assertThat(analysis.getEndTime().get(), equalTo(max));
}
@Test
public void testGetScores_GivenScores_ExpectInputScoresBack() {
DetailedContributionScore score1 = createScore("JAVA", 5.0, Instant.now(), "SkillView", "sjanisch", "O1");
DetailedContributionScore score2 = createScore("JAVA", 1.0, Instant.now(), "SkillView", "sjanisch", "O1");
HashSet<DetailedContributionScore> inputScores = new HashSet<>(Arrays.asList(score1, score2));
WeightingScheme weightingScheme = singleWeightingScheme("JAVA", "O1");
ContributionScorerDefinitions contributionScorerDefinitions = singleContributionScorer("JAVA", "O1", 0.0);
ContributionAnalysisImpl analysis = new ContributionAnalysisImpl(inputScores, weightingScheme,
contributionScorerDefinitions, contributorUniverse("sjanisch"));
Collection<DetailedContributionScore> outputScores = analysis.getScores();
assertThat(outputScores.size(), is(2));
assertThat(outputScores, hasItem(score1));
assertThat(outputScores, hasItem(score2));
}
@Test
public void testGetNormalisedScores_GivenOneScorePerOriginator_Expect0NormalisedScore() {
DetailedContributionScore score1 = createScore("JAVA", 5.0, Instant.now(), "SkillView", "sjanisch", "O1");
HashSet<DetailedContributionScore> inputScores = new HashSet<>(Arrays.asList(score1));
WeightingScheme weightingScheme = singleWeightingScheme("JAVA", "O1");
ContributionScorerDefinitions contributionScorerDefinitions = singleContributionScorer("JAVA", "O1", 0.0);
ContributionAnalysisImpl analysis = new ContributionAnalysisImpl(inputScores, weightingScheme,
contributionScorerDefinitions, contributorUniverse("sjanisch"));
Map<Contributor, Collection<ContributionScore>> normalisedScores = analysis
.getNormalisedScores(DetailedContributionScore::getContributor);
assertThat(normalisedScores.size(), is(1));
assertThat(normalisedScores.keySet(), hasItem(Contributor.of("sjanisch")));
Collection<ContributionScore> scores = normalisedScores.get(Contributor.of("sjanisch"));
assertThat(scores.size(), is(1));
ContributionScore score = scores.iterator().next();
assertThat(score.getScore().getAsDouble(), is(0.0));
assertThat(score.getSkillTag(), is(SkillTag.of("JAVA")));
}
@Test
public void testGetNormalisedScores_GivenTwoScoresForOneContributorPerOriginator_Expect0NormalisedScore() {
DetailedContributionScore score1 = createScore("JAVA", 5.0, Instant.now(), "SkillView", "sjanisch", "O1");
DetailedContributionScore score2 = createScore("JAVA", 10.0, Instant.now(), "SkillView", "sjanisch", "O1");
HashSet<DetailedContributionScore> inputScores = new HashSet<>(Arrays.asList(score1, score2));
WeightingScheme weightingScheme = singleWeightingScheme("JAVA", "O1");
ContributionScorerDefinitions contributionScorerDefinitions = singleContributionScorer("JAVA", "O1", 0.0);
ContributionAnalysisImpl analysis = new ContributionAnalysisImpl(inputScores, weightingScheme,
contributionScorerDefinitions, contributorUniverse("sjanisch"));
Map<Contributor, Collection<ContributionScore>> normalisedScores = analysis
.getNormalisedScores(DetailedContributionScore::getContributor);
assertThat(normalisedScores.size(), is(1));
assertThat(normalisedScores.keySet(), hasItem(Contributor.of("sjanisch")));
Collection<ContributionScore> scores = normalisedScores.get(Contributor.of("sjanisch"));
assertThat(scores.size(), is(1));
ContributionScore score = scores.iterator().next();
assertThat(score.getScore().getAsDouble(), is(0.0));
assertThat(score.getSkillTag(), is(SkillTag.of("JAVA")));
}
@Test
public void testGetNormalisedScores_GivenScoresForTwoContributorsPerOriginator_ExpectNormalisedScores() {
DetailedContributionScore score1 = createScore("JAVA", 5.0, Instant.now(), "SkillView", "sjanisch", "O1");
DetailedContributionScore score2 = createScore("JAVA", 10.0, Instant.now(), "SkillView", "jondoe", "O1");
HashSet<DetailedContributionScore> inputScores = new HashSet<>(Arrays.asList(score1, score2));
WeightingScheme weightingScheme = singleWeightingScheme("JAVA", "O1");
ContributionScorerDefinitions contributionScorerDefinitions = singleContributionScorer("JAVA", "O1", 0.0);
ContributionAnalysisImpl analysis = new ContributionAnalysisImpl(inputScores, weightingScheme,
contributionScorerDefinitions, contributorUniverse("sjanisch", "jondoe"));
Map<Contributor, Collection<ContributionScore>> normalisedScores = analysis
.getNormalisedScores(DetailedContributionScore::getContributor);
assertThat(normalisedScores.size(), is(2));
assertThat(normalisedScores.keySet(), hasItem(Contributor.of("sjanisch")));
assertThat(normalisedScores.keySet(), hasItem(Contributor.of("jondoe")));
Collection<ContributionScore> sjanischScores = normalisedScores.get(Contributor.of("sjanisch"));
Collection<ContributionScore> jondoeScores = normalisedScores.get(Contributor.of("jondoe"));
assertThat(sjanischScores.size(), is(1));
assertThat(jondoeScores.size(), is(1));
ContributionScore sjanischScore = sjanischScores.iterator().next();
ContributionScore jondoeScore = jondoeScores.iterator().next();
double mean = (5.0 + 10.0) / 2;
double stdDev = Math.sqrt(1 / 2.0 * (Math.pow(5.0 - mean, 2) + Math.pow(10.0 - mean, 2)));
assertThat(sjanischScore.getScore().getAsDouble(), is(closeTo((5.0 - mean) / stdDev, 1e-10)));
assertThat(jondoeScore.getScore().getAsDouble(), is(closeTo((10.0 - mean) / stdDev, 1e-10)));
}
@Test
public void testGetNormalisedScores_GivenMultipleScoresForTwoContributorsPerOriginator_ExpectSumScoresPerContributor() {
DetailedContributionScore score1 = createScore("JAVA", 1.0, Instant.now(), "SkillView", "sjanisch", "O1");
DetailedContributionScore score2 = createScore("JAVA", 4.0, Instant.now(), "SkillView", "sjanisch", "O1");
DetailedContributionScore score3 = createScore("JAVA", 12.0, Instant.now(), "SkillView", "jondoe", "O1");
DetailedContributionScore score4 = createScore("JAVA", -2.0, Instant.now(), "SkillView", "jondoe", "O1");
HashSet<DetailedContributionScore> inputScores = new HashSet<>(Arrays.asList(score1, score2, score3, score4));
WeightingScheme weightingScheme = singleWeightingScheme("JAVA", "O1");
ContributionScorerDefinitions contributionScorerDefinitions = singleContributionScorer("JAVA", "O1", 0.0);
ContributionAnalysisImpl analysis = new ContributionAnalysisImpl(inputScores, weightingScheme,
contributionScorerDefinitions, contributorUniverse("sjanisch", "jondoe"));
Map<Contributor, Collection<ContributionScore>> normalisedScores = analysis
.getNormalisedScores(DetailedContributionScore::getContributor);
assertThat(normalisedScores.size(), is(2));
assertThat(normalisedScores.keySet(), hasItem(Contributor.of("sjanisch")));
assertThat(normalisedScores.keySet(), hasItem(Contributor.of("jondoe")));
Collection<ContributionScore> sjanischScores = normalisedScores.get(Contributor.of("sjanisch"));
Collection<ContributionScore> jondoeScores = normalisedScores.get(Contributor.of("jondoe"));
assertThat(sjanischScores.size(), is(1));
assertThat(jondoeScores.size(), is(1));
ContributionScore sjanischScore = sjanischScores.iterator().next();
ContributionScore jondoeScore = jondoeScores.iterator().next();
double sjanischSum = (1.0 + 4.0);
double jondoeSum = (12.0 - 2.0);
double mean = (sjanischSum + jondoeSum) / 2;
double stdDev = Math.sqrt(1 / 2.0 * (Math.pow(sjanischSum - mean, 2) + Math.pow(jondoeSum - mean, 2)));
assertThat(sjanischScore.getScore().getAsDouble(), is(closeTo((sjanischSum - mean) / stdDev, 1e-10)));
assertThat(jondoeScore.getScore().getAsDouble(), is(closeTo((jondoeSum - mean) / stdDev, 1e-10)));
}
@Test
public void testGetNormalisedScores_GivenMultipleScoresForTwoContributorsAndMultipleOriginators_ExpectSumScoresPerContributorAndWeightedScores() {
DetailedContributionScore score1 = createScore("JAVA", 1.0, Instant.now(), "SkillView", "sjanisch", "O1");
DetailedContributionScore score2 = createScore("JAVA", 4.0, Instant.now(), "SkillView", "sjanisch", "O1");
DetailedContributionScore score3 = createScore("JAVA", 12.0, Instant.now(), "SkillView", "jondoe", "O1");
DetailedContributionScore score4 = createScore("JAVA", -2.0, Instant.now(), "SkillView", "jondoe", "O1");
DetailedContributionScore score5 = createScore("JAVA", 95.0, Instant.now(), "SkillView", "tomsmith", "O1");
DetailedContributionScore score6 = createScore("JAVA", 9.0, Instant.now(), "SkillView", "sjanisch", "O2");
DetailedContributionScore score7 = createScore("JAVA", 4.0, Instant.now(), "SkillView", "sjanisch", "O2");
DetailedContributionScore score8 = createScore("JAVA", 12.0, Instant.now(), "SkillView", "jondoe", "O2");
DetailedContributionScore score9 = createScore("JAVA", 33.0, Instant.now(), "SkillView", "jondoe", "O2");
DetailedContributionScore score10 = createScore("JAVA", 0.0, Instant.now(), "SkillView", "tomsmith", "O2");
HashSet<DetailedContributionScore> inputScores = new HashSet<>(
Arrays.asList(score1, score2, score3, score4, score5, score6, score7, score8, score9, score10));
WeightingScheme weightingScheme = twoWeightingScheme("JAVA", "O1", "O2", 0.75, 0.25);
ContributionScorerDefinitions contributionScorerDefinitions = twoContributionScorer("JAVA", "O1", "O2", 0.0,
0.0);
ContributionAnalysisImpl analysis = new ContributionAnalysisImpl(inputScores, weightingScheme,
contributionScorerDefinitions, contributorUniverse("sjanisch", "jondoe", "tomsmith"));
Map<Contributor, Collection<ContributionScore>> normalisedScores = analysis
.getNormalisedScores(DetailedContributionScore::getContributor);
assertThat(normalisedScores.size(), is(3));
assertThat(normalisedScores.keySet(), hasItem(Contributor.of("sjanisch")));
assertThat(normalisedScores.keySet(), hasItem(Contributor.of("jondoe")));
assertThat(normalisedScores.keySet(), hasItem(Contributor.of("tomsmith")));
Collection<ContributionScore> sjanischScores = normalisedScores.get(Contributor.of("sjanisch"));
Collection<ContributionScore> jondoeScores = normalisedScores.get(Contributor.of("jondoe"));
Collection<ContributionScore> tomsmithScores = normalisedScores.get(Contributor.of("tomsmith"));
assertThat(sjanischScores.size(), is(1));
assertThat(jondoeScores.size(), is(1));
assertThat(tomsmithScores.size(), is(1));
ContributionScore sjanischScore = sjanischScores.iterator().next();
ContributionScore jondoeScore = jondoeScores.iterator().next();
ContributionScore tomsmithScore = tomsmithScores.iterator().next();
double sjanischSumO1 = (1.0 + 4.0);
double sjanischSumO2 = (9.0 + 4.0);
double jondoeSumO1 = (12.0 - 2.0);
double jondoeSumO2 = (12.0 + 33.0);
double tomsmithSumO1 = 95.0;
double tomsmithSumO2 = 0.0;
double meanO1 = (sjanischSumO1 + jondoeSumO1 + tomsmithSumO1) / 3;
double stdDevO1 = Math.sqrt(1 / 3.0 * (Math.pow(sjanischSumO1 - meanO1, 2) + Math.pow(jondoeSumO1 - meanO1, 2)
+ Math.pow(tomsmithSumO1 - meanO1, 2)));
double meanO2 = (sjanischSumO2 + jondoeSumO2 + tomsmithSumO2) / 3;
double stdDevO2 = Math.sqrt(1 / 3.0 * (Math.pow(sjanischSumO2 - meanO2, 2) + Math.pow(jondoeSumO2 - meanO2, 2)
+ Math.pow(tomsmithSumO2 - meanO2, 2)));
double sjanischNormalisedO1 = (sjanischSumO1 - meanO1) / stdDevO1;
double jondoeNormalisedO1 = (jondoeSumO1 - meanO1) / stdDevO1;
double tomsmithNormalisedO1 = (tomsmithSumO1 - meanO1) / stdDevO1;
double sjanischNormalisedO2 = (sjanischSumO2 - meanO2) / stdDevO2;
double jondoeNormalisedO2 = (jondoeSumO2 - meanO2) / stdDevO2;
double tomsmithNormalisedO2 = (tomsmithSumO2 - meanO2) / stdDevO2;
double sjanischWeighted = sjanischNormalisedO1 * 0.75 + sjanischNormalisedO2 * 0.25;
double jondoeWeighted = jondoeNormalisedO1 * 0.75 + jondoeNormalisedO2 * 0.25;
double tomsmithWeighted = tomsmithNormalisedO1 * 0.75 + tomsmithNormalisedO2 * 0.25;
double weightedMean = (sjanischWeighted + jondoeWeighted + tomsmithWeighted) / 3;
double weightedStdDev = Math.sqrt(1.0 / 3 * (Math.pow(sjanischWeighted - weightedMean, 2)
+ Math.pow(jondoeWeighted - weightedMean, 2) + Math.pow(tomsmithWeighted - weightedMean, 2)));
double sjanischFinal = (sjanischWeighted - weightedMean) / weightedStdDev;
double jondoeFinal = (jondoeWeighted - weightedMean) / weightedStdDev;
double tomsmithFinal = (tomsmithWeighted - weightedMean) / weightedStdDev;
assertThat(sjanischScore.getScore().getAsDouble(), is(closeTo(sjanischFinal, 1e-10)));
assertThat(jondoeScore.getScore().getAsDouble(), is(closeTo(jondoeFinal, 1e-10)));
assertThat(tomsmithScore.getScore().getAsDouble(), is(closeTo(tomsmithFinal, 1e-10)));
}
// @formatter:off
private static DetailedContributionScore createScore(
String skillTag,
double score,
Instant scoreTime,
String project,
String contributor,
String scoreOriginator) {
ContributionScore rawScore = ContributionScore.of(SkillTag.of(skillTag), score);
return DetailedContributionScore.of(
rawScore,
scoreTime,
Project.of(project),
ContributionId.of("123"),
Contributor.of(contributor),
ScoreOriginator.of(scoreOriginator));
}
private static WeightingScheme singleWeightingScheme(String skillTag, String scoreOriginator) {
Weighting weighting = Weighting.of(SkillTag.of(skillTag),
Collections.singletonMap(ScoreOriginator.of(scoreOriginator),
1.0));
return WeightingScheme.of(Collections.singleton(weighting));
}
private static WeightingScheme twoWeightingScheme(
String skillTag,
String scoreOriginator1,
String scoreOriginator2,
double weight1,
double weight2) {
Map<ScoreOriginator, Double> weights = new HashMap<>();
weights.put(ScoreOriginator.of(scoreOriginator1), weight1);
weights.put(ScoreOriginator.of(scoreOriginator2), weight2);
Weighting weighting = Weighting.of(SkillTag.of(skillTag), weights);
return WeightingScheme.of(Collections.singleton(weighting));
}
private static ContributionScorerDefinitions singleContributionScorer(
String skillTag,
String scoreOriginator,
double neutralScore) {
ContributionScorerDefinition scorerDefinition = ContributionScorerDefinition.of(
ScoreOriginator.of(scoreOriginator),
SkillTag.of(skillTag),
neutralScore);
return ContributionScorerDefinitions.of(Collections.singleton(scorerDefinition));
}
private static ContributionScorerDefinitions twoContributionScorer(
String skillTag,
String scoreOriginator1,
String scoreOriginator2,
double neutralScore1,
double neutralScore2) {
ContributionScorerDefinition scorerDefinition1 = ContributionScorerDefinition.of(
ScoreOriginator.of(scoreOriginator1),
SkillTag.of(skillTag),
neutralScore1);
ContributionScorerDefinition scorerDefinition2 = ContributionScorerDefinition.of(
ScoreOriginator.of(scoreOriginator2),
SkillTag.of(skillTag),
neutralScore2);
return ContributionScorerDefinitions.of(Arrays.asList(scorerDefinition1, scorerDefinition2));
}
// @formatter:on
private static ContributorUniverse contributorUniverse(String... contributors) {
Set<Contributor> universe = Stream.of(contributors).map(Contributor::of).collect(Collectors.toSet());
return ContributorUniverse.of(Instant.MIN, Instant.MAX, universe);
}
}
| mit |
franlu/curso_android_uned | tema04/Ejercicio404/app/src/androidTest/java/app/uned/es/ejercicio404/ApplicationTest.java | 355 | package app.uned.es.ejercicio404;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | mit |
alv-ch/job-room | jobroom-gateway-app/src/main/java/ch/admin/seco/jobroom/JobroomApp.java | 5045 | package ch.admin.seco.jobroom;
import ch.admin.seco.jobroom.config.ApplicationProperties;
import ch.admin.seco.jobroom.config.DefaultProfileUtil;
import io.github.jhipster.config.JHipsterConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.core.Ordered;
import org.springframework.core.env.Environment;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.annotation.PostConstruct;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Collection;
@SpringBootApplication
@EnableConfigurationProperties({LiquibaseProperties.class, ApplicationProperties.class})
@EnableDiscoveryClient
@EnableZuulProxy
@EnableFeignClients
@EnableTransactionManagement(order = Ordered.HIGHEST_PRECEDENCE)
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
@EnableJpaRepositories(basePackages = "ch.admin.seco.jobroom.domain")
@EnableElasticsearchRepositories(basePackages = "ch.admin.seco.jobroom.service.search")
@EnableCaching
@EnableAsync
@EnableScheduling
public class JobroomApp {
private static final Logger log = LoggerFactory.getLogger(JobroomApp.class);
private final Environment env;
public JobroomApp(Environment env) {
this.env = env;
}
/**
* Main method, used to run the application.
*
* @param args the command line arguments
* @throws UnknownHostException if the local host name could not be resolved into an address
*/
public static void main(String[] args) throws UnknownHostException {
SpringApplication app = new SpringApplication(JobroomApp.class);
DefaultProfileUtil.addDefaultProfile(app);
Environment env = app.run(args).getEnvironment();
String protocol = "http";
if (env.getProperty("server.ssl.key-store") != null) {
protocol = "https";
}
log.info("\n----------------------------------------------------------\n\t" +
"Application '{}' is running! Access URLs:\n\t" +
"Local: \t\t{}://localhost:{}\n\t" +
"External: \t{}://{}:{}\n\t" +
"Profile(s): \t{}\n----------------------------------------------------------",
env.getProperty("spring.application.name"),
protocol,
env.getProperty("server.port"),
protocol,
InetAddress.getLocalHost().getHostAddress(),
env.getProperty("server.port"),
env.getActiveProfiles());
String configServerStatus = env.getProperty("configserver.status");
log.info("\n----------------------------------------------------------\n\t" +
"Config Server: \t{}\n----------------------------------------------------------",
configServerStatus == null ? "Not found or not setup for this application" : configServerStatus);
}
/**
* Initializes jobroom.
* <p>
* Spring profiles can be configured with a program arguments --spring.profiles.active=your-active-profile
* <p>
* You can find more information on how profiles work with JHipster on <a href="http://www.jhipster.tech/profiles/">http://www.jhipster.tech/profiles/</a>.
*/
@PostConstruct
public void initApplication() {
Collection<String> activeProfiles = Arrays.asList(env.getActiveProfiles());
if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_PRODUCTION)) {
log.error("You have misconfigured your application! It should not run " +
"with both the 'dev' and 'prod' profiles at the same time.");
}
if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_CLOUD)) {
log.error("You have misconfigured your application! It should not " +
"run with both the 'dev' and 'cloud' profiles at the same time.");
}
}
}
| mit |
lbwleon/blog | src/main/java/xyz/isnull/blog/core/service/CustomUserDetailService.java | 737 | package xyz.isnull.blog.core.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import xyz.isnull.blog.core.repository.UserRepository;
@Service
public class CustomUserDetailService implements UserDetailsService{
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
return new SecurityUser(userRepository.findByUsername(s));
}
}
| mit |
Steppschuh/PlaceTracking | App Engine/backend/src/main/java/placetracking/util/MapUtil.java | 829 | package placetracking.util;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class MapUtil {
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
return (o1.getValue()).compareTo(o2.getValue());
}
});
Map<K, V> result = new LinkedHashMap<K, V>();
for (Map.Entry<K, V> entry : list) {
result.put(entry.getKey(), entry.getValue());
}
return result;
}
} | mit |
ailyenko/JavaRush | src/com/javarush/test/level24/lesson06/home03/Util.java | 3103 | package com.javarush.test.level24.lesson06.home03;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
public class Util {
private static final Collection<Object[]> jeansArray = new LinkedList<>();
static {
jeansArray.add(new Object[]{1, Company.Levis, 34, 6, 150.0});
jeansArray.add(new Object[]{2, Company.Denim, 35, 8, 154.0});
jeansArray.add(new Object[]{3, Company.Colins, 32, 6, 120.0});
jeansArray.add(new Object[]{4, Company.CalvinKleinJeans, 31, 8, 125.0});
}
public static List<Jeans> getAllJeans() {
abstract class AbstractJeans implements Jeans {
private int length;
private int size;
private int id;
private double price;
AbstractJeans(int id, int length, int size, double price) {
this.id = id;
this.length = length;
this.size = size;
this.price = price;
}
@Override
public int getLength() {
return length;
}
@Override
public int getSize() {
return size;
}
@Override
public int getId() {
return id;
}
@Override
public double getPrice() {
return price;
}
@Override
public String toString() {
return this.getClass().getSimpleName() + "{" +
"id=" + id +
", length=" + length +
", size=" + size +
", price=" + price +
'}';
}
}
class Levis extends AbstractJeans {
private String TM;
private Levis(int id, int length, int size, double price) {
super(id, length, size, price);
}
@Override
public String getTM() {
return TM;
}
}
class Denim extends AbstractJeans {
private String TM;
private Denim(int id, int length, int size, double price) {
super(id, length, size, price);
}
@Override
public String getTM() {
return TM;
}
}
List<Jeans> allJeans = new LinkedList<>();
for (Object[] obj : getJeansArray()) {
int id = (int) obj[0];
final Company company = (Company) obj[1];
int length = (int) obj[2];
int size = (int) obj[3];
double price = (double) obj[4];
Jeans jeans;
switch (company) {
case Levis:
jeans = new Levis(id, length, size, price);
break;
case Denim:
jeans = new Denim(id, length, size, price);
break;
default:
jeans = new AbstractJeans(id, length, size, price) {
public String getTM() {
return company.fullName;
}
};
break;
}
allJeans.add(jeans);
}
return allJeans;
}
@SuppressWarnings("SameReturnValue")
private static Collection<Object[]> getJeansArray() {
return jeansArray;
}
enum Company {
Levis("Levi's"),
Denim("Denim"),
Colins("COLIN'S"),
CalvinKleinJeans("Calvin Klein Jeans");
final String fullName;
Company(String name) {
this.fullName = name;
}
}
}
| mit |
TheTacoScott/ctci-v6 | src/com/tacoscott/Main.java | 123 | package com.tacoscott;
public class Main {
public static void main(String[] args) {
// write your code here
}
}
| mit |
a-r-d/java-1-class-demos | week3-arrays/week3/src/week3/ArrayBlowUp.java | 284 | package week3;
import java.util.Arrays;
public class ArrayBlowUp {
public static void main(String[] args) {
int nums [] = new int [] {5,6,7};
System.out.println(nums.length);
nums[2] = 100;
System.out.println(Arrays.toString(nums));
nums[3] = 200;
}
}
| mit |
JeffreyFalgout/Utils | src/falgout/utils/io/SwingConsole.java | 5814 | package falgout.utils.io;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicReference;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.WindowConstants;
import com.google.inject.Inject;
import falgout.utils.swing.ConsoleEvent;
import falgout.utils.swing.ConsoleListener;
import falgout.utils.swing.JConsole;
import falgout.utils.swing.SwingUtils;
public class SwingConsole extends Console {
private final JConsole console;
@Inject
public SwingConsole() {
try {
console = SwingUtils.runOnEDT(new Callable<JConsole>() {
@Override
public JConsole call() {
JConsole console = new JConsole();
console.addConsoleListener(new ConsoleListener() {
@Override
public void textWritten(ConsoleEvent e) {
if (!e.getWriter().equals(JConsole.INPUT)) {
JConsole console = e.getSource();
Window w = SwingUtils.getParent(Window.class, console);
if (w == null) {
JFrame frame = new JFrame("Console");
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.setLocationByPlatform(true);
frame.setContentPane(new JScrollPane(console));
frame.pack();
w = frame;
}
if (!w.isVisible()) {
w.setVisible(true);
} else {
w.requestFocus();
}
}
}
});
return console;
}
});
} catch (InterruptedException | ExecutionException e) {
throw new Error(e);
}
}
public JConsole getConsole() {
return console;
}
@Override
public PrintWriter writer() {
return console.getWriter(JConsole.OUTPUT);
}
@Override
public BufferedReader reader() {
return console.getInput();
}
@Override
public char[] readPassword(final String fmt, final Object... args) {
try {
return SwingUtils.runOnEDT(new Callable<char[]>() {
@Override
public char[] call() throws Exception {
Window w = SwingUtils.getParent(Window.class, console);
final JDialog d = new JDialog(w, "Enter Password");
final AtomicReference<char[]> password = new AtomicReference<>();
final JPasswordField pass = new JPasswordField(20);
ActionListener dispose = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
d.dispose();
}
};
ActionListener updatePassword = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
password.set(pass.getPassword());
}
};
JLabel prompt = new JLabel(String.format(fmt, args));
prompt.setLabelFor(pass);
pass.addActionListener(dispose);
pass.addActionListener(updatePassword);
JPanel textField = new JPanel();
textField.add(prompt);
textField.add(pass);
JButton submit = new JButton("Submit");
submit.addActionListener(dispose);
submit.addActionListener(updatePassword);
JButton cancel = new JButton("Cancel");
cancel.addActionListener(dispose);
JPanel buttons = new JPanel();
buttons.add(submit);
buttons.add(cancel);
JPanel content = new JPanel();
content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
content.add(textField);
content.add(buttons);
d.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
d.setContentPane(content);
d.pack();
d.setResizable(false);
d.setLocationRelativeTo(w);
d.setModal(true);
d.setVisible(true);
return password.get();
}
});
} catch (InterruptedException | ExecutionException e) {
throw new Error(e);
}
}
@Override
public void flush() {}
}
| mit |
nilsschmidt1337/ldparteditor | src/org/nschmidt/ldparteditor/workbench/UserSettingState.java | 51593 | /* MIT - License
Copyright (c) 2012 - this year, Nils Schmidt
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
package org.nschmidt.ldparteditor.workbench;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicBoolean;
import org.eclipse.wb.swt.SWTResourceManager;
import org.nschmidt.ldparteditor.composite.ToolItemState;
import org.nschmidt.ldparteditor.data.GColour;
import org.nschmidt.ldparteditor.enumtype.Colour;
import org.nschmidt.ldparteditor.enumtype.LDConfig;
import org.nschmidt.ldparteditor.enumtype.Task;
import org.nschmidt.ldparteditor.enumtype.TextEditorColour;
import org.nschmidt.ldparteditor.enumtype.TextTask;
import org.nschmidt.ldparteditor.logger.NLogger;
import org.nschmidt.ldparteditor.state.KeyStateManager;
/**
* This class represents the permanent state of the application setting with
* focus on user dependent information (e.g. user name, LDraw path, ...)
*
* @author nils
*
*/
public class UserSettingState implements Serializable {
// Do not rename fields. It will break backwards compatibility! New values, which were not included in the state before, have to be initialized! (@ WorkbenchManager.loadWorkbench())
/** V1.00 */
private static final long serialVersionUID = 1L;
/** Where your part authoring folder is located. */
private String authoringFolderPath = ""; //$NON-NLS-1$
/** Where your LDraw folder is located. */
private String ldrawFolderPath = ""; //$NON-NLS-1$
/** Where your unofficial parts folder is located. */
private String unofficialFolderPath = ""; //$NON-NLS-1$
/** Your LDraw user name. */
private String ldrawUserName = ""; //$NON-NLS-1$
/** The license under you want to publish your work. */
private String license = ""; //$NON-NLS-1$
/** Your real name. */
private String realUserName = ""; //$NON-NLS-1$
/** {@code true} if the user wants to use relative paths */
private boolean usingRelativePaths = false;
/** Your colour palette. */
private List<GColour> userPalette = new ArrayList<>();
/** Your coarse move snap value */
private BigDecimal coarseMoveSnap = new BigDecimal("1"); //$NON-NLS-1$
/** Your coarse rotate snap value */
private BigDecimal coarseRotateSnap = new BigDecimal("90"); //$NON-NLS-1$
/** Your coarse scale snap value */
private BigDecimal coarseScaleSnap = new BigDecimal("2"); //$NON-NLS-1$
/** Your medium move snap value */
private BigDecimal mediumMoveSnap = new BigDecimal("0.01"); //$NON-NLS-1$
/** Your medium rotate snap value */
private BigDecimal mediumRotateSnap = new BigDecimal("11.25"); //$NON-NLS-1$
/** Your medium scale snap value */
private BigDecimal mediumScaleSnap = new BigDecimal("1.1"); //$NON-NLS-1$
/** Your fine move snap value */
private BigDecimal fineMoveSnap = new BigDecimal("0.0001"); //$NON-NLS-1$
/** Your fine rotate snap value */
private BigDecimal fineRotateSnap = BigDecimal.ONE;
/** Your fine scale snap value */
private BigDecimal fineScaleSnap = new BigDecimal("1.001"); //$NON-NLS-1$
/** Your "fuzziness factor", LDU distance below which vertices would be considered the same in 3D space. */
private BigDecimal fuzziness3D = new BigDecimal("0.001"); //$NON-NLS-1$
/** Your "fuzziness factor", "pixel" distance below which vertices would be considered the same in 2D projected space. */
private int fuzziness2D = 7;
/** Your transformation matrix precision */
private int transMatrixPrecision = 5;
/** Your coordinates precision */
private int coordsPrecision = 3;
/** {@code true} if the user wants to delete this settings */
private boolean resetOnStart = false;
/** LDConfig.ldr */
private String ldConfigPath = null;
/** {@code true} if the user wants active synchronisation with the text editor */
@SuppressWarnings("unused")
private AtomicBoolean syncWithTextEditor = new AtomicBoolean(true);
/** {@code true} if the user wants active synchronisation with the text editor */
private AtomicBoolean syncWithLpeInline = new AtomicBoolean(false);
private int iconSize = 0;
private float[] manipulatorSize = null;
private List<String> recentItems = new ArrayList<>();
private Locale locale = Locale.US;
/** {@code true} if the user has got the information that BFC certification is mandatory for the LDraw Standard Preview Mode */
private boolean bfcCertificationRequiredForLDrawMode = false;
private String[] key3DStrings = null;
private String[] key3DKeys = null;
private Task[] key3DTasks = null;
private String[] keyTextStrings = null;
private String[] keyTextKeys = null;
private TextTask[] keyTextTasks = null;
private List<ToolItemState> toolItemConfig3D = new ArrayList<>();
/** {@code true} if anti-aliasing is enabled for 3D windows */
private boolean antiAliasing = false;
/** {@code true} if the new OpenGL 3.3 engine is enabled for 3D windows */
private boolean newEngine = false;
/** {@code true} if the Vulkan engine is enabled for 3D windows */
private boolean vulkanEngine = false;
/** {@code true} if invalid shapes are allowed in the 3D editor */
private boolean allowInvalidShapes = false;
/** {@code true} if the user can translate the 3D view with the cursor */
private boolean translateViewByCursor = false;
private boolean disableMAD3D = false;
private boolean disableMADtext = false;
// I need the arrays to detect if the value was not initialised before.
// Otherwise it would be just 0 on new fields.
private float[] color16OverrideColour = null;
private float[] bfcFrontColour = null;
private float[] bfcBackColour = null;
private float[] bfcUncertifiedColour = null;
private float[] vertexColour = null;
private float[] vertexSelectedColour = null;
private float[] condlineSelectedColour = null;
private float[] lineColour = null;
private float[] meshlineColour = null;
private float[] condlineHiddenColour = null;
private float[] condlineShownColour = null;
private float[] backgroundColour = null;
private float[] light1Colour = null;
private float[] light1SpecularColour = null;
private float[] light2Colour = null;
private float[] light2SpecularColour = null;
private float[] light3Colour = null;
private float[] light3SpecularColour = null;
private float[] light4Colour = null;
private float[] light4SpecularColour = null;
private float[] manipulatorSelectedColour = null;
private float[] manipulatorInnerCircleColour = null;
private float[] manipulatorOuterCircleColour = null;
private float[] manipulatorXAxisColour = null;
private float[] manipulatorYAxisColour = null;
private float[] manipulatorZAxisColour = null;
private float[] addObjectColour = null;
private float[] originColour = null;
private float[] grid10Colour = null;
private float[] gridColour = null;
private float[] rubberBandColour = null;
private float[] textColour = null;
private float[] xAxisColour = null;
private float[] yAxisColour = null;
private float[] zAxisColour = null;
private float[] primitiveBackgroundColour = null;
private float[] primitiveSignFGColour = null;
private float[] primitiveSignBGColour = null;
private float[] primitivePlusAndMinusColour = null;
private float[] primitiveSelectedCellColour = null;
private float[] primitiveFocusedCellColour = null;
private float[] primitiveNormalCellColour = null;
private float[] primitiveCell1Colour = null;
private float[] primitiveCell2Colour = null;
private float[] primitiveCategoryCell1Colour = null;
private float[] primitiveCategoryCell2Colour = null;
private float[] primitiveEdgeColour = null;
private float[] primitiveCondlineColour = null;
private int[] lineBoxFontColour = null;
private int[] lineColourAttrFontColour = null;
private int[] lineCommentFontColour = null;
private int[] lineErrorUnderlineColour = null;
private int[] lineHighlightBackgroundColour = null;
private int[] lineHighlightSelectedBackgroundColour = null;
private int[] lineHintUnderlineColour = null;
private int[] linePrimaryFontColour = null;
private int[] lineQuadFontColour = null;
private int[] lineSecondaryFontColour = null;
private int[] lineWarningUnderlineColour = null;
private int[] textBackgroundColour = null;
private int[] textForegroundColour = null;
private int[] textForegroundHiddenColour = null;
private float[] cursor1ColourColour = null;
private float[] cursor2ColourColour = null;
private boolean syncingTabs = false;
private int textWinArr = 2;
private boolean roundX = false;
private boolean roundY = false;
private boolean roundZ = false;
private transient int openGLVersion = 20;
private boolean movingAdjacentData = false;
private double coplanarityAngleWarning = 1d;
private double coplanarityAngleError = 3d;
private double viewportScaleFactor = 1d;
private int mouseButtonLayout = 0;
private boolean invertingWheelZoomDirection = false;
public UserSettingState() {
this.getUserPalette().add(new GColour(0, 0.02f, 0.075f, 0.114f, 1f));
this.getUserPalette().add(new GColour(1, 0f, 0.333f, 0.749f, 1f));
this.getUserPalette().add(new GColour(2, 0.145f, 0.478f, 0.243f, 1f));
this.getUserPalette().add(new GColour(3, 0f, 0.514f, 0.561f, 1f));
this.getUserPalette().add(new GColour(4, 0.788f, 0.102f, 0.035f, 1f));
this.getUserPalette().add(new GColour(5, 0.784f, 0.439f, 0.627f, 1f));
this.getUserPalette().add(new GColour(6, 0.345f, 0.224f, 0.153f, 1f));
this.getUserPalette().add(new GColour(7, 0.608f, 0.631f, 0.616f, 1f));
this.getUserPalette().add(new GColour(72, 0.335f, 0.342f, 0.323f, 1f));
this.getUserPalette().add(new GColour(9, 0.706f, 0.824f, 0.89f, 1f));
this.getUserPalette().add(new GColour(10, 0.294f, 0.624f, 0.29f, 1f));
this.getUserPalette().add(new GColour(11, 0.333f, 0.647f, 0.686f, 1f));
this.getUserPalette().add(new GColour(12, 0.949f, 0.439f, 0.369f, 1f));
this.getUserPalette().add(new GColour(13, 0.988f, 0.592f, 0.675f, 1f));
this.getUserPalette().add(new GColour(14, 0.949f, 0.804f, 0.216f, 1f));
this.getUserPalette().add(new GColour(15, 1f, 1f, 1f, 1f));
this.getUserPalette().add(new GColour(16, 0.498f, 0.498f, 0.498f, 1f));
syncWithTextEditor = new AtomicBoolean(true);
}
/**
* @return where your part authoring folder is located.
*/
public String getAuthoringFolderPath() {
return authoringFolderPath;
}
/**
* @param path
* the path where your part authoring folder is located.
*/
public void setAuthoringFolderPath(String path) {
this.authoringFolderPath = path;
}
/**
* @return where your LDraw folder is located.
*/
public String getLdrawFolderPath() {
return ldrawFolderPath;
}
/**
* @param path
* the path where your LDraw folder is located.
*/
public void setLdrawFolderPath(String path) {
this.ldrawFolderPath = path;
}
/**
* @return where your unofficial parts folder is located.
*/
public String getUnofficialFolderPath() {
return unofficialFolderPath;
}
/**
* @param path
* the path where your unofficial parts folder is located.
*/
public void setUnofficialFolderPath(String path) {
this.unofficialFolderPath = path;
}
/**
* @return your LDraw user name.
*/
public String getLdrawUserName() {
return ldrawUserName;
}
/**
* @param name
* your LDraw user name to set.
*/
public void setLdrawUserName(String name) {
this.ldrawUserName = name;
}
/**
* @return the license under you want to publish your work.
*/
public String getLicense() {
return license;
}
/**
* @param license
* your new license to set.
*/
public void setLicense(String license) {
this.license = license;
}
/**
* @return your real name.
*/
public String getRealUserName() {
return realUserName;
}
/**
* @param name
* your real name to set.
*/
public void setRealUserName(String name) {
this.realUserName = name;
}
/**
* @return {@code true} if the user wants to use relative paths, which share
* a common base path.
*/
public boolean isUsingRelativePaths() {
return usingRelativePaths;
}
/**
* @param usingRelativePaths
* Set to {@code true} if the user wants to use relative paths,
* which share a common base path.
*/
public void setUsingRelativePaths(boolean usingRelativePaths) {
this.usingRelativePaths = usingRelativePaths;
}
/**
* @return your colour palette (17 colours)
*/
public List<GColour> getUserPalette() {
return userPalette;
}
/**
* @param userPalette
* sets the colour palette (17 colours)
*/
public void setUserPalette(List<GColour> userPalette) {
this.userPalette = userPalette;
}
public BigDecimal getCoarseMoveSnap() {
return coarseMoveSnap;
}
public void setCoarseMoveSnap(BigDecimal coarseMoveSnap) {
this.coarseMoveSnap = coarseMoveSnap;
}
public BigDecimal getCoarseRotateSnap() {
return coarseRotateSnap;
}
public void setCoarseRotateSnap(BigDecimal coarseRotateSnap) {
this.coarseRotateSnap = coarseRotateSnap;
}
public BigDecimal getCoarseScaleSnap() {
return coarseScaleSnap;
}
public void setCoarseScaleSnap(BigDecimal coarseScaleSnap) {
this.coarseScaleSnap = coarseScaleSnap;
}
public BigDecimal getMediumMoveSnap() {
return mediumMoveSnap;
}
public void setMediumMoveSnap(BigDecimal mediumMoveSnap) {
this.mediumMoveSnap = mediumMoveSnap;
}
public BigDecimal getMediumRotateSnap() {
return mediumRotateSnap;
}
public void setMediumRotateSnap(BigDecimal mediumRotateSnap) {
this.mediumRotateSnap = mediumRotateSnap;
}
public BigDecimal getMediumScaleSnap() {
return mediumScaleSnap;
}
public void setMediumScaleSnap(BigDecimal mediumScaleSnap) {
this.mediumScaleSnap = mediumScaleSnap;
}
public BigDecimal getFineMoveSnap() {
return fineMoveSnap;
}
public void setFineMoveSnap(BigDecimal fineMoveSnap) {
this.fineMoveSnap = fineMoveSnap;
}
public BigDecimal getFineRotateSnap() {
return fineRotateSnap;
}
public void setFineRotateSnap(BigDecimal fineRotateSnap) {
this.fineRotateSnap = fineRotateSnap;
}
public BigDecimal getFineScaleSnap() {
return fineScaleSnap;
}
public void setFineScaleSnap(BigDecimal fineScaleSnap) {
this.fineScaleSnap = fineScaleSnap;
}
public int getTransMatrixPrecision() {
return transMatrixPrecision;
}
public void setTransMatrixPrecision(int transMatrixPrecision) {
this.transMatrixPrecision = transMatrixPrecision;
}
public int getCoordsPrecision() {
return coordsPrecision;
}
public void setCoordsPrecision(int coordsPrecision) {
this.coordsPrecision = coordsPrecision;
}
public boolean isResetOnStart() {
return resetOnStart;
}
public void setResetOnStart(boolean resetOnStart) {
this.resetOnStart = resetOnStart;
}
public String getLdConfigPath() {
return ldConfigPath;
}
public void setLdConfigPath(String ldConfigPath) {
this.ldConfigPath = ldConfigPath;
}
public AtomicBoolean getSyncWithTextEditor() {
return new AtomicBoolean(true);
}
public void setSyncWithTextEditor(AtomicBoolean syncWithTextEditor) {
this.syncWithTextEditor = syncWithTextEditor;
}
public AtomicBoolean getSyncWithLpeInline() {
return syncWithLpeInline;
}
public void setSyncWithLpeInline(AtomicBoolean syncWithLpeInline) {
this.syncWithLpeInline = syncWithLpeInline;
}
public int getIconSize() {
return iconSize;
}
public void setIconSize(int iconSize) {
this.iconSize = iconSize;
}
public float[] getManipulatorSize() {
return manipulatorSize;
}
public void setManipulatorSize(float[] manipulatorSize) {
this.manipulatorSize = manipulatorSize;
}
public List<String> getRecentItems() {
if (recentItems == null) recentItems = new ArrayList<>();
return recentItems;
}
public void setRecentItems(List<String> recentItems) {
this.recentItems = recentItems;
}
public Locale getLocale() {
return locale;
}
public void setLocale(Locale locale) {
this.locale = locale;
}
public boolean isBfcCertificationRequiredForLDrawMode() {
return bfcCertificationRequiredForLDrawMode;
}
public void setBfcCertificationRequiredForLDrawMode(boolean bfcCertificationRequiredForLDrawMode) {
this.bfcCertificationRequiredForLDrawMode = bfcCertificationRequiredForLDrawMode;
}
public List<ToolItemState> getToolItemConfig3D() {
return toolItemConfig3D;
}
public void setToolItemConfig3D(List<ToolItemState> toolItemConfig3D) {
this.toolItemConfig3D = toolItemConfig3D;
}
void loadShortkeys() {
if (key3DStrings != null && key3DKeys != null && key3DTasks != null) {
final int size = key3DStrings.length;
for (int i = 0; i < size; i++) {
KeyStateManager.changeKey(key3DKeys[i], key3DStrings[i], key3DTasks[i]);
}
}
if (keyTextStrings != null && keyTextKeys != null && keyTextTasks != null) {
final int size = keyTextStrings.length;
for (int i = 0; i < size; i++) {
KeyStateManager.changeKey(keyTextKeys[i], keyTextStrings[i], keyTextTasks[i]);
}
}
}
void saveShortkeys() {
Map<String, Task> m1 = KeyStateManager.getTaskmap();
Map<Task, String> m2 = KeyStateManager.getTaskKeymap();
Map<String, TextTask> m3 = KeyStateManager.getTextTaskmap();
Map<TextTask, String> m4 = KeyStateManager.getTextTaskKeymap();
int size1 = m1.size();
int size2 = m3.size();
key3DStrings = new String[size1];
key3DKeys = new String[size1];
key3DTasks = new Task[size1];
keyTextStrings = new String[size2];
keyTextKeys = new String[size2];
keyTextTasks = new TextTask[size2];
{
int i = 0;
for (Entry<String, Task> entry : m1.entrySet()) {
String k = entry.getKey();
Task t = entry.getValue();
String keyString = m2.get(t);
key3DStrings[i] = keyString;
key3DKeys[i] = k;
key3DTasks[i] = t;
i++;
}
}
{
int i = 0;
for (Entry<String, TextTask> entry : m3.entrySet()) {
String k = entry.getKey();
TextTask t = entry.getValue();
String keyString = m4.get(t);
keyTextStrings[i] = keyString;
keyTextKeys[i] = k;
keyTextTasks[i] = t;
i++;
}
}
}
public boolean isAntiAliasing() {
return antiAliasing;
}
public void setAntiAliasing(boolean antiAliasing) {
this.antiAliasing = antiAliasing;
}
public boolean isOpenGL33Engine() {
return newEngine;
}
public void setOpenGL33Engine(boolean openGL33Engine) {
this.newEngine = openGL33Engine;
}
public boolean isVulkanEngine() {
return vulkanEngine;
}
public void setVulkanEngine(boolean vulkanEngine) {
this.vulkanEngine = vulkanEngine;
}
void saveColours() {
color16OverrideColour = new float[] {LDConfig.colour16overrideR,LDConfig.colour16overrideG,LDConfig.colour16overrideB};
bfcFrontColour = new float[] {Colour.bfcFrontColourR,Colour.bfcFrontColourG,Colour.bfcFrontColourB};
bfcBackColour = new float[] {Colour.bfcBackColourR,Colour.bfcBackColourG,Colour.bfcBackColourB};
bfcUncertifiedColour = new float[] {Colour.bfcUncertifiedColourR,Colour.bfcUncertifiedColourG,Colour.bfcUncertifiedColourB};
vertexColour = new float[] {Colour.vertexColourR,Colour.vertexColourG,Colour.vertexColourB};
vertexSelectedColour = new float[] {Colour.vertexSelectedColourR,Colour.vertexSelectedColourG,Colour.vertexSelectedColourB};
condlineSelectedColour = new float[] {Colour.condlineSelectedColourR,Colour.condlineSelectedColourG,Colour.condlineSelectedColourB};
lineColour = new float[] {Colour.lineColourR,Colour.lineColourG,Colour.lineColourB};
meshlineColour = new float[] {Colour.meshlineColourR,Colour.meshlineColourG,Colour.meshlineColourB};
condlineHiddenColour = new float[] {Colour.condlineHiddenColourR,Colour.condlineHiddenColourG,Colour.condlineHiddenColourB};
condlineShownColour = new float[] {Colour.condlineShownColourR,Colour.condlineShownColourG,Colour.condlineShownColourB};
backgroundColour = new float[] {Colour.backgroundColourR,Colour.backgroundColourG,Colour.backgroundColourB};
light1Colour = new float[] {Colour.light1ColourR,Colour.light1ColourG,Colour.light1ColourB};
light1SpecularColour = new float[] {Colour.light1SpecularColourR,Colour.light1SpecularColourG,Colour.light1SpecularColourB};
light2Colour = new float[] {Colour.light2ColourR,Colour.light2ColourG,Colour.light2ColourB};
light2SpecularColour = new float[] {Colour.light2SpecularColourR,Colour.light2SpecularColourG,Colour.light2SpecularColourB};
light3Colour = new float[] {Colour.light3ColourR,Colour.light3ColourG,Colour.light3ColourB};
light3SpecularColour = new float[] {Colour.light3SpecularColourR,Colour.light3SpecularColourG,Colour.light3SpecularColourB};
light4Colour = new float[] {Colour.light4ColourR,Colour.light4ColourG,Colour.light4ColourB};
light4SpecularColour = new float[] {Colour.light4SpecularColourR,Colour.light4SpecularColourG,Colour.light4SpecularColourB};
manipulatorSelectedColour = new float[] {Colour.manipulatorSelectedColourR,Colour.manipulatorSelectedColourG,Colour.manipulatorSelectedColourB};
manipulatorInnerCircleColour = new float[] {Colour.manipulatorInnerCircleColourR,Colour.manipulatorInnerCircleColourG,Colour.manipulatorInnerCircleColourB};
manipulatorOuterCircleColour = new float[] {Colour.manipulatorOuterCircleColourR,Colour.manipulatorOuterCircleColourG,Colour.manipulatorOuterCircleColourB};
manipulatorXAxisColour = new float[] {Colour.manipulatorXAxisColourR,Colour.manipulatorXAxisColourG,Colour.manipulatorXAxisColourB};
manipulatorYAxisColour = new float[] {Colour.manipulatorYAxisColourR,Colour.manipulatorYAxisColourG,Colour.manipulatorYAxisColourB};
manipulatorZAxisColour = new float[] {Colour.manipulatorZAxisColourR,Colour.manipulatorZAxisColourG,Colour.manipulatorZAxisColourB};
addObjectColour = new float[] {Colour.addObjectColourR,Colour.addObjectColourG,Colour.addObjectColourB};
originColour = new float[] {Colour.originColourR,Colour.originColourG,Colour.originColourB};
grid10Colour = new float[] {Colour.grid10ColourR,Colour.grid10ColourG,Colour.grid10ColourB};
gridColour = new float[] {Colour.gridColourR,Colour.gridColourB,Colour.gridColourB};
rubberBandColour = new float[] {Colour.rubberBandColourR,Colour.rubberBandColourG,Colour.rubberBandColourB};
textColour = new float[] {Colour.textColourR,Colour.textColourG,Colour.textColourB};
xAxisColour = new float[] {Colour.xAxisColourR,Colour.xAxisColourG,Colour.xAxisColourB};
yAxisColour = new float[] {Colour.yAxisColourR,Colour.yAxisColourG,Colour.yAxisColourB};
zAxisColour = new float[] {Colour.zAxisColourR,Colour.zAxisColourG,Colour.zAxisColourB};
primitiveBackgroundColour = new float[] {Colour.primitiveBackgroundColourR,Colour.primitiveBackgroundColourG,Colour.primitiveBackgroundColourB};
primitiveSignFGColour = new float[] {Colour.primitiveSignFgColourR,Colour.primitiveSignFgColourG,Colour.primitiveSignFgColourB};
primitiveSignBGColour = new float[] {Colour.primitiveSignBgColourR,Colour.primitiveSignBgColourG,Colour.primitiveSignBgColourB};
primitivePlusAndMinusColour = new float[] {Colour.primitivePlusNMinusColourR,Colour.primitivePlusNMinusColourG,Colour.primitivePlusNMinusColourB};
primitiveSelectedCellColour = new float[] {Colour.primitiveSelectedCellColourR,Colour.primitiveSelectedCellColourG,Colour.primitiveSelectedCellColourB};
primitiveFocusedCellColour = new float[] {Colour.primitiveFocusedCellColourR,Colour.primitiveFocusedCellColourG,Colour.primitiveFocusedCellColourB};
primitiveNormalCellColour = new float[] {Colour.primitiveNormalCellColourR,Colour.primitiveNormalCellColourG,Colour.primitiveNormalCellColourB};
primitiveCell1Colour = new float[] {Colour.primitiveCell1ColourR,Colour.primitiveCell1ColourG,Colour.primitiveCell1ColourB};
primitiveCell2Colour = new float[] {Colour.primitiveCell2ColourR,Colour.primitiveCell2ColourG,Colour.primitiveCell2ColourB};
primitiveCategoryCell1Colour = new float[] {Colour.primitiveCategoryCell1ColourR,Colour.primitiveCategoryCell1ColourG,Colour.primitiveCategoryCell1ColourB};
primitiveCategoryCell2Colour = new float[] {Colour.primitiveCategoryCell2ColourR,Colour.primitiveCategoryCell2ColourG,Colour.primitiveCategoryCell2ColourB};
primitiveEdgeColour = new float[] {Colour.primitiveEdgeColourR,Colour.primitiveEdgeColourG,Colour.primitiveEdgeColourB};
primitiveCondlineColour = new float[] {Colour.primitiveCondlineColourR,Colour.primitiveCondlineColourG,Colour.primitiveCondlineColourB};
lineBoxFontColour = new int[]{TextEditorColour.getLineBoxFont().getRed(),TextEditorColour.getLineBoxFont().getGreen(),TextEditorColour.getLineBoxFont().getBlue()};
lineColourAttrFontColour = new int[]{TextEditorColour.getLineColourAttrFont().getRed(),TextEditorColour.getLineColourAttrFont().getGreen(),TextEditorColour.getLineColourAttrFont().getBlue()};
lineCommentFontColour = new int[]{TextEditorColour.getLineCommentFont().getRed(),TextEditorColour.getLineCommentFont().getGreen(),TextEditorColour.getLineCommentFont().getBlue()};
lineWarningUnderlineColour = new int[]{TextEditorColour.getLineWarningUnderline().getRed(),TextEditorColour.getLineWarningUnderline().getGreen(),TextEditorColour.getLineWarningUnderline().getBlue()};
lineErrorUnderlineColour = new int[]{TextEditorColour.getLineErrorUnderline().getRed(),TextEditorColour.getLineErrorUnderline().getGreen(),TextEditorColour.getLineErrorUnderline().getBlue()};
lineHighlightBackgroundColour = new int[]{TextEditorColour.getLineHighlightBackground().getRed(),TextEditorColour.getLineHighlightBackground().getGreen(),TextEditorColour.getLineHighlightBackground().getBlue()};
lineHighlightSelectedBackgroundColour = new int[]{TextEditorColour.getLineHighlightSelectedBackground().getRed(),TextEditorColour.getLineHighlightSelectedBackground().getGreen(),TextEditorColour.getLineHighlightSelectedBackground().getBlue()};
lineHintUnderlineColour = new int[]{TextEditorColour.getLineHintUnderline().getRed(),TextEditorColour.getLineHintUnderline().getGreen(),TextEditorColour.getLineHintUnderline().getBlue()};
linePrimaryFontColour = new int[]{TextEditorColour.getLinePrimaryFont().getRed(),TextEditorColour.getLinePrimaryFont().getGreen(),TextEditorColour.getLinePrimaryFont().getBlue()};
lineSecondaryFontColour = new int[]{TextEditorColour.getLineSecondaryFont().getRed(),TextEditorColour.getLineSecondaryFont().getGreen(),TextEditorColour.getLineSecondaryFont().getBlue()};
lineQuadFontColour = new int[]{TextEditorColour.getLineQuadFont().getRed(),TextEditorColour.getLineQuadFont().getGreen(),TextEditorColour.getLineQuadFont().getBlue()};
textBackgroundColour = new int[]{TextEditorColour.getTextBackground().getRed(),TextEditorColour.getTextBackground().getGreen(),TextEditorColour.getTextBackground().getBlue()};
textForegroundColour = new int[]{TextEditorColour.getTextForeground().getRed(),TextEditorColour.getTextForeground().getGreen(),TextEditorColour.getTextForeground().getBlue()};
textForegroundHiddenColour = new int[]{TextEditorColour.getTextForegroundHidden().getRed(),TextEditorColour.getTextForegroundHidden().getGreen(),TextEditorColour.getTextForegroundHidden().getBlue()};
cursor1ColourColour = new float[] {Colour.cursor1ColourR,Colour.cursor1ColourG,Colour.cursor1ColourB};
cursor2ColourColour = new float[] {Colour.cursor2ColourR,Colour.cursor2ColourG,Colour.cursor2ColourB};
}
@SuppressWarnings("java:S2696")
public void loadColours() {
if (color16OverrideColour != null) {
LDConfig.colour16overrideR = color16OverrideColour[0];
LDConfig.colour16overrideG = color16OverrideColour[1];
LDConfig.colour16overrideB = color16OverrideColour[2];
}
if (bfcFrontColour != null) {
Colour.bfcFrontColourR = bfcFrontColour[0];
Colour.bfcFrontColourG = bfcFrontColour[1];
Colour.bfcFrontColourB = bfcFrontColour[2];
}
if (bfcBackColour != null) {
Colour.bfcBackColourR = bfcBackColour[0];
Colour.bfcBackColourG = bfcBackColour[1];
Colour.bfcBackColourB = bfcBackColour[2];
}
if (bfcUncertifiedColour != null) {
Colour.bfcUncertifiedColourR = bfcUncertifiedColour[0];
Colour.bfcUncertifiedColourG = bfcUncertifiedColour[1];
Colour.bfcUncertifiedColourB = bfcUncertifiedColour[2];
}
if (vertexColour != null) {
Colour.vertexColourR = vertexColour[0];
Colour.vertexColourG = vertexColour[1];
Colour.vertexColourB = vertexColour[2];
}
if (vertexSelectedColour != null) {
Colour.vertexSelectedColourR = vertexSelectedColour[0];
Colour.vertexSelectedColourG = vertexSelectedColour[1];
Colour.vertexSelectedColourB = vertexSelectedColour[2];
}
if (condlineSelectedColour != null) {
Colour.condlineSelectedColourR = condlineSelectedColour[0];
Colour.condlineSelectedColourG = condlineSelectedColour[1];
Colour.condlineSelectedColourB = condlineSelectedColour[2];
}
if (lineColour != null) {
Colour.lineColourR = lineColour[0];
Colour.lineColourG = lineColour[1];
Colour.lineColourB = lineColour[2];
}
if (meshlineColour != null) {
Colour.meshlineColourR = meshlineColour[0];
Colour.meshlineColourG = meshlineColour[1];
Colour.meshlineColourB = meshlineColour[2];
}
if (condlineHiddenColour != null) {
Colour.condlineHiddenColourR = condlineHiddenColour[0];
Colour.condlineHiddenColourG = condlineHiddenColour[1];
Colour.condlineHiddenColourB = condlineHiddenColour[2];
}
if (condlineShownColour != null) {
Colour.condlineShownColourR = condlineShownColour[0];
Colour.condlineShownColourG = condlineShownColour[1];
Colour.condlineShownColourB = condlineShownColour[2];
}
if (backgroundColour != null) {
Colour.backgroundColourR = backgroundColour[0];
Colour.backgroundColourG = backgroundColour[1];
Colour.backgroundColourB = backgroundColour[2];
}
if (light1Colour != null) {
Colour.light1ColourR = light1Colour[0];
Colour.light1ColourG = light1Colour[1];
Colour.light1ColourB = light1Colour[2];
}
if (light1SpecularColour != null) {
Colour.light1SpecularColourR = light1SpecularColour[0];
Colour.light1SpecularColourG = light1SpecularColour[1];
Colour.light1SpecularColourB = light1SpecularColour[2];
}
if (light2Colour != null) {
Colour.light2ColourR = light2Colour[0];
Colour.light2ColourG = light2Colour[1];
Colour.light2ColourB = light2Colour[2];
}
if (light2SpecularColour != null) {
Colour.light2SpecularColourR = light2SpecularColour[0];
Colour.light2SpecularColourG = light2SpecularColour[1];
Colour.light2SpecularColourB = light2SpecularColour[2];
}
if (light3Colour != null) {
Colour.light3ColourR = light3Colour[0];
Colour.light3ColourG = light3Colour[1];
Colour.light3ColourB = light3Colour[2];
}
if (light3SpecularColour != null) {
Colour.light3SpecularColourR = light3SpecularColour[0];
Colour.light3SpecularColourG = light3SpecularColour[1];
Colour.light3SpecularColourB = light3SpecularColour[2];
}
if (light4Colour != null) {
Colour.light4ColourR = light4Colour[0];
Colour.light4ColourG = light4Colour[1];
Colour.light4ColourB = light4Colour[2];
}
if (light4SpecularColour != null) {
Colour.light4SpecularColourR = light4SpecularColour[0];
Colour.light4SpecularColourG = light4SpecularColour[1];
Colour.light4SpecularColourB = light4SpecularColour[2];
}
if (manipulatorSelectedColour != null) {
Colour.manipulatorSelectedColourR = manipulatorSelectedColour[0];
Colour.manipulatorSelectedColourG = manipulatorSelectedColour[1];
Colour.manipulatorSelectedColourB = manipulatorSelectedColour[2];
}
if (manipulatorInnerCircleColour != null) {
Colour.manipulatorInnerCircleColourR = manipulatorInnerCircleColour[0];
Colour.manipulatorInnerCircleColourG = manipulatorInnerCircleColour[1];
Colour.manipulatorInnerCircleColourB = manipulatorInnerCircleColour[2];
}
if (manipulatorOuterCircleColour != null) {
Colour.manipulatorOuterCircleColourR = manipulatorOuterCircleColour[0];
Colour.manipulatorOuterCircleColourG = manipulatorOuterCircleColour[1];
Colour.manipulatorOuterCircleColourB = manipulatorOuterCircleColour[2];
}
if (manipulatorXAxisColour != null) {
Colour.manipulatorXAxisColourR = manipulatorXAxisColour[0];
Colour.manipulatorXAxisColourG = manipulatorXAxisColour[1];
Colour.manipulatorXAxisColourB = manipulatorXAxisColour[2];
}
if (manipulatorYAxisColour != null) {
Colour.manipulatorYAxisColourR = manipulatorYAxisColour[0];
Colour.manipulatorYAxisColourG = manipulatorYAxisColour[1];
Colour.manipulatorYAxisColourB = manipulatorYAxisColour[2];
}
if (manipulatorZAxisColour != null) {
Colour.manipulatorZAxisColourR = manipulatorZAxisColour[0];
Colour.manipulatorZAxisColourG = manipulatorZAxisColour[1];
Colour.manipulatorZAxisColourB = manipulatorZAxisColour[2];
}
if (addObjectColour != null) {
Colour.addObjectColourR = addObjectColour[0];
Colour.addObjectColourG = addObjectColour[1];
Colour.addObjectColourB = addObjectColour[2];
}
if (originColour != null) {
Colour.originColourR = originColour[0];
Colour.originColourG = originColour[1];
Colour.originColourB = originColour[2];
}
if (grid10Colour != null) {
Colour.grid10ColourR = grid10Colour[0];
Colour.grid10ColourG = grid10Colour[1];
Colour.grid10ColourB = grid10Colour[2];
}
if (gridColour != null) {
Colour.gridColourR = gridColour[0];
Colour.gridColourG = gridColour[1];
Colour.gridColourB = gridColour[2];
}
if (rubberBandColour != null) {
Colour.rubberBandColourR = rubberBandColour[0];
Colour.rubberBandColourG = rubberBandColour[1];
Colour.rubberBandColourB = rubberBandColour[2];
}
if (textColour != null) {
Colour.textColourR = textColour[0];
Colour.textColourG = textColour[1];
Colour.textColourB = textColour[2];
}
if (xAxisColour != null) {
Colour.xAxisColourR = xAxisColour[0];
Colour.xAxisColourG = xAxisColour[1];
Colour.xAxisColourB = xAxisColour[2];
}
if (yAxisColour != null) {
Colour.yAxisColourR = yAxisColour[0];
Colour.yAxisColourG = yAxisColour[1];
Colour.yAxisColourB = yAxisColour[2];
}
if (zAxisColour != null) {
Colour.zAxisColourR = zAxisColour[0];
Colour.zAxisColourG = zAxisColour[1];
Colour.zAxisColourB = zAxisColour[2];
}
if (primitiveBackgroundColour != null) {
Colour.primitiveBackgroundColourR = primitiveBackgroundColour[0];
Colour.primitiveBackgroundColourG = primitiveBackgroundColour[1];
Colour.primitiveBackgroundColourB = primitiveBackgroundColour[2];
}
if (primitiveSignFGColour != null) {
Colour.primitiveSignFgColourR = primitiveSignFGColour[0];
Colour.primitiveSignFgColourG = primitiveSignFGColour[1];
Colour.primitiveSignFgColourB = primitiveSignFGColour[2];
}
if (primitiveSignBGColour != null) {
Colour.primitiveSignBgColourR = primitiveSignBGColour[0];
Colour.primitiveSignBgColourG = primitiveSignBGColour[1];
Colour.primitiveSignBgColourB = primitiveSignBGColour[2];
}
if (primitivePlusAndMinusColour != null) {
Colour.primitivePlusNMinusColourR = primitivePlusAndMinusColour[0];
Colour.primitivePlusNMinusColourG = primitivePlusAndMinusColour[1];
Colour.primitivePlusNMinusColourB = primitivePlusAndMinusColour[2];
}
if (primitiveSelectedCellColour != null) {
Colour.primitiveSelectedCellColourR = primitiveSelectedCellColour[0];
Colour.primitiveSelectedCellColourG = primitiveSelectedCellColour[1];
Colour.primitiveSelectedCellColourB = primitiveSelectedCellColour[2];
}
if (primitiveFocusedCellColour != null) {
Colour.primitiveFocusedCellColourR = primitiveFocusedCellColour[0];
Colour.primitiveFocusedCellColourG = primitiveFocusedCellColour[1];
Colour.primitiveFocusedCellColourB = primitiveFocusedCellColour[2];
}
if (primitiveNormalCellColour != null) {
Colour.primitiveNormalCellColourR = primitiveNormalCellColour[0];
Colour.primitiveNormalCellColourG = primitiveNormalCellColour[1];
Colour.primitiveNormalCellColourB = primitiveNormalCellColour[2];
}
if (primitiveCell1Colour != null) {
Colour.primitiveCell1ColourR = primitiveCell1Colour[0];
Colour.primitiveCell1ColourG = primitiveCell1Colour[1];
Colour.primitiveCell1ColourB = primitiveCell1Colour[2];
}
if (primitiveCell2Colour != null) {
Colour.primitiveCell2ColourR = primitiveCell2Colour[0];
Colour.primitiveCell2ColourG = primitiveCell2Colour[1];
Colour.primitiveCell2ColourB = primitiveCell2Colour[2];
}
if (primitiveCategoryCell1Colour != null) {
Colour.primitiveCategoryCell1ColourR = primitiveCategoryCell1Colour[0];
Colour.primitiveCategoryCell1ColourG = primitiveCategoryCell1Colour[1];
Colour.primitiveCategoryCell1ColourB = primitiveCategoryCell1Colour[2];
}
if (primitiveCategoryCell2Colour != null) {
Colour.primitiveCategoryCell2ColourR = primitiveCategoryCell2Colour[0];
Colour.primitiveCategoryCell2ColourG = primitiveCategoryCell2Colour[1];
Colour.primitiveCategoryCell2ColourB = primitiveCategoryCell2Colour[2];
}
if (primitiveEdgeColour != null) {
Colour.primitiveEdgeColourR = primitiveEdgeColour[0];
Colour.primitiveEdgeColourG = primitiveEdgeColour[1];
Colour.primitiveEdgeColourB = primitiveEdgeColour[2];
}
if (primitiveCondlineColour != null) {
Colour.primitiveCondlineColourR = primitiveCondlineColour[0];
Colour.primitiveCondlineColourG = primitiveCondlineColour[1];
Colour.primitiveCondlineColourB = primitiveCondlineColour[2];
}
if (cursor1ColourColour != null) {
Colour.cursor1ColourR = cursor1ColourColour[0];
Colour.cursor1ColourG = cursor1ColourColour[1];
Colour.cursor1ColourB = cursor1ColourColour[2];
}
if (cursor2ColourColour != null) {
Colour.cursor2ColourR = cursor2ColourColour[0];
Colour.cursor2ColourG = cursor2ColourColour[1];
Colour.cursor2ColourB = cursor2ColourColour[2];
}
if (lineBoxFontColour != null) {
TextEditorColour.loadLineBoxFont(SWTResourceManager.getColor(lineBoxFontColour[0], lineBoxFontColour[1], lineBoxFontColour[2]));
}
if (lineColourAttrFontColour != null) {
TextEditorColour.loadLineColourAttrFont(SWTResourceManager.getColor(lineColourAttrFontColour[0], lineColourAttrFontColour[1], lineColourAttrFontColour[2]));
}
if (lineCommentFontColour != null) {
TextEditorColour.loadLineCommentFont(SWTResourceManager.getColor(lineCommentFontColour[0], lineCommentFontColour[1], lineCommentFontColour[2]));
}
if (lineErrorUnderlineColour != null) {
TextEditorColour.loadLineErrorUnderline(SWTResourceManager.getColor(lineErrorUnderlineColour[0], lineErrorUnderlineColour[1], lineErrorUnderlineColour[2]));
}
if (lineHighlightBackgroundColour != null) {
TextEditorColour.loadLineHighlightBackground(SWTResourceManager.getColor(lineHighlightBackgroundColour[0], lineHighlightBackgroundColour[1], lineHighlightBackgroundColour[2]));
}
if (lineHighlightSelectedBackgroundColour != null) {
TextEditorColour.loadLineHighlightSelectedBackground(SWTResourceManager.getColor(lineHighlightSelectedBackgroundColour[0], lineHighlightSelectedBackgroundColour[1], lineHighlightSelectedBackgroundColour[2]));
}
if (lineHintUnderlineColour != null) {
TextEditorColour.loadLineHintUnderline(SWTResourceManager.getColor(lineHintUnderlineColour[0], lineHintUnderlineColour[1], lineHintUnderlineColour[2]));
}
if (linePrimaryFontColour != null) {
TextEditorColour.loadLinePrimaryFont(SWTResourceManager.getColor(linePrimaryFontColour[0], linePrimaryFontColour[1], linePrimaryFontColour[2]));
}
if (lineQuadFontColour != null) {
TextEditorColour.loadLineQuadFont(SWTResourceManager.getColor(lineQuadFontColour[0], lineQuadFontColour[1], lineQuadFontColour[2]));
}
if (lineSecondaryFontColour != null) {
TextEditorColour.loadLineSecondaryFont(SWTResourceManager.getColor(lineSecondaryFontColour[0], lineSecondaryFontColour[1], lineSecondaryFontColour[2]));
}
if (lineWarningUnderlineColour != null) {
TextEditorColour.loadLineWarningUnderline(SWTResourceManager.getColor(lineWarningUnderlineColour[0], lineWarningUnderlineColour[1], lineWarningUnderlineColour[2]));
}
if (textBackgroundColour != null) {
TextEditorColour.loadTextBackground(SWTResourceManager.getColor(textBackgroundColour[0], textBackgroundColour[1], textBackgroundColour[2]));
}
if (textForegroundColour != null) {
TextEditorColour.loadTextForeground(SWTResourceManager.getColor(textForegroundColour[0], textForegroundColour[1], textForegroundColour[2]));
}
if (textForegroundHiddenColour != null) {
TextEditorColour.loadTextForegroundHidden(SWTResourceManager.getColor(textForegroundHiddenColour[0], textForegroundHiddenColour[1], textForegroundHiddenColour[2]));
}
}
public boolean isAllowInvalidShapes() {
return allowInvalidShapes;
}
public void setAllowInvalidShapes(boolean allowInvalidShapes) {
this.allowInvalidShapes = allowInvalidShapes;
}
public boolean isSyncingTabs() {
return syncingTabs;
}
public void setSyncingTabs(boolean syncingTabs) {
this.syncingTabs = syncingTabs;
}
public int getTextWinArr() {
return textWinArr;
}
public void setTextWinArr(int textWinArr) {
this.textWinArr = textWinArr;
}
public boolean isDisableMAD3D() {
return !disableMAD3D;
}
public void setDisableMAD3D(boolean disableMAD3D) {
this.disableMAD3D = !disableMAD3D;
}
public boolean isDisableMADtext() {
return !disableMADtext;
}
public void setDisableMADtext(boolean disableMADtext) {
this.disableMADtext = !disableMADtext;
}
public boolean isRoundX() {
return roundX;
}
public void setRoundX(boolean roundX) {
this.roundX = roundX;
}
public boolean isRoundY() {
return roundY;
}
public void setRoundY(boolean roundY) {
this.roundY = roundY;
}
public boolean isRoundZ() {
return roundZ;
}
public void setRoundZ(boolean roundZ) {
this.roundZ = roundZ;
}
public int getOpenGLVersion() {
return openGLVersion;
}
public String getOpenGLVersionString() {
switch (openGLVersion) {
case 20:
return "OpenGL 2.0"; //$NON-NLS-1$
case 33:
return "OpenGL 3.3"; //$NON-NLS-1$
case 100:
return "Vulkan API 1.0"; //$NON-NLS-1$
default:
NLogger.error(getClass(), "getOpenGLVersionString(): No version string defined! OpenGL " + openGLVersion); //$NON-NLS-1$
return openGLVersion + " [n.def.!]"; //$NON-NLS-1$
}
}
public void setOpenGLVersion(int openGLVersion) {
this.openGLVersion = openGLVersion;
}
public BigDecimal getFuzziness3D() {
return fuzziness3D;
}
public void setFuzziness3D(BigDecimal fuzziness3d) {
fuzziness3D = fuzziness3d;
}
public int getFuzziness2D() {
return fuzziness2D;
}
public void setFuzziness2D(int fuzziness2d) {
fuzziness2D = fuzziness2d;
}
public boolean isMovingAdjacentData() {
return movingAdjacentData;
}
public void setMovingAdjacentData(boolean movingAdjacentData) {
this.movingAdjacentData = movingAdjacentData;
}
public boolean isTranslatingViewByCursor() {
return translateViewByCursor;
}
public void setTranslatingViewByCursor(boolean translateViewByCursor) {
this.translateViewByCursor = translateViewByCursor;
}
public double getCoplanarityAngleWarning() {
return coplanarityAngleWarning;
}
public void setCoplanarityAngleWarning(double coplanarityAngleWarning) {
this.coplanarityAngleWarning = coplanarityAngleWarning;
}
public double getCoplanarityAngleError() {
return coplanarityAngleError;
}
public void setCoplanarityAngleError(double coplanarityAngleError) {
this.coplanarityAngleError = coplanarityAngleError;
}
public double getViewportScaleFactor() {
return viewportScaleFactor;
}
public void setViewportScaleFactor(double viewportScaleFactor) {
this.viewportScaleFactor = viewportScaleFactor;
}
public int getMouseButtonLayout() {
return mouseButtonLayout;
}
public void setMouseButtonLayout(int mouseButtonLayout) {
this.mouseButtonLayout = mouseButtonLayout;
}
public boolean isInvertingWheelZoomDirection() {
return invertingWheelZoomDirection;
}
public void setInvertingWheelZoomDirection(boolean invertingWheelZoomDirection) {
this.invertingWheelZoomDirection = invertingWheelZoomDirection;
}
}
| mit |
Azure/azure-sdk-for-java | sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ClientSideRequestStatistics.java | 19958 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.cosmos.implementation;
import com.azure.cosmos.CosmosException;
import com.azure.cosmos.implementation.apachecommons.lang.StringUtils;
import com.azure.cosmos.implementation.cpu.CpuMemoryMonitor;
import com.azure.cosmos.implementation.directconnectivity.DirectBridgeInternal;
import com.azure.cosmos.implementation.directconnectivity.StoreResponse;
import com.azure.cosmos.implementation.directconnectivity.StoreResult;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import java.io.IOException;
import java.net.URI;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
@JsonSerialize(using = ClientSideRequestStatistics.ClientSideRequestStatisticsSerializer.class)
public class ClientSideRequestStatistics {
private static final int MAX_SUPPLEMENTAL_REQUESTS_FOR_TO_STRING = 10;
private final DiagnosticsClientContext diagnosticsClientContext;
private String activityId;
private List<StoreResponseStatistics> responseStatisticsList;
private List<StoreResponseStatistics> supplementalResponseStatisticsList;
private Map<String, AddressResolutionStatistics> addressResolutionStatistics;
private List<URI> contactedReplicas;
private Set<URI> failedReplicas;
private Instant requestStartTimeUTC;
private Instant requestEndTimeUTC;
private Set<String> regionsContacted;
private Set<URI> locationEndpointsContacted;
private RetryContext retryContext;
private GatewayStatistics gatewayStatistics;
private RequestTimeline gatewayRequestTimeline;
private MetadataDiagnosticsContext metadataDiagnosticsContext;
private SerializationDiagnosticsContext serializationDiagnosticsContext;
private GlobalEndpointManager globalEndpointManager;
public ClientSideRequestStatistics(DiagnosticsClientContext diagnosticsClientContext, GlobalEndpointManager globalEndpointManager) {
this.diagnosticsClientContext = diagnosticsClientContext;
this.requestStartTimeUTC = Instant.now();
this.requestEndTimeUTC = Instant.now();
this.responseStatisticsList = new ArrayList<>();
this.supplementalResponseStatisticsList = new ArrayList<>();
this.addressResolutionStatistics = new HashMap<>();
this.contactedReplicas = Collections.synchronizedList(new ArrayList<>());
this.failedReplicas = Collections.synchronizedSet(new HashSet<>());
this.regionsContacted = Collections.synchronizedSet(new HashSet<>());
this.locationEndpointsContacted = Collections.synchronizedSet(new HashSet<>());
this.metadataDiagnosticsContext = new MetadataDiagnosticsContext();
this.serializationDiagnosticsContext = new SerializationDiagnosticsContext();
this.retryContext = new RetryContext();
this.globalEndpointManager = globalEndpointManager;
}
public Duration getDuration() {
return Duration.between(requestStartTimeUTC, requestEndTimeUTC);
}
public Instant getRequestStartTimeUTC() {
return requestStartTimeUTC;
}
public DiagnosticsClientContext getDiagnosticsClientContext() {
return diagnosticsClientContext;
}
public void recordResponse(RxDocumentServiceRequest request, StoreResult storeResult) {
Objects.requireNonNull(request, "request is required and cannot be null.");
Instant responseTime = Instant.now();
StoreResponseStatistics storeResponseStatistics = new StoreResponseStatistics();
storeResponseStatistics.requestResponseTimeUTC = responseTime;
storeResponseStatistics.storeResult = storeResult;
storeResponseStatistics.requestOperationType = request.getOperationType();
storeResponseStatistics.requestResourceType = request.getResourceType();
activityId = request.getActivityId().toString();
URI locationEndPoint = null;
if (request.requestContext != null) {
if (request.requestContext.locationEndpointToRoute != null) {
locationEndPoint = request.requestContext.locationEndpointToRoute;
}
}
synchronized (this) {
if (responseTime.isAfter(this.requestEndTimeUTC)) {
this.requestEndTimeUTC = responseTime;
}
if (locationEndPoint != null) {
this.regionsContacted.add(this.globalEndpointManager.getRegionName(locationEndPoint, request.getOperationType()));
this.locationEndpointsContacted.add(locationEndPoint);
}
if (storeResponseStatistics.requestOperationType == OperationType.Head
|| storeResponseStatistics.requestOperationType == OperationType.HeadFeed) {
this.supplementalResponseStatisticsList.add(storeResponseStatistics);
} else {
this.responseStatisticsList.add(storeResponseStatistics);
}
}
}
public void recordGatewayResponse(
RxDocumentServiceRequest rxDocumentServiceRequest, StoreResponse storeResponse,
CosmosException exception) {
Instant responseTime = Instant.now();
synchronized (this) {
if (responseTime.isAfter(this.requestEndTimeUTC)) {
this.requestEndTimeUTC = responseTime;
}
URI locationEndPoint = null;
if (rxDocumentServiceRequest != null && rxDocumentServiceRequest.requestContext != null) {
locationEndPoint = rxDocumentServiceRequest.requestContext.locationEndpointToRoute;
}
this.recordRetryContextEndTime();
if (locationEndPoint != null) {
this.regionsContacted.add(this.globalEndpointManager.getRegionName(locationEndPoint, rxDocumentServiceRequest.getOperationType()));
this.locationEndpointsContacted.add(locationEndPoint);
}
this.gatewayStatistics = new GatewayStatistics();
if (rxDocumentServiceRequest != null) {
this.gatewayStatistics.operationType = rxDocumentServiceRequest.getOperationType();
this.gatewayStatistics.resourceType = rxDocumentServiceRequest.getResourceType();
}
if (storeResponse != null) {
this.gatewayStatistics.statusCode = storeResponse.getStatus();
this.gatewayStatistics.subStatusCode = DirectBridgeInternal.getSubStatusCode(storeResponse);
this.gatewayStatistics.sessionToken = storeResponse
.getHeaderValue(HttpConstants.HttpHeaders.SESSION_TOKEN);
this.gatewayStatistics.requestCharge = storeResponse
.getHeaderValue(HttpConstants.HttpHeaders.REQUEST_CHARGE);
this.gatewayStatistics.requestTimeline = DirectBridgeInternal.getRequestTimeline(storeResponse);
this.gatewayStatistics.partitionKeyRangeId = storeResponse.getPartitionKeyRangeId();
this.activityId= storeResponse.getHeaderValue(HttpConstants.HttpHeaders.ACTIVITY_ID);
} else if (exception != null) {
this.gatewayStatistics.statusCode = exception.getStatusCode();
this.gatewayStatistics.subStatusCode = exception.getSubStatusCode();
this.gatewayStatistics.requestTimeline = this.gatewayRequestTimeline;
this.gatewayStatistics.requestCharge= String.valueOf(exception.getRequestCharge());
this.activityId=exception.getActivityId();
}
}
}
public void setGatewayRequestTimeline(RequestTimeline transportRequestTimeline) {
this.gatewayRequestTimeline = transportRequestTimeline;
}
public RequestTimeline getGatewayRequestTimeline() {
return this.gatewayRequestTimeline;
}
public String recordAddressResolutionStart(
URI targetEndpoint,
boolean forceRefresh,
boolean forceCollectionRoutingMapRefresh) {
String identifier = Utils
.randomUUID()
.toString();
AddressResolutionStatistics resolutionStatistics = new AddressResolutionStatistics();
resolutionStatistics.startTimeUTC = Instant.now();
resolutionStatistics.endTimeUTC = null;
resolutionStatistics.targetEndpoint = targetEndpoint == null ? "<NULL>" : targetEndpoint.toString();
resolutionStatistics.forceRefresh = forceRefresh;
resolutionStatistics.forceCollectionRoutingMapRefresh = forceCollectionRoutingMapRefresh;
synchronized (this) {
this.addressResolutionStatistics.put(identifier, resolutionStatistics);
}
return identifier;
}
public void recordAddressResolutionEnd(String identifier, String errorMessage) {
if (StringUtils.isEmpty(identifier)) {
return;
}
Instant responseTime = Instant.now();
synchronized (this) {
if (!this.addressResolutionStatistics.containsKey(identifier)) {
throw new IllegalArgumentException("Identifier " + identifier + " does not exist. Please call start "
+ "before calling end");
}
if (responseTime.isAfter(this.requestEndTimeUTC)) {
this.requestEndTimeUTC = responseTime;
}
AddressResolutionStatistics resolutionStatistics = this.addressResolutionStatistics.get(identifier);
resolutionStatistics.endTimeUTC = responseTime;
resolutionStatistics.errorMessage = errorMessage;
resolutionStatistics.inflightRequest = false;
}
}
public List<URI> getContactedReplicas() {
return contactedReplicas;
}
public void setContactedReplicas(List<URI> contactedReplicas) {
this.contactedReplicas = Collections.synchronizedList(contactedReplicas);
}
public Set<URI> getFailedReplicas() {
return failedReplicas;
}
public void setFailedReplicas(Set<URI> failedReplicas) {
this.failedReplicas = Collections.synchronizedSet(failedReplicas);
}
public Set<String> getContactedRegionNames() {
return regionsContacted;
}
public void setRegionsContacted(Set<String> regionsContacted) {
this.regionsContacted = Collections.synchronizedSet(regionsContacted);
}
public Set<URI> getLocationEndpointsContacted() {
return locationEndpointsContacted;
}
public void setLocationEndpointsContacted(Set<URI> locationEndpointsContacted) {
this.locationEndpointsContacted = locationEndpointsContacted;
}
public MetadataDiagnosticsContext getMetadataDiagnosticsContext(){
return this.metadataDiagnosticsContext;
}
public SerializationDiagnosticsContext getSerializationDiagnosticsContext() {
return this.serializationDiagnosticsContext;
}
public void recordRetryContextEndTime() {
this.retryContext.updateEndTime();
}
public RetryContext getRetryContext() {
return retryContext;
}
public List<StoreResponseStatistics> getResponseStatisticsList() {
return responseStatisticsList;
}
public List<StoreResponseStatistics> getSupplementalResponseStatisticsList() {
return supplementalResponseStatisticsList;
}
public Map<String, AddressResolutionStatistics> getAddressResolutionStatistics() {
return addressResolutionStatistics;
}
public GatewayStatistics getGatewayStatistics() {
return gatewayStatistics;
}
public static class StoreResponseStatistics {
@JsonSerialize(using = StoreResult.StoreResultSerializer.class)
private StoreResult storeResult;
@JsonSerialize(using = DiagnosticsInstantSerializer.class)
private Instant requestResponseTimeUTC;
@JsonSerialize
private ResourceType requestResourceType;
@JsonSerialize
private OperationType requestOperationType;
public StoreResult getStoreResult() {
return storeResult;
}
public Instant getRequestResponseTimeUTC() {
return requestResponseTimeUTC;
}
public ResourceType getRequestResourceType() {
return requestResourceType;
}
public OperationType getRequestOperationType() {
return requestOperationType;
}
}
public static class SystemInformation {
private String usedMemory;
private String availableMemory;
private String systemCpuLoad;
private int availableProcessors;
public String getUsedMemory() {
return usedMemory;
}
public String getAvailableMemory() {
return availableMemory;
}
public String getSystemCpuLoad() {
return systemCpuLoad;
}
public int getAvailableProcessors() {
return availableProcessors;
}
}
public static class ClientSideRequestStatisticsSerializer extends StdSerializer<ClientSideRequestStatistics> {
private static final long serialVersionUID = -2746532297176812860L;
ClientSideRequestStatisticsSerializer() {
super(ClientSideRequestStatistics.class);
}
@Override
public void serialize(
ClientSideRequestStatistics statistics, JsonGenerator generator, SerializerProvider provider) throws
IOException {
generator.writeStartObject();
long requestLatency = statistics
.getDuration()
.toMillis();
generator.writeStringField("userAgent", Utils.getUserAgent());
generator.writeStringField("activityId", statistics.activityId);
generator.writeNumberField("requestLatencyInMs", requestLatency);
generator.writeStringField("requestStartTimeUTC", DiagnosticsInstantSerializer.fromInstant(statistics.requestStartTimeUTC));
generator.writeStringField("requestEndTimeUTC", DiagnosticsInstantSerializer.fromInstant(statistics.requestEndTimeUTC));
generator.writeObjectField("responseStatisticsList", statistics.responseStatisticsList);
generator.writeObjectField("supplementalResponseStatisticsList", getCappedSupplementalResponseStatisticsList(statistics.supplementalResponseStatisticsList));
generator.writeObjectField("addressResolutionStatistics", statistics.addressResolutionStatistics);
generator.writeObjectField("regionsContacted", statistics.regionsContacted);
generator.writeObjectField("retryContext", statistics.retryContext);
generator.writeObjectField("metadataDiagnosticsContext", statistics.getMetadataDiagnosticsContext());
generator.writeObjectField("serializationDiagnosticsContext", statistics.getSerializationDiagnosticsContext());
generator.writeObjectField("gatewayStatistics", statistics.gatewayStatistics);
try {
SystemInformation systemInformation = fetchSystemInformation();
generator.writeObjectField("systemInformation", systemInformation);
} catch (Exception e) {
// Error while evaluating system information, do nothing
}
generator.writeObjectField("clientCfgs", statistics.diagnosticsClientContext);
generator.writeEndObject();
}
}
public static List<StoreResponseStatistics> getCappedSupplementalResponseStatisticsList(List<StoreResponseStatistics> supplementalResponseStatisticsList) {
int supplementalResponseStatisticsListCount = supplementalResponseStatisticsList.size();
int initialIndex =
Math.max(supplementalResponseStatisticsListCount - MAX_SUPPLEMENTAL_REQUESTS_FOR_TO_STRING, 0);
if (initialIndex != 0) {
List<StoreResponseStatistics> subList = supplementalResponseStatisticsList
.subList(initialIndex,
supplementalResponseStatisticsListCount);
return subList;
}
return supplementalResponseStatisticsList;
}
public static class AddressResolutionStatistics {
@JsonSerialize(using = DiagnosticsInstantSerializer.class)
private Instant startTimeUTC;
@JsonSerialize(using = DiagnosticsInstantSerializer.class)
private Instant endTimeUTC;
@JsonSerialize
private String targetEndpoint;
@JsonSerialize
private String errorMessage;
@JsonSerialize
private boolean forceRefresh;
@JsonSerialize
private boolean forceCollectionRoutingMapRefresh;
// If one replica return error we start address call in parallel,
// on other replica valid response, we end the current user request,
// indicating background addressResolution is still inflight
@JsonSerialize
private boolean inflightRequest = true;
public Instant getStartTimeUTC() {
return startTimeUTC;
}
public Instant getEndTimeUTC() {
return endTimeUTC;
}
public String getTargetEndpoint() {
return targetEndpoint;
}
public String getErrorMessage() {
return errorMessage;
}
public boolean isInflightRequest() {
return inflightRequest;
}
public boolean isForceRefresh() {
return forceRefresh;
}
public boolean isForceCollectionRoutingMapRefresh() {
return forceCollectionRoutingMapRefresh;
}
}
public static class GatewayStatistics {
private String sessionToken;
private OperationType operationType;
private ResourceType resourceType;
private int statusCode;
private int subStatusCode;
private String requestCharge;
private RequestTimeline requestTimeline;
private String partitionKeyRangeId;
public String getSessionToken() {
return sessionToken;
}
public OperationType getOperationType() {
return operationType;
}
public int getStatusCode() {
return statusCode;
}
public int getSubStatusCode() {
return subStatusCode;
}
public String getRequestCharge() {
return requestCharge;
}
public RequestTimeline getRequestTimeline() {
return requestTimeline;
}
public ResourceType getResourceType() {
return resourceType;
}
public String getPartitionKeyRangeId() {
return partitionKeyRangeId;
}
}
public static SystemInformation fetchSystemInformation() {
SystemInformation systemInformation = new SystemInformation();
Runtime runtime = Runtime.getRuntime();
long totalMemory = runtime.totalMemory() / 1024;
long freeMemory = runtime.freeMemory() / 1024;
long maxMemory = runtime.maxMemory() / 1024;
systemInformation.usedMemory = totalMemory - freeMemory + " KB";
systemInformation.availableMemory = (maxMemory - (totalMemory - freeMemory)) + " KB";
systemInformation.availableProcessors = runtime.availableProcessors();
// TODO: other system related info also can be captured using a similar approach
systemInformation.systemCpuLoad = CpuMemoryMonitor
.getCpuLoad()
.toString();
return systemInformation;
}
}
| mit |
Azure/azure-sdk-for-java | sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/SentenceSentiment.java | 3831 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.ai.textanalytics.models;
import com.azure.ai.textanalytics.implementation.SentenceSentimentPropertiesHelper;
import com.azure.core.util.IterableStream;
/**
* The {@link SentenceSentiment} model that contains a sentiment label of a sentence, confidence scores of the
* sentiment label, sentence opinions, and offset of sentence within a document.
*/
public final class SentenceSentiment {
private final String text;
private final TextSentiment sentiment;
private final SentimentConfidenceScores confidenceScores;
private IterableStream<SentenceOpinion> opinions;
private int offset;
private int length;
/**
* Creates a {@link SentenceSentiment} model that describes the sentiment analysis of sentence.
*
* @param text The sentence text.
* @param sentiment The sentiment label of the sentence.
* @param confidenceScores The sentiment confidence score (Softmax score) between 0 and 1, for each sentiment label.
* Higher values signify higher confidence.
*/
public SentenceSentiment(String text, TextSentiment sentiment, SentimentConfidenceScores confidenceScores) {
this.text = text;
this.sentiment = sentiment;
this.confidenceScores = confidenceScores;
}
static {
SentenceSentimentPropertiesHelper.setAccessor(
new SentenceSentimentPropertiesHelper.SentenceSentimentAccessor() {
@Override
public void setOpinions(SentenceSentiment sentenceSentiment, IterableStream<SentenceOpinion> opinions) {
sentenceSentiment.setOpinions(opinions);
}
@Override
public void setOffset(SentenceSentiment sentenceSentiment, int offset) {
sentenceSentiment.setOffset(offset);
}
@Override
public void setLength(SentenceSentiment sentenceSentiment, int length) {
sentenceSentiment.setLength(length);
}
});
}
/**
* Gets the sentence text property.
*
* @return The text property value.
*/
public String getText() {
return this.text;
}
/**
* Gets the text sentiment label: POSITIVE, NEGATIVE, or NEUTRAL.
*
* @return The {@link TextSentiment}.
*/
public TextSentiment getSentiment() {
return sentiment;
}
/**
* Gets the confidence score of the sentiment label. All score values sum up to 1, the higher the score, the
* higher the confidence in the sentiment.
*
* @return The {@link SentimentConfidenceScores}.
*/
public SentimentConfidenceScores getConfidenceScores() {
return confidenceScores;
}
/**
* Gets the sentence opinions of sentence sentiment.
* This is only returned if you pass the opinion mining parameter to the analyze sentiment APIs.
*
* @return The sentence opinions of sentence sentiment.
*/
public IterableStream<SentenceOpinion> getOpinions() {
return opinions;
}
/**
* Gets the offset of sentence. The start position for the sentence in a document.
*
* @return The offset of sentence.
*/
public int getOffset() {
return offset;
}
/**
* Gets the length of sentence.
*
* @return The length of sentence.
*/
public int getLength() {
return length;
}
private void setOpinions(IterableStream<SentenceOpinion> opinions) {
this.opinions = opinions;
}
private void setOffset(int offset) {
this.offset = offset;
}
private void setLength(int length) {
this.length = length;
}
}
| mit |
nithinvnath/PAVProject | com.ibm.wala.core/src/com/ibm/wala/util/CancelRuntimeException.java | 1086 | /*******************************************************************************
* Copyright (c) 2007 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.wala.util;
/**
* An exception for when work is canceled in eclipse. This is identical to {@link CancelException}, but this one extends
* {@link RuntimeException}, so it need not be threaded through every API that uses it.
*/
public class CancelRuntimeException extends RuntimeException {
protected CancelRuntimeException(String msg) {
super(msg);
}
public CancelRuntimeException(Exception cause) {
super(cause);
}
public static CancelRuntimeException make(String msg) {
return new CancelRuntimeException(msg);
}
}
| mit |
CreaRo/dawebmail | app/src/main/java/com/sigmobile/dawebmail/asyncTasks/ViewMailListener.java | 250 | package com.sigmobile.dawebmail.asyncTasks;
import com.sigmobile.dawebmail.database.EmailMessage;
/**
* Created by rish on 6/10/15.
*/
public interface ViewMailListener {
void onPreView();
void onPostView(EmailMessage emailMessage);
}
| mit |
Deveo/jenkins-plugin | src/main/java/com/deveo/plugin/jenkins/DeveoEvent.java | 1741 | package com.deveo.plugin.jenkins;
import net.sf.json.JSONObject;
public class DeveoEvent {
private String target = "build";
private String operation;
private String project;
private String repository;
private String[] commits;
private String[] resources;
public DeveoEvent(String operation, DeveoRepository deveoRepository, String revisionId, String buildUrl) {
this.project = deveoRepository.getProjectId();
this.repository = deveoRepository.getId();
this.operation = operation;
this.commits = new String[]{revisionId};
this.resources = new String[]{buildUrl};
}
public String toJSON() {
JSONObject json = new JSONObject();
json.put("event", JSONObject.fromObject(this));
return json.toString();
}
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
public String getOperation() {
return operation;
}
public void setOperation(String operation) {
this.operation = operation;
}
public String getProject() {
return project;
}
public void setProject(String project) {
this.project = project;
}
public String getRepository() {
return repository;
}
public void setRepository(String repository) {
this.repository = repository;
}
public String[] getCommits() {
return commits;
}
public void setCommits(String[] commit) {
this.commits = commit;
}
public String[] getResources() {
return resources;
}
public void setResources(String[] resources) {
this.resources = resources;
}
}
| mit |
yildiz-online/module-graphic-ogre | src/main/java/jni/JniParticleScaleAffector.java | 1681 | /*
* This file is part of the Yildiz-Engine project, licenced under the MIT License (MIT)
*
* Copyright (c) 2019 Grégory Van den Borre
*
* More infos available: https://engine.yildiz-games.be
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package jni;
/**
* @author Grégory Van den Borre
*/
public class JniParticleScaleAffector {
/**
* Scale the particle in native code.
*
* @param pointer Address to the native object.
* @param width Width scale per second.
* @param height Height scale per second.
*/
public native void setScale(final long pointer, final float width, final float height);
}
| mit |
awesome-raccoons/gqt | src/main/java/models/PolygonModel.java | 2643 | package models;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.CoordinateSequence;
import com.vividsolutions.jts.geom.Polygon;
import com.vividsolutions.jts.geom.LineString;
import com.vividsolutions.jts.geom.Geometry;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import java.util.ArrayList;
/**
* Created by thea on 22/09/15.
*/
public class PolygonModel extends GeometryModel {
public PolygonModel(final Geometry geometry, final AnchorPane group) {
super(geometry, group);
}
public final ArrayList<Circle> drawAndCreateToolTips(final GraphicsContext graphicsContext) {
ArrayList<Circle> tooltips = new ArrayList<>();
Coordinate[] coordinates = this.getGeometry().getCoordinates();
Coordinate[] origCoordinates = this.getOriginalGeometry().getCoordinates();
double[] xCoordinates = new double[coordinates.length];
double[] yCoordinates = new double[coordinates.length];
for (int i = 0; i < coordinates.length; i++) {
xCoordinates[i] = coordinates[i].x;
yCoordinates[i] = coordinates[i].y;
Circle tooltip = createToolTip(coordinates[i].x, coordinates[i].y,
origCoordinates[i].x, origCoordinates[i].y, Color.BLACK);
tooltips.add(tooltip);
}
graphicsContext.fillPolygon(xCoordinates, yCoordinates, coordinates.length);
drawOutLines(graphicsContext);
return tooltips;
}
private void strokeCoordinateSequence(final CoordinateSequence cs,
final GraphicsContext graphicsContext) {
for (int i = 1; i < cs.size(); i++) {
graphicsContext.strokeLine(cs.getCoordinate(i - 1).x, cs.getCoordinate(i - 1).y,
cs.getCoordinate(i).x, cs.getCoordinate(i).y);
}
}
private void drawOutLines(final GraphicsContext graphicsContext) {
Polygon polygon = (Polygon) getGeometry();
graphicsContext.setStroke(Color.BLACK);
if (polygon.getNumInteriorRing() > 0) {
int interiorRings = polygon.getNumInteriorRing();
for (int x = 0; x < interiorRings; x++) {
LineString hole = polygon.getInteriorRingN(x);
strokeCoordinateSequence(hole.getCoordinateSequence(), graphicsContext);
}
}
LineString outer = polygon.getExteriorRing();
strokeCoordinateSequence(outer.getCoordinateSequence(), graphicsContext);
}
}
| mit |
nevihta/knjiznicaRIS | knjiznica/src/ris/projekt/knjiznica/beans/VrstaGradiva.java | 430 | package ris.projekt.knjiznica.beans;
public class VrstaGradiva {
private int id;
private String naziv;
public VrstaGradiva(){
}
public VrstaGradiva(int id, String naziv){
this.id=id;
this.naziv=naziv;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNaziv() {
return naziv;
}
public void setNaziv(String naziv) {
this.naziv = naziv;
}
}
| mit |
robotis/heklapunch | src/is/heklapunch/KeppaActivity.java | 10260 | /*
* Activity for competiton part
*
* logip@hi.is
*/
package is.heklapunch;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
public class KeppaActivity extends Activity {
TableLayout station_table;
SQLHandler handler;
long time;
boolean isTimeChecked;
TextView brautTitle;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_keppa);
// create database object
handler = new SQLHandler(this);
// Set time object
this.fillTime();
// make table
station_table = (TableLayout) findViewById(R.id.station_table);
this.fillTable();
}
/**
* Setur upp tengingu við tímaþjón
* */
protected void fillTime() {
// Set time object
if (isOnline()) {
// Use json service http://json-time.appspot.com/time.json?tz=GMT
@SuppressLint("NewApi")
class GetTimeFromServer extends AsyncTask<String, Void, String> {
public KeppaActivity activity;
public GetTimeFromServer(KeppaActivity a) {
activity = a;
}
@Override
protected String doInBackground(String... urls) {
String url = urls[0];
String response = "";
// Log.v("tester", "execute request");
HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse;
HttpGet getRequest = new HttpGet(url);
try {
httpResponse = client.execute(getRequest);
HttpEntity entity = httpResponse.getEntity();
// Log.v("entity test", entity.getContent().toString());
if (entity != null) {
// Log.v("tester", "execute entity er ekki núll");
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(instream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder(100000);
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
instream.close();
} catch (IOException e) {
}
response = sb.toString();
Log.v("tester",
"hér er response size: "
+ response.length());
instream.close();
}
} catch (Exception e) {
Log.v("tester",
"villa í execute request: " + e.toString());
}
return response;
}
@Override
protected void onPostExecute(String result) {
// Log.v("Logatest onPostExecute", result);
activity.setTime(result);
}
}// inner class end
// run inner class and correct the time of the app
GetTimeFromServer task = new GetTimeFromServer(this);
// set the time object
task.execute(new String[] { "http://date.jsontest.com/" });
isTimeChecked = true;
} else {
time = System.currentTimeMillis();
isTimeChecked = false;
}
}
// fill table with content
@SuppressLint("NewApi")
public void fillTable() {
TableRow row;
TextView t1, t2, t3;
// Converting to dip unit
ArrayList<ArrayList<String>> results = handler.getAllStations();
Iterator<ArrayList<String>> i = results.iterator();
// Make header for table if there are results
if (i.hasNext()) {
TextView h1, h2, h3;
row = new TableRow(this);
h1 = new TextView(this);
h2 = new TextView(this);
h3 = new TextView(this);
h1.setText("Stöð");
h2.setText("Tími");
h3.setText("Millitími");
h1.setTextSize(17);
h2.setTextSize(17);
h3.setTextSize(17);
h1.setTextColor(Color.WHITE);
h2.setTextColor(Color.WHITE);
h3.setTextColor(Color.WHITE);
row.addView(h1);
row.addView(h2);
row.addView(h3);
station_table.addView(row, new TableLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
}
Long temp = new Long("0");
//make time rows
while (i.hasNext()) {
ArrayList<?> entry = i.next();
row = new TableRow(this);
t1 = new TextView(this);
t2 = new TextView(this);
t3 = new TextView(this);
t1.setText(entry.get(3).toString());
// fix date
String longV = entry.get(1).toString();
long millisecond = Long.parseLong(longV);
String dateString = DateFormat.format("kk:mm:ss",
new Date(millisecond)).toString();
t2.setText(dateString);
//split time
Long milli = millisecond - temp;
//check for first entry
if(milli.equals(millisecond)){
milli = new Long("0");
}
String dateString2 = DateFormat.format("kk:mm:ss",
new Date(milli)).toString();
t3.setText(dateString2);
//keep time
temp = millisecond;
t1.setTypeface(null, 1);
// t1.setWidth(130);
t2.setTypeface(null, 1);
t3.setTypeface(null, 1);
t1.setTextSize(15);
t2.setTextSize(15);
t3.setTextSize(15);
t1.setPadding(0, 0, 15, 0);
t2.setPadding(0, 0, 15, 0);
t3.setPadding(0, 0, 15, 0);
t1.setTextColor(Color.WHITE);
t2.setTextColor(Color.GREEN);
t3.setTextColor(Color.RED);
row.addView(t1);
row.addView(t2);
row.addView(t3);
station_table.addView(row, new TableLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
}
}
// Go to organize mode
public void send_info_bt(View view) {
Intent o = new Intent(this, SendActivity.class);
startActivity(o);
}
public void send_info_json(View view) {
Intent o = new Intent(this, SendJSONActivity.class);
}
// Go to organize mode
public void read_qr(View view) {
IntentIntegrator integrator = new IntentIntegrator(this);
integrator.initiateScan();
}
// Delete all stations from the view and db
public void delete(View view) {
handler.deleteAll();
// redraw view
TableLayout vg = (TableLayout) findViewById(R.id.station_table);
vg.removeAllViews();
}
// QR Scan result
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode != 44) {
boolean isTimeChecked = false;
IntentResult scanResult = IntentIntegrator.parseActivityResult(
requestCode, resultCode, intent
);
if (scanResult != null
&& scanResult.getContents() != null
&& scanResult.getContents().length() != 0) {
// handle scan result
Toast.makeText(this, scanResult.getContents(),
Toast.LENGTH_SHORT).show();
// Set time object
time = System.currentTimeMillis();
// write to db
handler.addStation(
"Stöð " + Integer.toString(handler.count() + 30), time,
scanResult.getContents(), isTimeChecked, this.getGPS());
// redraw view
TableLayout vg = (TableLayout) findViewById(R.id.station_table);
vg.removeAllViews();
// redraw table
this.fillTable();
} else {
Toast.makeText(this, "No scan", Toast.LENGTH_SHORT).show();
}
}
}
// get gps points from last known location
private String getGPS() {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
List<String> providers = lm.getProviders(true);
Location l = null;
for (int i = providers.size() - 1; i >= 0; i--) {
l = lm.getLastKnownLocation(providers.get(i));
if (l != null)
break;
}
// double[] gps = new double[2];
String loc = "null";
if (l != null) {
loc = "";
// Log.d("Loga gps test", "Location not null");
Log.d("Loga gps test", Double.toString(l.getLatitude()));
loc = loc + Double.toString(l.getLatitude());
loc = loc + Double.toString(l.getLongitude());
}
return loc;
}
/*
* Check if we are online <jtm@hi.is>
*/
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
/*
* Set correct time by using a string from json service <logip@hi.is>
*/
public void setTime(String json) {
Gson gson = new Gson();
TimeItemResult jsonResult = gson.fromJson(json, TimeItemResult.class);
Log.d("Loga time test", "Setting time with internet");
// Calendar c = Calendar.getInstance();
// Phone date used but time taken from server
// c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH),
// c.get(Calendar.DAY_OF_MONTH), jsonResult.hour, jsonResult.minute,
// jsonResult.second);
this.time = jsonResult.milliseconds_since_epoch;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_keppa, menu);
return true;
}
@Override
//Handle menu clicks
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.keppa_senda:
this.send_info_bt(this.getCurrentFocus());
return true;
case R.id.keppa_henda:
delete(this.getCurrentFocus());
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
| mit |
xinerd/algorithm | LeetCode/src/cn/fmachine/lintcode/easy/APlusBProblem.java | 1380 | package cn.fmachine.lintcode.easy;
/**
* Write a function that add two numbers A and B. You should not use + or any arithmetic operators.
* <p>
* Notice
* <p>
* There is no need to read data from standard input stream. Both parameters are given in function aplusb, you job is to calculate the sum and return it.
* <p>
* Have you met this question in a real interview? Yes
* Clarification
* Are a and b both 32-bit integers?
* <p>
* Yes.
* Can I use bit operation?
* <p>
* Sure you can.
* Example
* Given a=1 and b=2 return 3
* <p>
* Challenge
* Of course you can just return a + b to get accepted. But Can you challenge not do it like that?
* <p>
* Tags
* Cracking The Coding Interview Bit Manipulation
* <p>
* algorithm
* Author: XIN MING
* Date: 10/23/16
*
*
*/
public class APlusBProblem {
/**
* xor ^ : 不进位加法
* and & : 11=1 carry position
* << : << 1 carry
* example:
* 0101
* 0100
* 0001 ^ 1
*
* 0100 & 2
* 1000 2<<1 1000&0001 = 0
*
* 1001 1^2
* param a: The first integer
* param b: The second integer
* return: The sum of a and b
*/
public int aplusb(int a, int b) {
while (b != 0) {
int xor = a ^ b;
int carry = (a & b) << 1;
a = xor;
b = carry;
}
return a;
}
}
| mit |
dacduong/escpos-printer-simulator | src/biz/iteksolutions/escpos/parser/GraphicsDataCommand.java | 99 | package biz.iteksolutions.escpos.parser;
public class GraphicsDataCommand extends DataCommand {
}
| mit |
Glockshna/ColossalChests | src/main/java/org/cyclops/colossalchests/block/Interface.java | 8030 | package org.cyclops.colossalchests.block;
import net.minecraft.block.Block;
import net.minecraft.block.SoundType;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyBool;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.BlockRenderLayer;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.Vec3i;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.cyclops.colossalchests.tileentity.TileColossalChest;
import org.cyclops.colossalchests.tileentity.TileInterface;
import org.cyclops.cyclopscore.block.multi.CubeDetector;
import org.cyclops.cyclopscore.block.property.BlockProperty;
import org.cyclops.cyclopscore.block.property.BlockPropertyManagerComponent;
import org.cyclops.cyclopscore.config.configurable.ConfigurableBlockContainer;
import org.cyclops.cyclopscore.config.extendedconfig.BlockConfig;
import org.cyclops.cyclopscore.config.extendedconfig.ExtendedConfig;
import org.cyclops.cyclopscore.helper.MinecraftHelpers;
import org.cyclops.cyclopscore.helper.TileHelpers;
import java.util.List;
/**
* Part of the Colossal Blood Chest multiblock structure.
* @author rubensworks
*
*/
public class Interface extends ConfigurableBlockContainer implements CubeDetector.IDetectionListener {
@BlockProperty
public static final PropertyBool ACTIVE = ColossalChest.ACTIVE;
@BlockProperty
public static final PropertyMaterial MATERIAL = ColossalChest.MATERIAL;
private static Interface _instance = null;
/**
* Get the unique instance.
* @return The instance.
*/
public static Interface getInstance() {
return _instance;
}
public Interface(ExtendedConfig<BlockConfig> eConfig) {
super(eConfig, Material.ROCK, TileInterface.class);
this.setHardness(5.0F);
this.setSoundType(SoundType.WOOD);
this.setHarvestLevel("axe", 0); // Wood tier
}
@Override
public boolean getUseNeighborBrightness(IBlockState state) {
return true;
}
@Override
public boolean isToolEffective(String type, IBlockState state) {
return ColossalChest.isToolEffectiveShared(type, state);
}
@SideOnly(Side.CLIENT)
@Override
public BlockRenderLayer getBlockLayer() {
return BlockRenderLayer.CUTOUT_MIPPED;
}
@SideOnly(Side.CLIENT)
@Override
public boolean isOpaqueCube(IBlockState blockState) {
return false;
}
@SideOnly(Side.CLIENT)
@Override
public boolean isFullCube(IBlockState blockState) {
return false;
}
@Override
public boolean canCreatureSpawn(IBlockState blockState, IBlockAccess world, BlockPos pos, EntityLiving.SpawnPlacementType type) {
return false;
}
@Override
public void onBlockPlacedBy(World world, BlockPos pos, IBlockState state, EntityLivingBase placer, ItemStack stack) {
super.onBlockPlacedBy(world, pos, state, placer, stack);
ColossalChest.triggerDetector(world, pos, true);
}
@Override
public void onBlockAdded(World world, BlockPos blockPos, IBlockState blockState) {
super.onBlockAdded(world, blockPos, blockState);
if(world.getBlockState(blockPos).getBlock() != blockState.getBlock()) {
ColossalChest.triggerDetector(world, blockPos, true);
}
}
@Override
public void breakBlock(World world, BlockPos pos, IBlockState state) {
if((Boolean)state.getValue(ACTIVE)) ColossalChest.triggerDetector(world, pos, false);
super.breakBlock(world, pos, state);
}
@Override
protected void onPreBlockDestroyed(World world, BlockPos blockPos) {
// Don't drop items in inventory.
}
@Override
public void onDetect(World world, BlockPos location, Vec3i size, boolean valid, BlockPos originCorner) {
Block block = world.getBlockState(location).getBlock();
if(block == this) {
boolean change = !(Boolean) world.getBlockState(location).getValue(ACTIVE);
world.setBlockState(location, world.getBlockState(location).withProperty(ACTIVE, valid), MinecraftHelpers.BLOCK_NOTIFY_CLIENT);
if(change) {
BlockPos tileLocation = ColossalChest.getCoreLocation(world, location);
TileInterface tile = TileHelpers.getSafeTile(world, location, TileInterface.class);
if(tile != null && tileLocation != null) {
tile.setCorePosition(tileLocation);
TileColossalChest core = TileHelpers.getSafeTile(world, tileLocation, TileColossalChest.class);
if (core != null) {
core.addInterface(location);
}
}
}
}
}
@Override
public boolean onBlockActivated(World world, BlockPos blockPos, IBlockState blockState, EntityPlayer player,
EnumHand hand, ItemStack heldItem, EnumFacing side,
float posX, float posY, float posZ) {
if(blockState.getValue(ACTIVE)) {
BlockPos tileLocation = ColossalChest.getCoreLocation(world, blockPos);
if(tileLocation != null) {
world.getBlockState(tileLocation).getBlock().
onBlockActivated(world, tileLocation, world.getBlockState(tileLocation),
player, hand, heldItem, side, posX, posY, posZ);
return true;
}
} else {
ColossalChest.addPlayerChatError(world, blockPos, player, hand);
}
return super.onBlockActivated(world, blockPos, blockState, player, hand, heldItem, side, posX, posY, posZ);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public void getSubBlocks(Item item, CreativeTabs creativeTabs, List list) {
for(PropertyMaterial.Type material : PropertyMaterial.Type.values()) {
list.add(new ItemStack(getInstance(), 1, material.ordinal()));
}
}
@Override
protected BlockStateContainer createBlockState() {
return (propertyManager = new BlockPropertyManagerComponent(this,
new BlockPropertyManagerComponent.PropertyComparator() {
@Override
public int compare(IProperty o1, IProperty o2) {
return o2.getName().compareTo(o1.getName());
}
},
new BlockPropertyManagerComponent.UnlistedPropertyComparator())).createDelegatedBlockState();
}
@Override
public IBlockState onBlockPlaced(World worldIn, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer) {
// Meta * 2 because we always want the inactive state
return super.onBlockPlaced(worldIn, pos, facing, hitX, hitY, hitZ, meta * 2, placer);
}
@Override
public int damageDropped(IBlockState state) {
return state.getValue(ColossalChest.MATERIAL).ordinal();
}
@Override
public boolean isKeepNBTOnDrop() {
return false;
}
@Override
public boolean canPlaceBlockAt(World worldIn, BlockPos pos) {
return super.canPlaceBlockAt(worldIn, pos) && ColossalChest.canPlace(worldIn, pos);
}
@Override
public boolean canSilkHarvest(World world, BlockPos pos, IBlockState state, EntityPlayer player) {
return false;
}
}
| mit |
askluolei/mytemplate | src/main/java/com/luolei/template/datasources/DynamicDataSourceConfig.java | 1134 | package com.luolei.template.datasources;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
import javax.sql.DataSource;
/**
* 配置多数据源
*
* @author luolei
* @email askluolei@gmail.com
* @date 2017/10/12 23:27
*/
@Profile("dev")
@Configuration
public class DynamicDataSourceConfig {
@Bean
@ConfigurationProperties("spring.datasource.druid.first")
@Primary
@Qualifier(DataSourceNames.FIRST)
public DataSource firstDataSource(){
return DruidDataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties("spring.datasource.druid.second")
@Qualifier(DataSourceNames.SECOND)
public DataSource secondDataSource(){
return DruidDataSourceBuilder.create().build();
}
}
| mit |
bauer-matthews/SPAN | src/main/java/protocol/ReachabilityProtocol.java | 3248 | package protocol;
import com.google.common.base.MoreObjects;
import org.apfloat.Aprational;
import protocol.role.Role;
import rewriting.Rewrite;
import rewriting.Signature;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* SPAN - Stochastic Protocol Analyzer
* <p>
* Created: 5/22/17
*
* @author Matthew S. Bauer
* @version 1.0
*/
public class ReachabilityProtocol {
private final Metadata metadata;
private final Signature signature;
private final Collection<Rewrite> rewrites;
private final Map<String, Aprational> fractionConstants;
private final List<Role> roles;
private final SafetyProperty safetyProperty;
ReachabilityProtocol(Metadata metadata, Signature signature, Collection<Rewrite> rewrites,
Map<String, Aprational> fractionConstants, List<Role> roles, SafetyProperty safetyProperty) {
Objects.requireNonNull(metadata);
Objects.requireNonNull(signature);
Objects.requireNonNull(rewrites);
Objects.requireNonNull(fractionConstants);
Objects.requireNonNull(roles);
Objects.requireNonNull(safetyProperty);
this.metadata = metadata;
this.signature = signature;
this.rewrites = rewrites;
this.fractionConstants = fractionConstants;
this.roles = roles;
this.safetyProperty = safetyProperty;
}
public String getProtocolVersion() {
return this.metadata.getVersion();
}
public Signature getSignature() {
return this.signature;
}
public Collection<Rewrite> getRewrites() {
return this.rewrites;
}
public Map<String, Aprational> getFractionConstants() {
return this.fractionConstants;
}
public List<Role> getRoles() {
return roles;
}
public Metadata getMetadata() {
return metadata;
}
public SafetyProperty getSafetyProperty() {
return safetyProperty;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof ReachabilityProtocol)) {
return false;
}
if (!metadata.equals(((ReachabilityProtocol) o).metadata)) return false;
if (!signature.equals(((ReachabilityProtocol) o).signature)) return false;
if (!rewrites.equals(((ReachabilityProtocol) o).rewrites)) return false;
if (!fractionConstants.equals(((ReachabilityProtocol) o).fractionConstants)) return false;
if (!roles.equals(((ReachabilityProtocol) o).roles)) return false;
if (!safetyProperty.equals(((ReachabilityProtocol) o).safetyProperty)) return false;
return true;
}
@Override
public int hashCode() {
return Objects.hash(metadata, signature, rewrites, fractionConstants, roles, safetyProperty);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("metadata", metadata)
.add("signature", signature)
.add("rewrites", rewrites)
.add("fraction constants", fractionConstants)
.add("roles", roles)
.add("safety property", safetyProperty)
.toString();
}
}
| mit |
torebre/EarTrainingAndroid | app/src/androidTest/java/com/kjipo/eartraining/tests/MainActivityTest.java | 504 | package com.kjipo.eartraining.tests;
import android.test.ActivityInstrumentationTestCase2;
public class MainActivityTest
extends ActivityInstrumentationTestCase2<MainActivity> {
private MainActivity mainActivity;
public MainActivityTest() {
super(MainActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
mainActivity = getActivity();
// TODO
}
}
| mit |
skomarica/java-web-series | 3-blog-webapp/src/main/java/rs/pstech/workshop/javaweb/blog/model/Comment.java | 1385 | package rs.pstech.workshop.javaweb.blog.model;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "comment")
public class Comment implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "comment_id")
@GeneratedValue
private Long id;
@Column
private String content;
@Column
private String author;
@Column
private Date created;
@ManyToOne
@JoinColumn(name = "blog_id")
private Blog blog;
public Comment() {
super();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Blog getBlog() {
return blog;
}
public void setBlog(Blog blog) {
this.blog = blog;
}
}
| mit |
denkers/graphi | src/com/graphi/tasks/SimulateNetworkTask.java | 3089 | //=========================================
// Kyle Russell
// AUT University 2015
// https://github.com/denkers/graphi
//=========================================
package com.graphi.tasks;
import com.graphi.display.layout.ControlPanel;
import com.graphi.sim.generator.BerbasiGenerator;
import com.graphi.sim.generator.KleinbergGenerator;
import com.graphi.sim.generator.NetworkGenerator;
import com.graphi.sim.generator.RandomNetworkGenerator;
import javax.swing.JOptionPane;
public class SimulateNetworkTask extends AbstractTask
{
@Override
public void initTaskDetails()
{
setTaskName("Simulate network");
}
@Override
public void initDefaultProperties()
{
MappedProperty prop = new MappedProperty();
prop.setName("kleinberg");
prop.setParamValue("latSize", "15");
prop.setParamValue("exp", "2.0");
setProperty("Generator", prop.toString());
setProperty("Generate directed edges", "false");
setProperty("Directed edge chance", "0.0");
}
@Override
public void performTask()
{
String genAlgorithmStr = (String) getProperty("Generator");
MappedProperty genProp = new MappedProperty(genAlgorithmStr);
String genName = genProp.getName();
NetworkGenerator gen;
switch(genName)
{
case "berbasi": gen = getBASim(genProp); break;
case "kleinberg": gen = getKleinbergSim(genProp); break;
case "random": gen = getRASim(genProp); break;
default: gen = null;
}
if(gen == null)
JOptionPane.showMessageDialog(null, "Invalid generator algorithm");
else
{
ControlPanel.getInstance().getSimulationPanel()
.executeGeneratorSim(gen);
}
}
protected NetworkGenerator getBASim(MappedProperty properties)
{
int m = Integer.parseInt(properties.getParamValue("i"));
int n = Integer.parseInt(properties.getParamValue("n"));
Object dirParam = properties.getParamValue("dir");
boolean dir = dirParam != null && ((String) dirParam).equals("true");
return new BerbasiGenerator(m, n, dir);
}
protected NetworkGenerator getRASim(MappedProperty properties)
{
int n = Integer.parseInt(properties.getParamValue("n"));
double p = properties.getDoubleParamValue("p");
Object dirParam = properties.getParamValue("dir");
boolean dir = dirParam != null && ((String) dirParam).equals("true");
return new RandomNetworkGenerator(n, p, dir);
}
protected NetworkGenerator getKleinbergSim(MappedProperty properties)
{
int latticeSize = Integer.parseInt(properties.getParamValue("latSize"));
double clusterExp = Double.parseDouble(properties.getParamValue("exp"));
return new KleinbergGenerator(latticeSize, clusterExp);
}
}
| mit |
GlowstonePlusPlus/Bukkit2Sponge | src/main/java/net/glowstone/bukkit2sponge/item/ShinyItemTypes.java | 450 | package net.glowstone.bukkit2sponge.item;
import org.spongepowered.api.item.ItemType;
/**
* Todo: Javadoc for ShinyItemTypes.
*/
public final class ShinyItemTypes {
private ShinyItemTypes() {
}
public static final ItemType IRON_SHOVEL = new ShinyItemType("iron_shovel");
public static final ItemType IRON_PICKAXE = new ShinyItemType("iron_pickaxe");
public static final ItemType IRON_AXE = new ShinyItemType("iron_axe");
}
| mit |
JiongboZhu/ucaruhome-oss-integration | samples/OSSCorsSample.java | 3325 | import java.util.ArrayList;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.SetBucketCORSRequest;
import com.aliyun.oss.model.SetBucketCORSRequest.CORSRule;
public class OSSCorsSample{
private static final String ACCESS_ID = OSSConfig.ACCESS_KEY_ID;
private static final String ACCESS_KEY = OSSConfig.ACCESS_KEY_SECRET;
private static final String OSS_ENDPOINT = OSSConfig.OSS_ENDPOINT;
private static final String BUCKET_NAME = OSSConfig.TEST_BUCKET_NAME;
public static void main(String[] args) {
OSSClient oss = new OSSClient(OSS_ENDPOINT, ACCESS_ID, ACCESS_KEY);
oss.createBucket(BUCKET_NAME);
//put
SetBucketCORSRequest request = new SetBucketCORSRequest("");
request.setBucketName(BUCKET_NAME);
ArrayList<CORSRule> putCorsRules = new ArrayList<CORSRule>();
CORSRule corRule = new CORSRule(); //CORS规则的容器,每个bucket最多允许10条规则
ArrayList<String> allowedOrigin = new ArrayList<String>();
allowedOrigin.add( "http://www.ucaruhome.com");//指定允许跨域请求的来源
ArrayList<String> allowedMethod = new ArrayList<String>();
allowedMethod.add("GET"); //指定允许的跨域请求方法(GET/PUT/DELETE/POST/HEAD)
ArrayList<String> allowedHeader = new ArrayList<String>();
allowedHeader.add("x-oss-test"); //控制在OPTIONS预取指令中Access-Control-Request-Headers头中指定的header是否允许。
ArrayList<String> exposedHeader = new ArrayList<String>();
exposedHeader.add("x-oss-test1"); //指定允许用户从应用程序中访问的响应头
corRule.setAllowedMethods(allowedMethod);
corRule.setAllowedOrigins(allowedOrigin);
corRule.setAllowedHeaders(allowedHeader);
corRule.setExposeHeaders(exposedHeader);
corRule.setMaxAgeSeconds(10); //指定浏览器对特定资源的预取(OPTIONS)请求返回结果的缓存时间,单位为秒。
putCorsRules.add(corRule); //最多允许10条规则
request.setCorsRules(putCorsRules);
oss.setBucketCORS(request);
//get
ArrayList<CORSRule> corsRules;
corsRules = (ArrayList<CORSRule>) oss.getBucketCORSRules(BUCKET_NAME);
for (CORSRule rule : corsRules) {
for (String allowedOrigin1 : rule.getAllowedOrigins()) {
System.out.println(allowedOrigin1);
}
for (String allowedMethod1 : rule.getAllowedMethods()) {
System.out.println(allowedMethod1);
}
if (rule.getAllowedHeaders().size() > 0){
for (String allowedHeader1 : rule.getAllowedHeaders()){
System.out.println(allowedHeader1);
}
}
if (rule.getExposeHeaders().size() > 0){
for (String exposeHeader : rule.getExposeHeaders()){
System.out.println(exposeHeader);
}
}
if ( null != rule.getMaxAgeSeconds()){
System.out.println(rule.getMaxAgeSeconds());
}
}
//delete
oss.deleteBucketCORSRules(BUCKET_NAME);
}
}
/*Output:
*http://www.b.com
*GET
*x-oss-test
*10
*/
| mit |
jfvh/AutoValueGenerator | src/Generator.java | 3452 | import model.JavaClassRepresentation;
import model.Keywords;
import model.NamedTypes;
import java.io.IOException;
/**
* Created by jvanheijst on 12/6/16.
*/
public class Generator {
public static String generateAutovalueClass(String codeInput) throws IOException {
JavaClassRepresentation javaClassRepresentation = ClassParser.getJavaClassRepresentation(codeInput);
//remove last }, so the functions are kept inside the class todo: check if necessary
int indexOfBracket = codeInput.lastIndexOf('}');
StringBuilder sb = new StringBuilder(codeInput);
codeInput = sb.deleteCharAt(indexOfBracket).toString();
String[] lines = codeInput.split(System.getProperty("line.separator"));
String templine;
int lastParamLineNumber = -1; //needed for placement of the
for (int i = 0; i < lines.length; i++) {
templine = lines[i];
if (i == 0) {
if (templine.contains("package")) {
templine = templine + "\n\n import com.google.auto.value.AutoValue; \n \n";
} else {
templine = "\n\n import com.google.auto.value.AutoValue; \n \n" + templine;
}
}
if (templine.contains(javaClassRepresentation.getClassName())) {
templine = Keywords.removeKeywords(templine);
templine = "@AutoValue \npublic abstract " + templine;
}
for (NamedTypes namedTypes : javaClassRepresentation.getParameterList()) {
if (templine.contains(namedTypes.toString())) { //todo: implement ignore spaces
templine = "public abstract " + namedTypes.toString() + "(); \n";
lastParamLineNumber = i;
}
}
lines[i] = templine + "\n ";
}
if (lastParamLineNumber == -1) {
throw new IOException("No parameters found");
}
lines[lastParamLineNumber] = lines[lastParamLineNumber] + getBuilderPart(javaClassRepresentation);
return combineArray(lines) + "\n }";
}
private static String combineArray(String[] strings) {
String output = "";
for (String string : strings) {
output += string;
}
return output;
}
private static String getBuilderPart(JavaClassRepresentation javaClassRepresentation) {
StringBuilder builder = new StringBuilder();
builder.append("public static Builder builder(){").append("\n");
builder.append(" return new AutoValue_").append(javaClassRepresentation.getClassName()).append(".Builder();").append("\n");
builder.append("}").append("\n");
builder.append("\n");
builder.append("@AutoValue.Builder").append("\n");
builder.append("public abstract static class Builder {").append("\n");
builder.append("\n");
for (NamedTypes namedTypes : javaClassRepresentation.getParameterList()) {
builder.append("public abstract Builder ").append(namedTypes.getName()).append("(").append(namedTypes.getType()).append(" ").append(namedTypes.getName()).append(");").append("\n");
builder.append("\n");
}
builder.append("public abstract ").append(javaClassRepresentation.getClassName()).append(" build();").append("\n");
builder.append(" \n } \n");
return builder.toString();
}
}
| mit |
ctkdev/blogJhipster | src/main/java/com/ctkdev/web/filter/gzip/GzipResponseHeadersNotModifiableException.java | 263 | package com.ctkdev.web.filter.gzip;
import javax.servlet.ServletException;
public class GzipResponseHeadersNotModifiableException extends ServletException {
public GzipResponseHeadersNotModifiableException(String message) {
super(message);
}
}
| mit |
ARISGames/aris-android-client | app/src/main/java/edu/uoregon/casls/aris_android/data_objects/Event.java | 479 | package edu.uoregon.casls.aris_android.data_objects;
/**
* Created by smorison on 8/19/15.
*/
public class Event {
public long event_id = 0;
public long event_package_id = 0;
public String event = "GIVE_ITEM_PLAYER";
public long content_id = 0;
public long qty = 0;
public long icon_media_id = 0; // may be irrelevant
public String name = ""; // may be irrelevant
public String script = "";
}
| mit |
molcikas/photon | photon-core/src/main/java/com/github/molcikas/photon/options/DefaultTableName.java | 116 | package com.github.molcikas.photon.options;
public enum DefaultTableName
{
ClassName,
ClassNameLowerCase
}
| mit |
why168/LoopViewPagerLayout | app/src/main/java/com/edwin/loopviewpager/fragment/ZoomLoopViewPagerFragment.java | 3331 | package com.edwin.loopviewpager.fragment;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.edwin.loopviewpager.R;
import com.edwin.loopviewpager.base.BaseFragment;
import com.edwin.loopviewpager.loader.OnFrescoImageViewLoader;
import com.github.why168.LoopViewPagerLayout;
import com.github.why168.listener.OnBannerItemClickListener;
import com.github.why168.modle.BannerInfo;
import com.github.why168.modle.IndicatorLocation;
import com.github.why168.modle.LoopStyle;
import com.github.why168.utils.L;
import java.util.ArrayList;
/**
* Zoom
* LoopViewPagerFragment
*
* @author Edwin.Wu
* @version 2016/11/7 17:27
* @since JDK1.8
*/
public class ZoomLoopViewPagerFragment extends BaseFragment implements OnBannerItemClickListener {
private LoopViewPagerLayout mLoopViewPagerLayout;
public static ZoomLoopViewPagerFragment getInstance() {
return new ZoomLoopViewPagerFragment();
}
@Override
protected int getLayoutId() {
return R.layout.fragment_loop_viewpager;
}
@Override
protected void initView(View view, Bundle savedInstanceState) {
mLoopViewPagerLayout = (LoopViewPagerLayout) view.findViewById(R.id.mLoopViewPagerLayout);
}
@Override
protected void initData() {
//TODO 设置LoopViewPager参数
mLoopViewPagerLayout.setLoop_ms(2000);//轮播的速度(毫秒)
mLoopViewPagerLayout.setLoop_duration(1000);//滑动的速率(毫秒)
mLoopViewPagerLayout.setLoop_style(LoopStyle.Zoom);//轮播的样式-深度depth
mLoopViewPagerLayout.setIndicatorLocation(IndicatorLocation.Right);//指示器位置-右Right
L.e("LoopViewPager Zoom 参数设置完毕");
//TODO 初始化
mLoopViewPagerLayout.initializeData(mActivity);
//TODO 准备数据
ArrayList<BannerInfo> bannerInfos = new ArrayList<>();
bannerInfos.add(new BannerInfo<String>("http://t1.mmonly.cc/uploads/tu/201710/9999/84ca7d2fb4.jpg", "第一张图片"));
bannerInfos.add(new BannerInfo<String>("http://t1.mmonly.cc/uploads/tu/201710/9999/70d59c5cac.jpg", "第二张图片"));
bannerInfos.add(new BannerInfo<String>("http://t1.mmonly.cc/uploads/tu/zyf/tt/20160324/hbanh31xprw.jpg", "第三张图片"));
bannerInfos.add(new BannerInfo<String>("http://t1.mmonly.cc/uploads/allimg/tuku2/16321JO7-0.jpg", "第四张图片"));
bannerInfos.add(new BannerInfo<String>("http://t1.mmonly.cc/uploads/tu/bj/20160304/afy1mp4cji2.jpg", "第五张图片"));
//TODO 设置监听
mLoopViewPagerLayout.setOnLoadImageViewListener(new OnFrescoImageViewLoader());
mLoopViewPagerLayout.setOnBannerItemClickListener(this);
//TODO 设置数据
mLoopViewPagerLayout.setLoopData(bannerInfos);
}
@Override
public void onBannerClick(int index, ArrayList<BannerInfo> banner) {
Toast.makeText(mActivity, "index = " + index + " title = " + banner.get(index).title, Toast.LENGTH_SHORT).show();
}
@Override
public void onStart() {
//TODO 开始循环
mLoopViewPagerLayout.startLoop();
super.onStart();
}
@Override
public void onStop() {
//TODO 停止循环
mLoopViewPagerLayout.stopLoop();
super.onStop();
}
}
| mit |
lzz5235/Code-Segment | Java/Chat/ChatServer.java | 1624 | import java.net.*;
import java.util.*;
import java.io.*;
public class ChatServer
{
ServerSocket server = null;
Collection cClient = new ArrayList();
public ChatServer(int port) throws Exception
{
server = new ServerSocket(port);
}
public void startServer() throws Exception
{
while(true)
{
Socket s = server.accept();
cClient.add( new ClientConn(s) );
}
}
class ClientConn implements Runnable
{
Socket s = null;
public ClientConn(Socket s)
{
this.s = s;
(new Thread(this)).start();
}
public void send(String str) throws IOException
{
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(str);
}
public void run()
{
try {
DataInputStream dis = new DataInputStream(s.getInputStream());
String str = dis.readUTF();
while(str != null && str.length() !=0)
{
System.out.println(str);
for(Iterator it = cClient.iterator(); it.hasNext(); )
{
ClientConn cc = (ClientConn)it.next();
if(this != cc)
{
cc.send(str);
}
}
str = dis.readUTF();
//send(str);
}
s.close();
cClient.remove(this);
}
catch (IOException e)
{
System.out.println("client quit");
try
{
if(s != null)
s.close();
cClient.remove(this);
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
}
public static void main(String[] args) throws Exception
{
ChatServer cs = new ChatServer(8888);
cs.startServer();
}
}
| mit |
rekbun/leetcode | src/leetcode/LinkedListCycle.java | 438 | package leetcode;
/*
http://oj.leetcode.com/problems/linked-list-cycle/
*/
public class LinkedListCycle {
public boolean hasCycle(ListNode head) {
if(head==null) {
return false;
}
ListNode slow=head;
ListNode fast=head.next;
while(slow!=fast && (fast!=null && fast.next!=null)) {
slow=slow.next;
fast=fast.next.next;
}
if(slow==fast && fast!=null && fast.next!=null) {
return true;
}
return false;
}
}
| mit |
ICIJ/extract | extract-cli/src/main/java/org/icij/extract/json/DocumentQueueDeserializer.java | 1137 | package org.icij.extract.json;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import org.icij.extract.document.DocumentFactory;
import org.icij.extract.queue.DocumentQueue;
import java.io.IOException;
import java.nio.file.Paths;
/**
* Deserializes a {@link DocumentQueue} from JSON.
*
*
*/
public class DocumentQueueDeserializer extends JsonDeserializer<DocumentQueue> {
private final DocumentQueue queue;
private final DocumentFactory factory;
public DocumentQueueDeserializer(final DocumentFactory factory, final DocumentQueue queue) {
this.queue = queue;
this.factory = factory;
}
@Override
public DocumentQueue deserialize(final JsonParser jsonParser, final DeserializationContext context)
throws IOException {
jsonParser.nextToken(); // Skip over the start of the array.
while (jsonParser.nextToken() != JsonToken.END_ARRAY && jsonParser.nextValue() != null) {
queue.add(Paths.get(jsonParser.getValueAsString()));
}
return queue;
}
}
| mit |
hammadirshad/dvare | src/main/java/org/dvare/expression/operation/chain/ToInteger.java | 2956 | /*The MIT License (MIT)
Copyright (c) 2016 Muhammad Hammad
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Sogiftware.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/
package org.dvare.expression.operation.chain;
import org.dvare.annotations.Operation;
import org.dvare.binding.data.InstancesBinding;
import org.dvare.exceptions.interpreter.InterpretException;
import org.dvare.exceptions.parser.IllegalValueException;
import org.dvare.expression.datatype.DataType;
import org.dvare.expression.literal.LiteralExpression;
import org.dvare.expression.literal.LiteralType;
import org.dvare.expression.literal.NullLiteral;
import org.dvare.expression.operation.ChainOperationExpression;
import org.dvare.expression.operation.OperationType;
import org.dvare.util.TrimString;
@Operation(type = OperationType.TO_INTEGER, dataTypes = {DataType.StringType})
public class ToInteger extends ChainOperationExpression {
public ToInteger() {
super(OperationType.TO_INTEGER);
}
@Override
public Object interpret(InstancesBinding instancesBinding) throws InterpretException {
leftValueOperand = super.interpretOperand(this.leftOperand, instancesBinding);
LiteralExpression literalExpression = toLiteralExpression(leftValueOperand);
if (literalExpression != null && !(literalExpression instanceof NullLiteral)) {
if (literalExpression.getValue() == null) {
return new NullLiteral();
}
String value = literalExpression.getValue().toString();
value = TrimString.trim(value);
try {
LiteralExpression returnExpression = LiteralType.getLiteralExpression(Integer.parseInt(value), DataType.IntegerType);
return returnExpression;
} catch (IllegalValueException e) {
logger.error(e.getMessage(), e);
} catch (NumberFormatException e) {
logger.error(e.getMessage(), e);
}
}
return new NullLiteral<>();
}
} | mit |
theshamuel/medregistry | api/src/test/java/com/theshamuel/medreg/model/schedule/dao/impl/ScheduleRepositoryImplTest.java | 4268 | package com.theshamuel.medreg.model.schedule.dao.impl;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsCollectionContaining.hasItems;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.junit.Assert.assertThat;
import com.theshamuel.medreg.buiders.DoctorBuilder;
import com.theshamuel.medreg.buiders.ScheduleBuilder;
import com.theshamuel.medreg.model.base.dao.impl.BaseRepositoryImplTest;
import com.theshamuel.medreg.model.doctor.entity.Doctor;
import com.theshamuel.medreg.model.schedule.entity.Schedule;
import java.time.LocalDate;
import java.util.Collections;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
/**
* The integration tests for {@link ScheduleRepositoryImpl}
*
* @author Alex Gladkikh
*/
public class ScheduleRepositoryImplTest extends BaseRepositoryImplTest {
private final ScheduleRepositoryImpl scheduleRepositoryImpl = new ScheduleRepositoryImpl(template);
private Doctor doc1;
private Doctor doc2;
private Doctor doc3;
private Schedule schedule1;
private Schedule schedule2;
private Schedule schedule3;
private Schedule schedule4;
@Test
public void testFindByFilter() {
List<Schedule> actual = scheduleRepositoryImpl.findByFilter("dateWork=2018-01-01;");
assertThat(actual.size(), is(2));
assertThat(actual, hasItems(schedule3, schedule2));
actual = scheduleRepositoryImpl.findByFilter("doctor=IVANOv;");
assertThat(actual.size(), is(4));
assertThat(actual, hasItems(schedule1, schedule2, schedule3, schedule4));
}
@Test
public void testFindByDoctor() {
List<Schedule> actual = scheduleRepositoryImpl.findByDoctor(doc1);
assertThat(actual.size(), is(2));
assertThat(actual, hasItems(schedule1, schedule2));
actual = scheduleRepositoryImpl.findByDoctor(doc2);
assertThat(actual.size(), is(1));
actual = scheduleRepositoryImpl.findByDoctor(new DoctorBuilder().id("000011").build());
assertThat(actual, is(Collections.emptyList()));
}
@Test
public void testFindByDateWorkAndDoctor() {
Schedule actual = scheduleRepositoryImpl.findByDateWorkAndDoctor(doc1, LocalDate.now());
assertThat(actual, notNullValue());
assertThat(actual, is(schedule1));
actual = scheduleRepositoryImpl.findByDateWorkAndDoctor(doc1, LocalDate.of(2018, 01, 05));
assertThat(actual, nullValue());
}
@Before
@Override
public void createTestRecords() {
initCollection("doctors");
template.findAllAndRemove(Query.query(Criteria.where("id").exists(true)), Doctor.class);
doc1 = new DoctorBuilder().name("Ivan").surname("Ivanov").middlename("Petrovich")
.contractor(0).isNotWork(0).excludeFromReport(0).position("therapist").build();
doc2 = new DoctorBuilder().name("Petr").surname("Petrov").middlename("Alexeevich")
.contractor(0).isNotWork(0).excludeFromReport(0).position("oculist").build();
doc3 = new DoctorBuilder().name("Alexey").surname("Sidorov").middlename("Ivanovich")
.contractor(0).isNotWork(0).excludeFromReport(0).position("surgeon").build();
template.save(doc1);
template.save(doc2);
template.save(doc3);
initCollection("schedule");
template.findAllAndRemove(Query.query(Criteria.where("id").exists(true)), Schedule.class);
schedule1 = new ScheduleBuilder().id("0001").doctor(doc1).dateWork(LocalDate.now()).build();
template.save(schedule1);
schedule2 = new ScheduleBuilder().id("0002").doctor(doc1)
.dateWork(LocalDate.of(2018, 01, 01)).build();
template.save(schedule2);
schedule3 = new ScheduleBuilder().id("0003").doctor(doc2)
.dateWork(LocalDate.of(2018, 01, 01)).build();
template.save(schedule3);
schedule4 = new ScheduleBuilder().id("0004").doctor(doc3)
.dateWork(LocalDate.of(2018, 01, 02)).build();
template.save(schedule4);
}
}
| mit |
gobiiproject/GOBii-System | gobiiproject/gobii-model/src/main/java/org/gobiiproject/gobiimodel/types/GobiiTableType.java | 924 | package org.gobiiproject.gobiimodel.types;
/**
* Created by CSarma on 6/19/2017.
*/
public class GobiiTableType {
public final static String GERMPLASM = "germplasm";
public final static String DNASAMPLE = "dnasample";
public final static String DNARUN = "dnarun";
public final static String MARKER = "marker";
public final static String LINKAGE_GROUP = "linkage_group";
public final static String MARKER_LINKAGE_GROUP = "marker_linkage_group"; // lg_marker
public final static String DATASET_MARKER = "dataset_marker";
public final static String DATASET_DNARUN = "dataset_dnarun";
public final static String MATRIX = "matrix";
public final static String GERMPLASM_PROP = "germplasm_prop";
public final static String DNASAMPLE_PROP = "dnasample_prop";
public final static String DNARUN_PROP = "dnarun_prop";
public final static String MARKER_PROP = "marker_prop";
}
| mit |
paploo/proapi-client-java | src/test/java/com/whitepages/proapi/api/client/querycoders/PersonQueryToProAPI20URICoderTest.java | 4155 | package com.whitepages.proapi.api.client.querycoders;
import com.whitepages.proapi.api.client.QueryCoder;
import com.whitepages.proapi.api.client.QueryCoderException;
import com.whitepages.proapi.api.query.PersonQuery;
import org.junit.Test;
import java.net.URI;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* Copyright 2015 Whitepages, Inc.
*/
public class PersonQueryToProAPI20URICoderTest extends WhereQueryToProAPI2URICoderTest<PersonQuery> {
private static final String uriPath = "/2.0/person.json";
private static final String name = "Amelia Pond";
private static final String nameEncoded = "Amelia+Pond";
private static final String firstName = "Amelia";
private static final String middleName = "Jessica";
private static final String lastName = "Pond";
private static final String suffix = "I";
private static final String title = "Dr";
@Test
public void nameParameter() throws QueryCoderException {
URI uri = getCoder().encode(getFullNameQuery(), getClient());
assertThat(uri.getQuery(), containsString("name=" + nameEncoded));
}
@Test
public void firstNameParameter() throws QueryCoderException {
URI uri = getCoder().encode(getDefaultQuery(), getClient());
assertThat(uri.getQuery(), containsString("first_name=" + firstName));
}
@Test
public void middleNameParameter() throws QueryCoderException {
URI uri = getCoder().encode(getDefaultQuery(), getClient());
assertThat(uri.getQuery(), containsString("middle_name=" + middleName));
}
@Test
public void lastNameParameter() throws QueryCoderException {
URI uri = getCoder().encode(getDefaultQuery(), getClient());
assertThat(uri.getQuery(), containsString("last_name=" + lastName));
}
@Test
public void titleParameter() throws QueryCoderException {
URI uri = getCoder().encode(getTitleAndSuffixNameQuery(), getClient());
assertThat(uri.getQuery(), containsString("title=" + title));
}
@Test
public void suffixParameter() throws QueryCoderException {
URI uri = getCoder().encode(getTitleAndSuffixNameQuery(), getClient());
assertThat(uri.getQuery(), containsString("suffix=" + suffix));
}
@Test
public void namePartParametersOptional() throws QueryCoderException {
URI uri = getCoder().encode(getFullNameQuery(), getClient());
assertThat(uri.getQuery(), not(containsString("first_name")));
assertThat(uri.getQuery(), not(containsString("middle_name")));
assertThat(uri.getQuery(), not(containsString("last_name")));
}
@Test
public void titleParametersOptional() throws QueryCoderException {
URI uri = getCoder().encode(getDefaultQuery(), getClient());
assertThat(uri.getQuery(), not(containsString("suffix")));
assertThat(uri.getQuery(), not(containsString("title")));
}
@Test
public void booleanProperties() throws QueryCoderException {
URI uri = getCoder().encode(getBooleanTestingQuery(), getClient());
assertThat(uri.getQuery(), not(containsString("use_metro")));
assertThat(uri.getQuery(), containsString("use_historical=false"));
}
protected PersonQuery getFullNameQuery() {
return new PersonQuery(name, null, null, null);
}
protected PersonQuery getTitleAndSuffixNameQuery() {
PersonQuery query = getDefaultQuery();
query.setTitle(title);
query.setSuffix(suffix);
return query;
}
protected PersonQuery getBooleanTestingQuery() {
PersonQuery query = getDefaultQuery();
query.setUseHistorical(false);
query.setUseMetro(null);
return query;
}
@Override
protected PersonQuery getDefaultQuery() {
return new PersonQuery(firstName, middleName, lastName, null, null, null);
}
@Override
protected QueryCoder<PersonQuery, URI> getCoder() {
return new PersonQueryToProAPI20URICoder();
}
@Override
protected String getURIPath() {
return uriPath;
}
}
| mit |
XeroAPI/Xero-Java | src/main/java/com/xero/models/payrollau/Payslip.java | 22670 | /*
* Xero Payroll AU API
* This is the Xero Payroll API for orgs in Australia region.
*
* Contact: api@xero.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.xero.models.payrollau;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.xero.api.StringUtil;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import org.threeten.bp.OffsetDateTime;
/** Payslip */
public class Payslip {
StringUtil util = new StringUtil();
@JsonProperty("EmployeeID")
private UUID employeeID;
@JsonProperty("PayslipID")
private UUID payslipID;
@JsonProperty("FirstName")
private String firstName;
@JsonProperty("LastName")
private String lastName;
@JsonProperty("Wages")
private Double wages;
@JsonProperty("Deductions")
private Double deductions;
@JsonProperty("Tax")
private Double tax;
@JsonProperty("Super")
private Double _super;
@JsonProperty("Reimbursements")
private Double reimbursements;
@JsonProperty("NetPay")
private Double netPay;
@JsonProperty("EarningsLines")
private List<EarningsLine> earningsLines = new ArrayList<EarningsLine>();
@JsonProperty("LeaveEarningsLines")
private List<LeaveEarningsLine> leaveEarningsLines = new ArrayList<LeaveEarningsLine>();
@JsonProperty("TimesheetEarningsLines")
private List<EarningsLine> timesheetEarningsLines = new ArrayList<EarningsLine>();
@JsonProperty("DeductionLines")
private List<DeductionLine> deductionLines = new ArrayList<DeductionLine>();
@JsonProperty("LeaveAccrualLines")
private List<LeaveAccrualLine> leaveAccrualLines = new ArrayList<LeaveAccrualLine>();
@JsonProperty("ReimbursementLines")
private List<ReimbursementLine> reimbursementLines = new ArrayList<ReimbursementLine>();
@JsonProperty("SuperannuationLines")
private List<SuperannuationLine> superannuationLines = new ArrayList<SuperannuationLine>();
@JsonProperty("TaxLines")
private List<TaxLine> taxLines = new ArrayList<TaxLine>();
@JsonProperty("UpdatedDateUTC")
private String updatedDateUTC;
/**
* The Xero identifier for an employee
*
* @param employeeID UUID
* @return Payslip
*/
public Payslip employeeID(UUID employeeID) {
this.employeeID = employeeID;
return this;
}
/**
* The Xero identifier for an employee
*
* @return employeeID
*/
@ApiModelProperty(
example = "4729f087-8eec-49c1-8294-4d11a5a0a37c",
value = "The Xero identifier for an employee")
/**
* The Xero identifier for an employee
*
* @return employeeID UUID
*/
public UUID getEmployeeID() {
return employeeID;
}
/**
* The Xero identifier for an employee
*
* @param employeeID UUID
*/
public void setEmployeeID(UUID employeeID) {
this.employeeID = employeeID;
}
/**
* Xero identifier for the payslip
*
* @param payslipID UUID
* @return Payslip
*/
public Payslip payslipID(UUID payslipID) {
this.payslipID = payslipID;
return this;
}
/**
* Xero identifier for the payslip
*
* @return payslipID
*/
@ApiModelProperty(
example = "f3c0874d-7cdd-459a-a95c-d90d51decc42",
value = "Xero identifier for the payslip")
/**
* Xero identifier for the payslip
*
* @return payslipID UUID
*/
public UUID getPayslipID() {
return payslipID;
}
/**
* Xero identifier for the payslip
*
* @param payslipID UUID
*/
public void setPayslipID(UUID payslipID) {
this.payslipID = payslipID;
}
/**
* First name of employee
*
* @param firstName String
* @return Payslip
*/
public Payslip firstName(String firstName) {
this.firstName = firstName;
return this;
}
/**
* First name of employee
*
* @return firstName
*/
@ApiModelProperty(example = "Karen", value = "First name of employee")
/**
* First name of employee
*
* @return firstName String
*/
public String getFirstName() {
return firstName;
}
/**
* First name of employee
*
* @param firstName String
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* Last name of employee
*
* @param lastName String
* @return Payslip
*/
public Payslip lastName(String lastName) {
this.lastName = lastName;
return this;
}
/**
* Last name of employee
*
* @return lastName
*/
@ApiModelProperty(example = "Jones", value = "Last name of employee")
/**
* Last name of employee
*
* @return lastName String
*/
public String getLastName() {
return lastName;
}
/**
* Last name of employee
*
* @param lastName String
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* The Wages for the Payslip
*
* @param wages Double
* @return Payslip
*/
public Payslip wages(Double wages) {
this.wages = wages;
return this;
}
/**
* The Wages for the Payslip
*
* @return wages
*/
@ApiModelProperty(example = "1060.5", value = "The Wages for the Payslip")
/**
* The Wages for the Payslip
*
* @return wages Double
*/
public Double getWages() {
return wages;
}
/**
* The Wages for the Payslip
*
* @param wages Double
*/
public void setWages(Double wages) {
this.wages = wages;
}
/**
* The Deductions for the Payslip
*
* @param deductions Double
* @return Payslip
*/
public Payslip deductions(Double deductions) {
this.deductions = deductions;
return this;
}
/**
* The Deductions for the Payslip
*
* @return deductions
*/
@ApiModelProperty(example = "0.0", value = "The Deductions for the Payslip")
/**
* The Deductions for the Payslip
*
* @return deductions Double
*/
public Double getDeductions() {
return deductions;
}
/**
* The Deductions for the Payslip
*
* @param deductions Double
*/
public void setDeductions(Double deductions) {
this.deductions = deductions;
}
/**
* The Tax for the Payslip
*
* @param tax Double
* @return Payslip
*/
public Payslip tax(Double tax) {
this.tax = tax;
return this;
}
/**
* The Tax for the Payslip
*
* @return tax
*/
@ApiModelProperty(example = "198.0", value = "The Tax for the Payslip")
/**
* The Tax for the Payslip
*
* @return tax Double
*/
public Double getTax() {
return tax;
}
/**
* The Tax for the Payslip
*
* @param tax Double
*/
public void setTax(Double tax) {
this.tax = tax;
}
/**
* The Super for the Payslip
*
* @param _super Double
* @return Payslip
*/
public Payslip _super(Double _super) {
this._super = _super;
return this;
}
/**
* The Super for the Payslip
*
* @return _super
*/
@ApiModelProperty(example = "75.6", value = "The Super for the Payslip")
/**
* The Super for the Payslip
*
* @return _super Double
*/
public Double getSuper() {
return _super;
}
/**
* The Super for the Payslip
*
* @param _super Double
*/
public void setSuper(Double _super) {
this._super = _super;
}
/**
* The Reimbursements for the Payslip
*
* @param reimbursements Double
* @return Payslip
*/
public Payslip reimbursements(Double reimbursements) {
this.reimbursements = reimbursements;
return this;
}
/**
* The Reimbursements for the Payslip
*
* @return reimbursements
*/
@ApiModelProperty(example = "0.0", value = "The Reimbursements for the Payslip")
/**
* The Reimbursements for the Payslip
*
* @return reimbursements Double
*/
public Double getReimbursements() {
return reimbursements;
}
/**
* The Reimbursements for the Payslip
*
* @param reimbursements Double
*/
public void setReimbursements(Double reimbursements) {
this.reimbursements = reimbursements;
}
/**
* The NetPay for the Payslip
*
* @param netPay Double
* @return Payslip
*/
public Payslip netPay(Double netPay) {
this.netPay = netPay;
return this;
}
/**
* The NetPay for the Payslip
*
* @return netPay
*/
@ApiModelProperty(example = "862.5", value = "The NetPay for the Payslip")
/**
* The NetPay for the Payslip
*
* @return netPay Double
*/
public Double getNetPay() {
return netPay;
}
/**
* The NetPay for the Payslip
*
* @param netPay Double
*/
public void setNetPay(Double netPay) {
this.netPay = netPay;
}
/**
* earningsLines
*
* @param earningsLines List<EarningsLine>
* @return Payslip
*/
public Payslip earningsLines(List<EarningsLine> earningsLines) {
this.earningsLines = earningsLines;
return this;
}
/**
* earningsLines
*
* @param earningsLinesItem EarningsLine
* @return Payslip
*/
public Payslip addEarningsLinesItem(EarningsLine earningsLinesItem) {
if (this.earningsLines == null) {
this.earningsLines = new ArrayList<EarningsLine>();
}
this.earningsLines.add(earningsLinesItem);
return this;
}
/**
* Get earningsLines
*
* @return earningsLines
*/
@ApiModelProperty(value = "")
/**
* earningsLines
*
* @return earningsLines List<EarningsLine>
*/
public List<EarningsLine> getEarningsLines() {
return earningsLines;
}
/**
* earningsLines
*
* @param earningsLines List<EarningsLine>
*/
public void setEarningsLines(List<EarningsLine> earningsLines) {
this.earningsLines = earningsLines;
}
/**
* leaveEarningsLines
*
* @param leaveEarningsLines List<LeaveEarningsLine>
* @return Payslip
*/
public Payslip leaveEarningsLines(List<LeaveEarningsLine> leaveEarningsLines) {
this.leaveEarningsLines = leaveEarningsLines;
return this;
}
/**
* leaveEarningsLines
*
* @param leaveEarningsLinesItem LeaveEarningsLine
* @return Payslip
*/
public Payslip addLeaveEarningsLinesItem(LeaveEarningsLine leaveEarningsLinesItem) {
if (this.leaveEarningsLines == null) {
this.leaveEarningsLines = new ArrayList<LeaveEarningsLine>();
}
this.leaveEarningsLines.add(leaveEarningsLinesItem);
return this;
}
/**
* Get leaveEarningsLines
*
* @return leaveEarningsLines
*/
@ApiModelProperty(value = "")
/**
* leaveEarningsLines
*
* @return leaveEarningsLines List<LeaveEarningsLine>
*/
public List<LeaveEarningsLine> getLeaveEarningsLines() {
return leaveEarningsLines;
}
/**
* leaveEarningsLines
*
* @param leaveEarningsLines List<LeaveEarningsLine>
*/
public void setLeaveEarningsLines(List<LeaveEarningsLine> leaveEarningsLines) {
this.leaveEarningsLines = leaveEarningsLines;
}
/**
* timesheetEarningsLines
*
* @param timesheetEarningsLines List<EarningsLine>
* @return Payslip
*/
public Payslip timesheetEarningsLines(List<EarningsLine> timesheetEarningsLines) {
this.timesheetEarningsLines = timesheetEarningsLines;
return this;
}
/**
* timesheetEarningsLines
*
* @param timesheetEarningsLinesItem EarningsLine
* @return Payslip
*/
public Payslip addTimesheetEarningsLinesItem(EarningsLine timesheetEarningsLinesItem) {
if (this.timesheetEarningsLines == null) {
this.timesheetEarningsLines = new ArrayList<EarningsLine>();
}
this.timesheetEarningsLines.add(timesheetEarningsLinesItem);
return this;
}
/**
* Get timesheetEarningsLines
*
* @return timesheetEarningsLines
*/
@ApiModelProperty(value = "")
/**
* timesheetEarningsLines
*
* @return timesheetEarningsLines List<EarningsLine>
*/
public List<EarningsLine> getTimesheetEarningsLines() {
return timesheetEarningsLines;
}
/**
* timesheetEarningsLines
*
* @param timesheetEarningsLines List<EarningsLine>
*/
public void setTimesheetEarningsLines(List<EarningsLine> timesheetEarningsLines) {
this.timesheetEarningsLines = timesheetEarningsLines;
}
/**
* deductionLines
*
* @param deductionLines List<DeductionLine>
* @return Payslip
*/
public Payslip deductionLines(List<DeductionLine> deductionLines) {
this.deductionLines = deductionLines;
return this;
}
/**
* deductionLines
*
* @param deductionLinesItem DeductionLine
* @return Payslip
*/
public Payslip addDeductionLinesItem(DeductionLine deductionLinesItem) {
if (this.deductionLines == null) {
this.deductionLines = new ArrayList<DeductionLine>();
}
this.deductionLines.add(deductionLinesItem);
return this;
}
/**
* Get deductionLines
*
* @return deductionLines
*/
@ApiModelProperty(value = "")
/**
* deductionLines
*
* @return deductionLines List<DeductionLine>
*/
public List<DeductionLine> getDeductionLines() {
return deductionLines;
}
/**
* deductionLines
*
* @param deductionLines List<DeductionLine>
*/
public void setDeductionLines(List<DeductionLine> deductionLines) {
this.deductionLines = deductionLines;
}
/**
* leaveAccrualLines
*
* @param leaveAccrualLines List<LeaveAccrualLine>
* @return Payslip
*/
public Payslip leaveAccrualLines(List<LeaveAccrualLine> leaveAccrualLines) {
this.leaveAccrualLines = leaveAccrualLines;
return this;
}
/**
* leaveAccrualLines
*
* @param leaveAccrualLinesItem LeaveAccrualLine
* @return Payslip
*/
public Payslip addLeaveAccrualLinesItem(LeaveAccrualLine leaveAccrualLinesItem) {
if (this.leaveAccrualLines == null) {
this.leaveAccrualLines = new ArrayList<LeaveAccrualLine>();
}
this.leaveAccrualLines.add(leaveAccrualLinesItem);
return this;
}
/**
* Get leaveAccrualLines
*
* @return leaveAccrualLines
*/
@ApiModelProperty(value = "")
/**
* leaveAccrualLines
*
* @return leaveAccrualLines List<LeaveAccrualLine>
*/
public List<LeaveAccrualLine> getLeaveAccrualLines() {
return leaveAccrualLines;
}
/**
* leaveAccrualLines
*
* @param leaveAccrualLines List<LeaveAccrualLine>
*/
public void setLeaveAccrualLines(List<LeaveAccrualLine> leaveAccrualLines) {
this.leaveAccrualLines = leaveAccrualLines;
}
/**
* reimbursementLines
*
* @param reimbursementLines List<ReimbursementLine>
* @return Payslip
*/
public Payslip reimbursementLines(List<ReimbursementLine> reimbursementLines) {
this.reimbursementLines = reimbursementLines;
return this;
}
/**
* reimbursementLines
*
* @param reimbursementLinesItem ReimbursementLine
* @return Payslip
*/
public Payslip addReimbursementLinesItem(ReimbursementLine reimbursementLinesItem) {
if (this.reimbursementLines == null) {
this.reimbursementLines = new ArrayList<ReimbursementLine>();
}
this.reimbursementLines.add(reimbursementLinesItem);
return this;
}
/**
* Get reimbursementLines
*
* @return reimbursementLines
*/
@ApiModelProperty(value = "")
/**
* reimbursementLines
*
* @return reimbursementLines List<ReimbursementLine>
*/
public List<ReimbursementLine> getReimbursementLines() {
return reimbursementLines;
}
/**
* reimbursementLines
*
* @param reimbursementLines List<ReimbursementLine>
*/
public void setReimbursementLines(List<ReimbursementLine> reimbursementLines) {
this.reimbursementLines = reimbursementLines;
}
/**
* superannuationLines
*
* @param superannuationLines List<SuperannuationLine>
* @return Payslip
*/
public Payslip superannuationLines(List<SuperannuationLine> superannuationLines) {
this.superannuationLines = superannuationLines;
return this;
}
/**
* superannuationLines
*
* @param superannuationLinesItem SuperannuationLine
* @return Payslip
*/
public Payslip addSuperannuationLinesItem(SuperannuationLine superannuationLinesItem) {
if (this.superannuationLines == null) {
this.superannuationLines = new ArrayList<SuperannuationLine>();
}
this.superannuationLines.add(superannuationLinesItem);
return this;
}
/**
* Get superannuationLines
*
* @return superannuationLines
*/
@ApiModelProperty(value = "")
/**
* superannuationLines
*
* @return superannuationLines List<SuperannuationLine>
*/
public List<SuperannuationLine> getSuperannuationLines() {
return superannuationLines;
}
/**
* superannuationLines
*
* @param superannuationLines List<SuperannuationLine>
*/
public void setSuperannuationLines(List<SuperannuationLine> superannuationLines) {
this.superannuationLines = superannuationLines;
}
/**
* taxLines
*
* @param taxLines List<TaxLine>
* @return Payslip
*/
public Payslip taxLines(List<TaxLine> taxLines) {
this.taxLines = taxLines;
return this;
}
/**
* taxLines
*
* @param taxLinesItem TaxLine
* @return Payslip
*/
public Payslip addTaxLinesItem(TaxLine taxLinesItem) {
if (this.taxLines == null) {
this.taxLines = new ArrayList<TaxLine>();
}
this.taxLines.add(taxLinesItem);
return this;
}
/**
* Get taxLines
*
* @return taxLines
*/
@ApiModelProperty(value = "")
/**
* taxLines
*
* @return taxLines List<TaxLine>
*/
public List<TaxLine> getTaxLines() {
return taxLines;
}
/**
* taxLines
*
* @param taxLines List<TaxLine>
*/
public void setTaxLines(List<TaxLine> taxLines) {
this.taxLines = taxLines;
}
/**
* Last modified timestamp
*
* @return updatedDateUTC
*/
@ApiModelProperty(example = "/Date(1583967733054+0000)/", value = "Last modified timestamp")
/**
* Last modified timestamp
*
* @return updatedDateUTC String
*/
public String getUpdatedDateUTC() {
return updatedDateUTC;
}
/**
* Last modified timestamp
*
* @return OffsetDateTime
*/
public OffsetDateTime getUpdatedDateUTCAsDate() {
if (this.updatedDateUTC != null) {
try {
return util.convertStringToOffsetDateTime(this.updatedDateUTC);
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Payslip payslip = (Payslip) o;
return Objects.equals(this.employeeID, payslip.employeeID)
&& Objects.equals(this.payslipID, payslip.payslipID)
&& Objects.equals(this.firstName, payslip.firstName)
&& Objects.equals(this.lastName, payslip.lastName)
&& Objects.equals(this.wages, payslip.wages)
&& Objects.equals(this.deductions, payslip.deductions)
&& Objects.equals(this.tax, payslip.tax)
&& Objects.equals(this._super, payslip._super)
&& Objects.equals(this.reimbursements, payslip.reimbursements)
&& Objects.equals(this.netPay, payslip.netPay)
&& Objects.equals(this.earningsLines, payslip.earningsLines)
&& Objects.equals(this.leaveEarningsLines, payslip.leaveEarningsLines)
&& Objects.equals(this.timesheetEarningsLines, payslip.timesheetEarningsLines)
&& Objects.equals(this.deductionLines, payslip.deductionLines)
&& Objects.equals(this.leaveAccrualLines, payslip.leaveAccrualLines)
&& Objects.equals(this.reimbursementLines, payslip.reimbursementLines)
&& Objects.equals(this.superannuationLines, payslip.superannuationLines)
&& Objects.equals(this.taxLines, payslip.taxLines)
&& Objects.equals(this.updatedDateUTC, payslip.updatedDateUTC);
}
@Override
public int hashCode() {
return Objects.hash(
employeeID,
payslipID,
firstName,
lastName,
wages,
deductions,
tax,
_super,
reimbursements,
netPay,
earningsLines,
leaveEarningsLines,
timesheetEarningsLines,
deductionLines,
leaveAccrualLines,
reimbursementLines,
superannuationLines,
taxLines,
updatedDateUTC);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Payslip {\n");
sb.append(" employeeID: ").append(toIndentedString(employeeID)).append("\n");
sb.append(" payslipID: ").append(toIndentedString(payslipID)).append("\n");
sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n");
sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n");
sb.append(" wages: ").append(toIndentedString(wages)).append("\n");
sb.append(" deductions: ").append(toIndentedString(deductions)).append("\n");
sb.append(" tax: ").append(toIndentedString(tax)).append("\n");
sb.append(" _super: ").append(toIndentedString(_super)).append("\n");
sb.append(" reimbursements: ").append(toIndentedString(reimbursements)).append("\n");
sb.append(" netPay: ").append(toIndentedString(netPay)).append("\n");
sb.append(" earningsLines: ").append(toIndentedString(earningsLines)).append("\n");
sb.append(" leaveEarningsLines: ").append(toIndentedString(leaveEarningsLines)).append("\n");
sb.append(" timesheetEarningsLines: ")
.append(toIndentedString(timesheetEarningsLines))
.append("\n");
sb.append(" deductionLines: ").append(toIndentedString(deductionLines)).append("\n");
sb.append(" leaveAccrualLines: ").append(toIndentedString(leaveAccrualLines)).append("\n");
sb.append(" reimbursementLines: ").append(toIndentedString(reimbursementLines)).append("\n");
sb.append(" superannuationLines: ")
.append(toIndentedString(superannuationLines))
.append("\n");
sb.append(" taxLines: ").append(toIndentedString(taxLines)).append("\n");
sb.append(" updatedDateUTC: ").append(toIndentedString(updatedDateUTC)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| mit |
jjhesk/LoyalNativeSlider | testApp/src/main/java/com/hkm/loyalns/mod/BaseApp.java | 1719 | package com.hkm.loyalns.mod;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.RelativeLayout;
import com.hkm.loyalns.R;
import com.hkm.slider.SliderLayout;
import com.hkm.slider.SliderTypes.BaseSliderView;
import com.hkm.slider.Tricks.ViewPagerEx;
/**
* Created by hesk on 24/11/15.
*/
public abstract class BaseApp extends AppCompatActivity implements BaseSliderView.OnSliderClickListener, ViewPagerEx.OnPageChangeListener {
@Override
protected void onStop() {
// To prevent a memory leak on rotation, make sure to call stopAutoCycle() on the slider before activity or fragment is destroyed
mDemoSlider.stopAutoCycle();
super.onStop();
}
protected SliderLayout mDemoSlider;
protected RelativeLayout mFrameMain;
protected boolean numbered = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getActivityMainLayoutId());
mDemoSlider = (SliderLayout) findViewById(R.id.slider);
mFrameMain = (RelativeLayout) findViewById(R.id.sliderframe);
setupSlider();
}
@LayoutRes
protected int getActivityMainLayoutId() {
return R.layout.main_slider;
}
protected abstract void setupSlider();
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
Log.d("Slider Demo", "Page Changed: " + position);
}
@Override
public void onPageScrollStateChanged(int state) {
}
}
| mit |
LousyLynx/Infinity-Storage | src/main/java/infinitystorage/api/autocrafting/ICraftingPatternProvider.java | 682 | package infinitystorage.api.autocrafting;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import javax.annotation.Nonnull;
/**
* Implement this interface on pattern items.
* When you implement this interface on your patterns, they will be insertable in crafters.
*/
public interface ICraftingPatternProvider {
/**
* Creates a crafting pattern.
*
* @param world The world
* @param stack The pattern stack
* @param container The container where the pattern is in
* @return The crafting pattern
*/
@Nonnull
ICraftingPattern create(World world, ItemStack stack, ICraftingPatternContainer container);
}
| mit |
dachengxi/spring1.1.1_source | src/org/springframework/orm/jdo/JdoTransactionObject.java | 2427 | /*
* Copyright 2002-2004 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.orm.jdo;
import org.springframework.jdbc.datasource.JdbcTransactionObjectSupport;
/**
* JDO transaction object, representing a PersistenceManagerHolder.
* Used as transaction object by JdoTransactionManager.
*
* <p>Derives from JdbcTransactionObjectSupport to inherit the capability
* to manage JDBC 3.0 Savepoints for underlying JDBC Connections.
*
* <p>Note: This is an SPI class, not intended to be used by applications.
*
* @author Juergen Hoeller
* @since 13.06.2003
* @see JdoTransactionManager
* @see PersistenceManagerHolder
*/
public class JdoTransactionObject extends JdbcTransactionObjectSupport {
private PersistenceManagerHolder persistenceManagerHolder;
private boolean newPersistenceManagerHolder;
private Object transactionData;
protected void setPersistenceManagerHolder(PersistenceManagerHolder persistenceManagerHolder,
boolean newPersistenceManagerHolder) {
this.persistenceManagerHolder = persistenceManagerHolder;
this.newPersistenceManagerHolder = newPersistenceManagerHolder;
}
public PersistenceManagerHolder getPersistenceManagerHolder() {
return persistenceManagerHolder;
}
public boolean isNewPersistenceManagerHolder() {
return newPersistenceManagerHolder;
}
public boolean hasTransaction() {
return (this.persistenceManagerHolder != null &&
this.persistenceManagerHolder.getPersistenceManager() != null &&
this.persistenceManagerHolder.getPersistenceManager().currentTransaction().isActive());
}
protected void setTransactionData(Object transactionData) {
this.transactionData = transactionData;
}
public Object getTransactionData() {
return transactionData;
}
public boolean isRollbackOnly() {
return getPersistenceManagerHolder().isRollbackOnly();
}
}
| mit |
evdubs/XChange | xchange-bitflyer/src/main/java/org/knowm/xchange/bitflyer/service/BitflyerMarketDataServiceRaw.java | 1729 | package org.knowm.xchange.bitflyer.service;
import java.io.IOException;
import java.util.List;
import org.knowm.xchange.Exchange;
import org.knowm.xchange.bitflyer.dto.BitflyerException;
import org.knowm.xchange.bitflyer.dto.account.BitflyerMarket;
import org.knowm.xchange.bitflyer.dto.marketdata.BitflyerOrderbook;
import org.knowm.xchange.bitflyer.dto.marketdata.BitflyerTicker;
/**
* <p>
* Implementation of the market data service for Bitflyer
* </p>
* <ul>
* <li>Provides access to various market data values</li>
* </ul>
*/
public class BitflyerMarketDataServiceRaw extends BitflyerBaseService {
/**
* Constructor
*
* @param exchange baseExchange
*/
public BitflyerMarketDataServiceRaw(Exchange exchange) {
super(exchange);
}
public List<BitflyerMarket> getMarkets() throws IOException {
try {
return bitflyer.getMarkets();
} catch (BitflyerException e) {
throw handleError(e);
}
}
public BitflyerTicker getTicker() throws IOException {
try {
return bitflyer.getTicker();
} catch (BitflyerException e) {
throw handleError(e);
}
}
public BitflyerTicker getTicker(String productCode) throws IOException {
try {
return bitflyer.getTicker(productCode);
} catch (BitflyerException e) {
throw handleError(e);
}
}
public BitflyerOrderbook getOrderbook() throws IOException {
try {
return bitflyer.getBoard();
} catch (BitflyerException e) {
throw handleError(e);
}
}
public BitflyerOrderbook getOrderbook(String productCode) throws IOException {
try {
return bitflyer.getBoard(productCode);
} catch (BitflyerException e) {
throw handleError(e);
}
}
}
| mit |