file_id
stringlengths 5
10
| content
stringlengths 110
36.3k
| repo
stringlengths 7
108
| path
stringlengths 8
198
| token_length
int64 37
8.19k
| original_comment
stringlengths 11
5.72k
| comment_type
stringclasses 2
values | detected_lang
stringclasses 1
value | prompt
stringlengths 62
36.3k
|
---|---|---|---|---|---|---|---|---|
11193_1 | package com.steen.controllers;
import com.steen.models.*;
import com.steen.velocity.VelocityTemplateEngine;
import spark.ModelAndView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.steen.Main.p_layout;
import static com.steen.Main.sfp;
import static spark.Spark.get;
import static spark.Spark.post;
public class CartController {
private CartModel cartModel;
private final int ADD = 0;
private final int DELETE = 1;
public CartController(final HashMap<String, Model> models) {
cartModel = (CartModel) models.get("cart");
post("/cart/act", (request, response) -> {
try {
int action = Integer.parseInt(request.queryParams("action"));
switch (action) {
case ADD:
int p_id = Integer.parseInt(request.queryParams("productId"));
int amount = Integer.parseInt(request.queryParams("amount"));
cartModel.addToCart(p_id, amount);
return "Product toegevoegd aan winkelwagen.";
case DELETE:
List<Integer> idsToDelete = new ArrayList<>();
for (int i = 0; true; i++) {
String p_idString = request.queryParams("p_id" + i);
if (p_idString == null) break;
int productID = Integer.parseInt(p_idString);
idsToDelete.add(productID);
}
int itemsdeleted = cartModel.removeFromCart(idsToDelete, -1);
if (itemsdeleted > 0){
if (itemsdeleted == 1)
return "1 product verwijderd.";
return itemsdeleted + " producten verwijderd.";
} else {
// return "Kon de geselecteerde producten niet verwijderen. " +
// "Neem aub. contact op met de sitebeheerder als dit vaak voor komt..";
return "0 producten verwijderd.";
}
default: throw new Exception();
}
} catch (Exception e) {
e.printStackTrace();
return "Er ging iets mis aan onze kant, " +
"neem aub. contact op met de sitebeheerder als dit vaak voor komt. ";
}
});
get("/cart", (request, response) -> {
Map<String, Object> model = new HashMap<>();
model.put("login_modal", sfp + "html/login_mod.vtl");
model.put("template", sfp + "html/cart.html");
model.put("admin", request.session().attribute("admin"));
model.put("correctinfo", request.session().attribute("correctinfo"));
model.put("username", request.session().attribute("username"));
return new ModelAndView(model, p_layout);
}, new VelocityTemplateEngine());
}
}
| 0912293/PythonMasterRace | src/main/java/com/steen/controllers/CartController.java | 802 | // "Neem aub. contact op met de sitebeheerder als dit vaak voor komt.."; | line_comment | nl | package com.steen.controllers;
import com.steen.models.*;
import com.steen.velocity.VelocityTemplateEngine;
import spark.ModelAndView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.steen.Main.p_layout;
import static com.steen.Main.sfp;
import static spark.Spark.get;
import static spark.Spark.post;
public class CartController {
private CartModel cartModel;
private final int ADD = 0;
private final int DELETE = 1;
public CartController(final HashMap<String, Model> models) {
cartModel = (CartModel) models.get("cart");
post("/cart/act", (request, response) -> {
try {
int action = Integer.parseInt(request.queryParams("action"));
switch (action) {
case ADD:
int p_id = Integer.parseInt(request.queryParams("productId"));
int amount = Integer.parseInt(request.queryParams("amount"));
cartModel.addToCart(p_id, amount);
return "Product toegevoegd aan winkelwagen.";
case DELETE:
List<Integer> idsToDelete = new ArrayList<>();
for (int i = 0; true; i++) {
String p_idString = request.queryParams("p_id" + i);
if (p_idString == null) break;
int productID = Integer.parseInt(p_idString);
idsToDelete.add(productID);
}
int itemsdeleted = cartModel.removeFromCart(idsToDelete, -1);
if (itemsdeleted > 0){
if (itemsdeleted == 1)
return "1 product verwijderd.";
return itemsdeleted + " producten verwijderd.";
} else {
// return "Kon de geselecteerde producten niet verwijderen. " +
// "Neem aub.<SUF>
return "0 producten verwijderd.";
}
default: throw new Exception();
}
} catch (Exception e) {
e.printStackTrace();
return "Er ging iets mis aan onze kant, " +
"neem aub. contact op met de sitebeheerder als dit vaak voor komt. ";
}
});
get("/cart", (request, response) -> {
Map<String, Object> model = new HashMap<>();
model.put("login_modal", sfp + "html/login_mod.vtl");
model.put("template", sfp + "html/cart.html");
model.put("admin", request.session().attribute("admin"));
model.put("correctinfo", request.session().attribute("correctinfo"));
model.put("username", request.session().attribute("username"));
return new ModelAndView(model, p_layout);
}, new VelocityTemplateEngine());
}
}
|
18424_13 | package com.example.idek;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.CameraX;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.ImageAnalysisConfig;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.ImageCaptureConfig;
import androidx.camera.core.ImageProxy;
import androidx.camera.core.Preview;
import androidx.camera.core.PreviewConfig;
import androidx.lifecycle.LifecycleOwner;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.util.Rational;
import android.util.Size;
import android.view.TextureView;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.PlanarYUVLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import java.nio.ByteBuffer;
//ik haat mijzelf dus daarom maak ik een camera ding met een api dat nog niet eens in de beta stage is
//en waarvan de tutorial in een taal is dat ik 0% begrijp
//saus: https://codelabs.developers.google.com/codelabs/camerax-getting-started/
public class MainActivity extends AppCompatActivity {
//private int REQUEST_CODE_PERMISSIONS = 10; //idek volgens tutorial is dit een arbitraire nummer zou helpen als je app meerdere toestimmingen vraagt
//private final String[] REQUIRED_PERMISSIONS = new String[]{"android.permission.CAMERA"}; //array met permissions vermeld in manifest
TextureView txView;
String result = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txView = findViewById(R.id.view_finder);
startCamera();
/*if(allPermissionsGranted()){
} else{
ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS);
}*/
}
private void startCamera() {//heel veel dingen gebeuren hier
//eerst zeker zijn dat de camera niet gebruikt wordt.
CameraX.unbindAll();
/* doe preview weergeven */
int aspRatioW = txView.getWidth(); //haalt breedte scherm op
int aspRatioH = txView.getHeight(); //haalt hoogte scherm op
Rational asp = new Rational (aspRatioW, aspRatioH); //helpt bij zetten aspect ratio
Size screen = new Size(aspRatioW, aspRatioH); //grootte scherm ofc
PreviewConfig pConfig = new PreviewConfig.Builder().setTargetAspectRatio(asp).setTargetResolution(screen).build();
Preview pview = new Preview(pConfig);
pview.setOnPreviewOutputUpdateListener(
new Preview.OnPreviewOutputUpdateListener() {
//eigenlijk maakt dit al een nieuwe texturesurface aan
//maar aangezien ik al eentje heb gemaakt aan het begin...
@Override
public void onUpdated(Preview.PreviewOutput output){
ViewGroup parent = (ViewGroup) txView.getParent();
parent.removeView(txView); //moeten wij hem eerst yeeten
parent.addView(txView, 0);
txView.setSurfaceTexture(output.getSurfaceTexture()); //dan weer toevoegen
//updateTransform(); //en dan updaten
}
});
/* image capture */
/*ImageCaptureConfig imgConfig = new ImageCaptureConfig.Builder().setCaptureMode(ImageCapture.CaptureMode.MIN_LATENCY).setTargetRotation(getWindowManager().getDefaultDisplay().getRotation()).build();
ImageCapture imgCap = new ImageCapture(imgConfig);*/
/* image analyser */
ImageAnalysisConfig imgAConfig = new ImageAnalysisConfig.Builder().setImageReaderMode(ImageAnalysis.ImageReaderMode.ACQUIRE_LATEST_IMAGE).build();
final ImageAnalysis imgAsys = new ImageAnalysis(imgAConfig);
imgAsys.setAnalyzer(
new ImageAnalysis.Analyzer(){
@Override
public void analyze(ImageProxy image, int rotationDegrees){
try {
ByteBuffer bf = image.getPlanes()[0].getBuffer();
byte[] b = new byte[bf.capacity()];
bf.get(b);
Rect r = image.getCropRect();
int w = image.getWidth();
int h = image.getHeight();
PlanarYUVLuminanceSource sauce = new PlanarYUVLuminanceSource(b ,w, h, r.left, r.top, r.width(), r.height(),false);
BinaryBitmap bit = new BinaryBitmap(new HybridBinarizer(sauce));
result = new qrReader().decoded(bit);
System.out.println(result);
Toast.makeText(getBaseContext(), result, Toast.LENGTH_SHORT).show();
Log.wtf("F: ", result);
} catch (NotFoundException e) {
e.printStackTrace();
} catch (FormatException e) {
e.printStackTrace();
}
}
}
);
//bindt de shit hierboven aan de lifecycle:
CameraX.bindToLifecycle((LifecycleOwner)this, imgAsys, /*imgCap,*/ pview);
}
/*private void updateTransform(){
//compenseert veranderingen in orientatie voor viewfinder, aangezien de rest van de layout in portrait mode blijft.
//methinks :thonk:
Matrix mx = new Matrix();
float w = txView.getMeasuredWidth();
float h = txView.getMeasuredHeight();
//berekent het midden
float cX = w / 2f;
float cY = h / 2f;
int rotDgr; //voor de switch < propt in hoeveel graden shit is gekanteld
//Display a = txView.getDisplay(); //ok dan stoppen wij .getdisplay in z'n eigen shit.
int rtrn = (int)txView.getRotation(); //dan dit maar in een aparte int zetten want alles deed boem bij het opstarten
//omfg het komt omdat .getDisplay erin zit.
switch(rtrn){
case Surface.ROTATION_0:
rotDgr = 0;
break;
case Surface.ROTATION_90:
rotDgr = 90;
break;
case Surface.ROTATION_180:
rotDgr = 180;
break;
case Surface.ROTATION_270:
rotDgr = 270;
break;
default:
return;
}
mx.postRotate((float)rotDgr, cX, cY); //berekent preview out put aan de hand van hoe de toestel gedraaid is
float buffer = txView.getMeasuredHeight() / txView.getMeasuredWidth() ;
int scaleW;
int scaleH;
if(w > h){ //center-crop transformation
scaleH = (int)w;
scaleW = Math.round(w * buffer);
} else{
scaleH = (int)h;
scaleW = Math.round(h * buffer);
}
float x = scaleW / w; //doet schaal berekenen
float y = scaleH / h;
mx.preScale(x, y, cX, cY); //vult preview op
txView.setTransform(mx); //past dit op preview toe
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//als alle permissies zijn toegestaan start camera
if(requestCode == REQUEST_CODE_PERMISSIONS){
if(allPermissionsGranted()){
startCamera();
} else{
Toast.makeText(this, "Permissions not granted by the user.", Toast.LENGTH_SHORT).show();
finish();
}
}
}
private boolean allPermissionsGranted(){
//kijken of alle permissies zijn toegestaan
for(String permission : REQUIRED_PERMISSIONS){
if(ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED){
return false;
}
}
return true;
}*/
}
| 0974201/code-bin | java/backup camerax proj.java | 2,322 | //maar aangezien ik al eentje heb gemaakt aan het begin... | line_comment | nl | package com.example.idek;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.CameraX;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.ImageAnalysisConfig;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.ImageCaptureConfig;
import androidx.camera.core.ImageProxy;
import androidx.camera.core.Preview;
import androidx.camera.core.PreviewConfig;
import androidx.lifecycle.LifecycleOwner;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.util.Rational;
import android.util.Size;
import android.view.TextureView;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.PlanarYUVLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import java.nio.ByteBuffer;
//ik haat mijzelf dus daarom maak ik een camera ding met een api dat nog niet eens in de beta stage is
//en waarvan de tutorial in een taal is dat ik 0% begrijp
//saus: https://codelabs.developers.google.com/codelabs/camerax-getting-started/
public class MainActivity extends AppCompatActivity {
//private int REQUEST_CODE_PERMISSIONS = 10; //idek volgens tutorial is dit een arbitraire nummer zou helpen als je app meerdere toestimmingen vraagt
//private final String[] REQUIRED_PERMISSIONS = new String[]{"android.permission.CAMERA"}; //array met permissions vermeld in manifest
TextureView txView;
String result = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txView = findViewById(R.id.view_finder);
startCamera();
/*if(allPermissionsGranted()){
} else{
ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS);
}*/
}
private void startCamera() {//heel veel dingen gebeuren hier
//eerst zeker zijn dat de camera niet gebruikt wordt.
CameraX.unbindAll();
/* doe preview weergeven */
int aspRatioW = txView.getWidth(); //haalt breedte scherm op
int aspRatioH = txView.getHeight(); //haalt hoogte scherm op
Rational asp = new Rational (aspRatioW, aspRatioH); //helpt bij zetten aspect ratio
Size screen = new Size(aspRatioW, aspRatioH); //grootte scherm ofc
PreviewConfig pConfig = new PreviewConfig.Builder().setTargetAspectRatio(asp).setTargetResolution(screen).build();
Preview pview = new Preview(pConfig);
pview.setOnPreviewOutputUpdateListener(
new Preview.OnPreviewOutputUpdateListener() {
//eigenlijk maakt dit al een nieuwe texturesurface aan
//maar aangezien<SUF>
@Override
public void onUpdated(Preview.PreviewOutput output){
ViewGroup parent = (ViewGroup) txView.getParent();
parent.removeView(txView); //moeten wij hem eerst yeeten
parent.addView(txView, 0);
txView.setSurfaceTexture(output.getSurfaceTexture()); //dan weer toevoegen
//updateTransform(); //en dan updaten
}
});
/* image capture */
/*ImageCaptureConfig imgConfig = new ImageCaptureConfig.Builder().setCaptureMode(ImageCapture.CaptureMode.MIN_LATENCY).setTargetRotation(getWindowManager().getDefaultDisplay().getRotation()).build();
ImageCapture imgCap = new ImageCapture(imgConfig);*/
/* image analyser */
ImageAnalysisConfig imgAConfig = new ImageAnalysisConfig.Builder().setImageReaderMode(ImageAnalysis.ImageReaderMode.ACQUIRE_LATEST_IMAGE).build();
final ImageAnalysis imgAsys = new ImageAnalysis(imgAConfig);
imgAsys.setAnalyzer(
new ImageAnalysis.Analyzer(){
@Override
public void analyze(ImageProxy image, int rotationDegrees){
try {
ByteBuffer bf = image.getPlanes()[0].getBuffer();
byte[] b = new byte[bf.capacity()];
bf.get(b);
Rect r = image.getCropRect();
int w = image.getWidth();
int h = image.getHeight();
PlanarYUVLuminanceSource sauce = new PlanarYUVLuminanceSource(b ,w, h, r.left, r.top, r.width(), r.height(),false);
BinaryBitmap bit = new BinaryBitmap(new HybridBinarizer(sauce));
result = new qrReader().decoded(bit);
System.out.println(result);
Toast.makeText(getBaseContext(), result, Toast.LENGTH_SHORT).show();
Log.wtf("F: ", result);
} catch (NotFoundException e) {
e.printStackTrace();
} catch (FormatException e) {
e.printStackTrace();
}
}
}
);
//bindt de shit hierboven aan de lifecycle:
CameraX.bindToLifecycle((LifecycleOwner)this, imgAsys, /*imgCap,*/ pview);
}
/*private void updateTransform(){
//compenseert veranderingen in orientatie voor viewfinder, aangezien de rest van de layout in portrait mode blijft.
//methinks :thonk:
Matrix mx = new Matrix();
float w = txView.getMeasuredWidth();
float h = txView.getMeasuredHeight();
//berekent het midden
float cX = w / 2f;
float cY = h / 2f;
int rotDgr; //voor de switch < propt in hoeveel graden shit is gekanteld
//Display a = txView.getDisplay(); //ok dan stoppen wij .getdisplay in z'n eigen shit.
int rtrn = (int)txView.getRotation(); //dan dit maar in een aparte int zetten want alles deed boem bij het opstarten
//omfg het komt omdat .getDisplay erin zit.
switch(rtrn){
case Surface.ROTATION_0:
rotDgr = 0;
break;
case Surface.ROTATION_90:
rotDgr = 90;
break;
case Surface.ROTATION_180:
rotDgr = 180;
break;
case Surface.ROTATION_270:
rotDgr = 270;
break;
default:
return;
}
mx.postRotate((float)rotDgr, cX, cY); //berekent preview out put aan de hand van hoe de toestel gedraaid is
float buffer = txView.getMeasuredHeight() / txView.getMeasuredWidth() ;
int scaleW;
int scaleH;
if(w > h){ //center-crop transformation
scaleH = (int)w;
scaleW = Math.round(w * buffer);
} else{
scaleH = (int)h;
scaleW = Math.round(h * buffer);
}
float x = scaleW / w; //doet schaal berekenen
float y = scaleH / h;
mx.preScale(x, y, cX, cY); //vult preview op
txView.setTransform(mx); //past dit op preview toe
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//als alle permissies zijn toegestaan start camera
if(requestCode == REQUEST_CODE_PERMISSIONS){
if(allPermissionsGranted()){
startCamera();
} else{
Toast.makeText(this, "Permissions not granted by the user.", Toast.LENGTH_SHORT).show();
finish();
}
}
}
private boolean allPermissionsGranted(){
//kijken of alle permissies zijn toegestaan
for(String permission : REQUIRED_PERMISSIONS){
if(ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED){
return false;
}
}
return true;
}*/
}
|
80385_8 | package com.example.idek;
import android.graphics.Bitmap;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.zxing.WriterException;
public class qrGenFragment extends Fragment {
//waarom heeft dit ding een spellchecker. leaf me be.
//also, waarom gebruikt dit ding letterlijk >2GB ram. android studio why
//idc about those 4 warnings shhhh @ xml zooi
//WAAROM IS MIJN XML ZOOI OPEENS COMPLETELY FUCKED
private ImageView ivStats;
private EditText dingetje;
private Button butt;
//private OnFragmentInteractionListener mListener;
public qrGenFragment() {
// Required empty public constructor
}
public static qrGenFragment newInstance() {
qrGenFragment fragment = new qrGenFragment();
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.ivStats = getView().findViewById(R.id.ivStats);
this.dingetje = getView().findViewById(R.id.dingetje);
this.butt = getView().findViewById(R.id.butt); //yeey it found the butt
butt.setOnClickListener(new View.OnClickListener() { //kijken of er op het knopje is gedrukt
@Override
public void onClick(View v) {
String geweldigeTekst = dingetje.getText().toString().trim(); //maakt van de ingevoerde text een string - spaties op het begin/einde.
try {
Bitmap yeet = new qrGenerator().qrGen(geweldigeTekst); //string -> qr code
ivStats.setImageBitmap(yeet); // -> laat qr code zien als het goed gaat
} catch (WriterException e) {
Toast.makeText(getContext(), "u done goofed", Toast.LENGTH_SHORT).show(); //?? moet nog uitzoeken hoe dit precies werkt lel.
e.printStackTrace(); //gooit een exception naar je.
Log.wtf(e.getMessage(), e);
}
}
});
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_qr_gen, container, false);
}
/*@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}*/
@Override
public void onDetach() {
super.onDetach();
//mListener = null;
}
/*public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}*/
}
| 0974201/qr-ding | app/src/main/java/com/example/idek/qrGenFragment.java | 896 | //maakt van de ingevoerde text een string - spaties op het begin/einde. | line_comment | nl | package com.example.idek;
import android.graphics.Bitmap;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.zxing.WriterException;
public class qrGenFragment extends Fragment {
//waarom heeft dit ding een spellchecker. leaf me be.
//also, waarom gebruikt dit ding letterlijk >2GB ram. android studio why
//idc about those 4 warnings shhhh @ xml zooi
//WAAROM IS MIJN XML ZOOI OPEENS COMPLETELY FUCKED
private ImageView ivStats;
private EditText dingetje;
private Button butt;
//private OnFragmentInteractionListener mListener;
public qrGenFragment() {
// Required empty public constructor
}
public static qrGenFragment newInstance() {
qrGenFragment fragment = new qrGenFragment();
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.ivStats = getView().findViewById(R.id.ivStats);
this.dingetje = getView().findViewById(R.id.dingetje);
this.butt = getView().findViewById(R.id.butt); //yeey it found the butt
butt.setOnClickListener(new View.OnClickListener() { //kijken of er op het knopje is gedrukt
@Override
public void onClick(View v) {
String geweldigeTekst = dingetje.getText().toString().trim(); //maakt van<SUF>
try {
Bitmap yeet = new qrGenerator().qrGen(geweldigeTekst); //string -> qr code
ivStats.setImageBitmap(yeet); // -> laat qr code zien als het goed gaat
} catch (WriterException e) {
Toast.makeText(getContext(), "u done goofed", Toast.LENGTH_SHORT).show(); //?? moet nog uitzoeken hoe dit precies werkt lel.
e.printStackTrace(); //gooit een exception naar je.
Log.wtf(e.getMessage(), e);
}
}
});
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_qr_gen, container, false);
}
/*@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}*/
@Override
public void onDetach() {
super.onDetach();
//mListener = null;
}
/*public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}*/
}
|
87789_8 |
package mongodbtest;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.util.JSON;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
/**
*
* @author Alex
*/
// Er is geen mapreduce, lambda functies verwerken in java was te tijd rovend naar het uitvinden van hoe mongoDB werkt
public class MongoDBTest<T>{
public static void main(String[] args) throws UnknownHostException {
DB db = (new MongoClient("localhost",27017)).getDB("Hro");//database
DBCollection colEmployee = db.getCollection("Employee");//table
List<String> listName = new ArrayList<>(Arrays.asList("Peter","Jay","Mike","Sally","Michel","Bob","Jenny"));
List<String> listSurname = new ArrayList<>(Arrays.asList("Ra","Grey","Uks","Bla","Woo","Foo","Lu"));
List<String> listOccupation = new ArrayList<>(Arrays.asList("Analyst","Developer","Tester"));
List<Integer> listHours = new ArrayList<>(Arrays.asList(4,5,6,19,20,21));
// Forloop dient als een generator die gebruik maakt van een random method
/////////////////////////////////////////////////
//// Generate random database info /////
/////////////////////////////////////////////////
for(int i = 11000; i < 21000;i++){ // creëren hiermee bsn nummers van 5 cijfers
String json = "{'e_bsn': '" + Integer.toString(i) + "', 'Name':'" + getRandomItem(listName) +"','Surname':'" + getRandomItem(listSurname) +"'"
+ ",'building_name':'H-Gebouw'"
+ ",'address':[{'country': 'Nederland','Postal_code':'3201TL','City':'Spijkenisse','Street':'Wagenmaker','house_nr':25},"
+ "{'country': 'Nederland','Postal_code':'3201RR','City':'Spijkenisse','Street':'Slaanbreek','house_nr':126}],"
+ "'Position_project': [{'p_id': 'P" + Integer.toString(i%100) + "','position_project':'"+ getRandomItem(listOccupation) // modulo zorgt voor projecten P0 t/m P99
+"', 'worked_hours':"+ getRandomItem(listHours) +"}],"
+ "'degree_employee': [{'Course':'Informatica','School':'HogeSchool Rotterdam','Level':'Bachelorr'}]}";
DBObject dbObject = (DBObject)JSON.parse(json);//parser
colEmployee.insert(dbObject);// insert in database
}
BasicDBObject fields = new BasicDBObject();
fields.put("e_bsn", 1);//get only 1 field
BasicDBObject uWQuery = new BasicDBObject();
uWQuery.put("Position_project.worked_hours", new BasicDBObject("$gt", -1).append("$lt", 5));//underworking
BasicDBObject nWQuery = new BasicDBObject();
nWQuery.put("Position_project.worked_hours", new BasicDBObject("$gte", 5).append("$lte", 20));//working normal
BasicDBObject oWQuery = new BasicDBObject();
oWQuery.put("Position_project.worked_hours", new BasicDBObject("$gt", 20));//overwork
BasicDBObject pidQuery = new BasicDBObject();
pidQuery.put("Position_project.p_id", new BasicDBObject("$eq", "P20"));//work in project
BasicDBObject hourQuery = new BasicDBObject();
hourQuery.put("Position_project.worked_hours", new BasicDBObject("$eq", 20));//overwork
BasicDBObject nameQuery = new BasicDBObject();
nameQuery.put("e_bsn", new BasicDBObject("$eq", "11200"));//find e_bsn
DBCursor cursorDocJSON = colEmployee.find(nameQuery,fields); //get documents USE the QUERY and the FIELDS
while (cursorDocJSON.hasNext()) {
System.out.println(cursorDocJSON.next());
}
colEmployee.remove(new BasicDBObject());
}
static Random rand = new Random();
static <T> T getRandomItem(List<T> list) {
return list.get(rand.nextInt(list.size()));
}
} | 0NightBot0/DevDatabase | assignment 2/MongoDB/src/mongodbtest/MongoDBTest.java | 1,285 | //work in project | line_comment | nl |
package mongodbtest;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.util.JSON;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
/**
*
* @author Alex
*/
// Er is geen mapreduce, lambda functies verwerken in java was te tijd rovend naar het uitvinden van hoe mongoDB werkt
public class MongoDBTest<T>{
public static void main(String[] args) throws UnknownHostException {
DB db = (new MongoClient("localhost",27017)).getDB("Hro");//database
DBCollection colEmployee = db.getCollection("Employee");//table
List<String> listName = new ArrayList<>(Arrays.asList("Peter","Jay","Mike","Sally","Michel","Bob","Jenny"));
List<String> listSurname = new ArrayList<>(Arrays.asList("Ra","Grey","Uks","Bla","Woo","Foo","Lu"));
List<String> listOccupation = new ArrayList<>(Arrays.asList("Analyst","Developer","Tester"));
List<Integer> listHours = new ArrayList<>(Arrays.asList(4,5,6,19,20,21));
// Forloop dient als een generator die gebruik maakt van een random method
/////////////////////////////////////////////////
//// Generate random database info /////
/////////////////////////////////////////////////
for(int i = 11000; i < 21000;i++){ // creëren hiermee bsn nummers van 5 cijfers
String json = "{'e_bsn': '" + Integer.toString(i) + "', 'Name':'" + getRandomItem(listName) +"','Surname':'" + getRandomItem(listSurname) +"'"
+ ",'building_name':'H-Gebouw'"
+ ",'address':[{'country': 'Nederland','Postal_code':'3201TL','City':'Spijkenisse','Street':'Wagenmaker','house_nr':25},"
+ "{'country': 'Nederland','Postal_code':'3201RR','City':'Spijkenisse','Street':'Slaanbreek','house_nr':126}],"
+ "'Position_project': [{'p_id': 'P" + Integer.toString(i%100) + "','position_project':'"+ getRandomItem(listOccupation) // modulo zorgt voor projecten P0 t/m P99
+"', 'worked_hours':"+ getRandomItem(listHours) +"}],"
+ "'degree_employee': [{'Course':'Informatica','School':'HogeSchool Rotterdam','Level':'Bachelorr'}]}";
DBObject dbObject = (DBObject)JSON.parse(json);//parser
colEmployee.insert(dbObject);// insert in database
}
BasicDBObject fields = new BasicDBObject();
fields.put("e_bsn", 1);//get only 1 field
BasicDBObject uWQuery = new BasicDBObject();
uWQuery.put("Position_project.worked_hours", new BasicDBObject("$gt", -1).append("$lt", 5));//underworking
BasicDBObject nWQuery = new BasicDBObject();
nWQuery.put("Position_project.worked_hours", new BasicDBObject("$gte", 5).append("$lte", 20));//working normal
BasicDBObject oWQuery = new BasicDBObject();
oWQuery.put("Position_project.worked_hours", new BasicDBObject("$gt", 20));//overwork
BasicDBObject pidQuery = new BasicDBObject();
pidQuery.put("Position_project.p_id", new BasicDBObject("$eq", "P20"));//work in<SUF>
BasicDBObject hourQuery = new BasicDBObject();
hourQuery.put("Position_project.worked_hours", new BasicDBObject("$eq", 20));//overwork
BasicDBObject nameQuery = new BasicDBObject();
nameQuery.put("e_bsn", new BasicDBObject("$eq", "11200"));//find e_bsn
DBCursor cursorDocJSON = colEmployee.find(nameQuery,fields); //get documents USE the QUERY and the FIELDS
while (cursorDocJSON.hasNext()) {
System.out.println(cursorDocJSON.next());
}
colEmployee.remove(new BasicDBObject());
}
static Random rand = new Random();
static <T> T getRandomItem(List<T> list) {
return list.get(rand.nextInt(list.size()));
}
} |
158349_6 | package com.spaceproject.math;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector3;
import java.math.BigDecimal;
import java.util.Arrays;
/**
* Disclaimer: I am not a physicist. There may be errata but I will do my best.
* Sources:
* https://en.wikipedia.org/wiki/Black-body_radiation
* https://en.wikipedia.org/wiki/Planck%27s_law
* https://en.wikipedia.org/wiki/Wien%27s_displacement_law
* https://en.wikipedia.org/wiki/Rayleigh%E2%80%93Jeans_law
* https://en.wikipedia.org/wiki/Stefan%E2%80%93Boltzmann_law
* https://en.wikipedia.org/wiki/Stellar_classification
*
* https://www.fourmilab.ch/documents/specrend/
* https://en.wikipedia.org/wiki/CIE_1931_color_space#Color_matching_functions
*
* Wolfram Alpha for testing and confirming formulas and values.
* https://www.wolframalpha.com/widgets/view.jsp?id=5072e9b72faacd73c9a4e4cb36ad08d
*
* Also found a tool that simulates:
* https://phet.colorado.edu/sims/html/blackbody-spectrum/latest/blackbody-spectrum_en.html
*/
public class Physics {
// ------ Universal Constants ------
// c: Speed of light: 299,792,458 (meters per second)
public static final long speedOfLight = 299792458; //m/s
// h: Planck's constant: 6.626 × 10^-34 (Joule seconds)
public static final double planckConstant = 6.626 * Math.pow(10, -34); //Js
public static final BigDecimal planckBig = new BigDecimal("6.62607015").movePointLeft(34);
// h*c: precalculated planckConstant * speedOfLight = 1.98644586...× 10^−25 J⋅m
public static final double hc = planckConstant * speedOfLight;
public static final BigDecimal hcBig = new BigDecimal("1.98644586").movePointLeft(25);
public static final BigDecimal hcCalculated = planckBig.multiply(new BigDecimal(speedOfLight));
// k: Boltzmann constant: 1.380649 × 10^-23 J⋅K (Joules per Kelvin)
public static final double boltzmannConstant = 1.380649 * Math.pow(10, -23); //JK
public static final BigDecimal boltzmannBig = new BigDecimal("1.380649").movePointLeft(23); //JK
// b: Wien's displacement constant: 2.897771955 × 10−3 m⋅K,[1] or b ≈ 2898 μm⋅K
public static final double wiensConstant = 2.8977719; //mK
// G: Gravitational constant: 6.674×10−11 Nm^2 / kg^2 (newton square meters per kilogram squared)
public static final double gravitationalConstant = 6.674 * Math.pow(10, -11);
// ? : not sure what to call this, but it doesn't change so we can precalculate it
public static final double unnamedConstant = (2 * planckConstant * Math.pow(speedOfLight, 2));
/** Wien's displacement law: λₘT = b
* Hotter things - peak at shorter wavelengths - bluer
* Cooler things - peak at longer wavelengths - redder
* λₘ = The maximum wavelength in nanometers corresponding to peak intensity
* T = The absolute temperature in kelvin
* b = Wein’s Constant: 2.88 x 10-3 m-K or 0.288 cm-K
*/
public static double temperatureToWavelength(double kelvin) {
return wiensConstant / kelvin;
}
/** T = b / λₘ */
public static double wavelengthToTemperature(double wavelength) {
return wiensConstant / wavelength;
}
/** ν = c / λ
* ν = frequency (hertz)
* λ = wavelength (nanometers)
* c = speed of light
*/
public static double wavelengthToFrequency(double wavelength) {
return speedOfLight / wavelength;
}
/** E = (h * c) / λ
* E = energy
* λ = wavelength (nanometers)
* h = planck constant
* c = speed of light
*/
public static double wavelengthToPhotonEnergy(double wavelength) {
//energy = (planckConstant * speedOfLight) / wavelength;
return hc / wavelength;
}
/** E = hv
* E = energy
* v = frequency (hertz)
* h = planck constant
*/
public static double frequencyToPhotonEnergy(double frequency) {
//energy = planckConstant * frequency;
return planckConstant * frequency;
}
/** Rayleigh–Jeans law: uν = (8 * π * (ν^2) * k * T) / (c^2)
* Note: formula fits low frequencies but fails increasingly for higher frequencies.
* see: "ultraviolet catastrophe"
* uν =
* v = frequency (hertz)
* k = Boltzmann's constant
* T = is the absolute temperature of the radiating bod
* c = speed of light
*/
public static double RayleighJeansLaw(int wavelength) {
double frequency = wavelengthToFrequency(wavelength);
double temperature = wavelengthToTemperature(wavelength);
return (8 * Math.PI * Math.pow(frequency, 2) * boltzmannConstant * temperature) / Math.pow(speedOfLight, 2);
}
/** Planck's law of black-body radiation: L(λ) = (2 h c^2) / (λ^5 (e^((h c)/(λ k T)) - 1))
* L(λ) = spectral radiance as function of wavelength
* λ = wavelength
* T = temperature of the body Kelvin
* h = Planck constant (≈ 6.626×10^-34 J s)
* c = speed of light (≈ 2.998×10^8 m/s)
* k Boltzmann constant (≈ 1.381×10^-23 J/K)
*/
public static double calcSpectralRadiance(int wavelength, double temperature) {
//L(λ) = (2 h c^2) / (λ^5 (e^((h c)/(λ k T)) - 1))
//L = (2 * planckConstant * (speedOfLight ^ 2)) /
//((wavelength ^ 5) * (Math.E ^ ( ((planckConstant * speedOfLight) / (wavelength * boltzmannConstant * temperature)) - 1)));
//break down
//double unnamedConstant = (2.0 * planckConstant * Math.pow(speedOfLight, 2));//(2 h c^2)
//double hc = planckConstant * speedOfLight;
double a = wavelength * boltzmannConstant * temperature;
double b = Math.exp(hc / a) - 1; //(e^((h c)/(λ k T)) - 1)
return unnamedConstant / (Math.pow(wavelength, 5) * b);
}
public static void calculateBlackBody(int wavelengthStart, int wavelengthEnd, double temperature) {
//double temperature = 5772;// wavelengthToTemperature(502);
for (int wavelength = wavelengthStart; wavelength <= wavelengthEnd; wavelength++) {
//we can kinda ignore rayleigh jean as we know it will produce incorrect values, just testing
//double r = RayleighJeansLaw(wavelength);
//Gdx.app.debug("Raleigh Jean ", String.format("%s - %g", wavelength, r));
double spectralRadiance = calcSpectralRadiance(wavelength, temperature);
Gdx.app.debug("spectralRadiance", String.format("%s - %g", wavelength, spectralRadiance));
//just a test: i don't think we have a precision issue...
//BigDecimal spectralBigDecimal = calcSpectralRadianceBig(wavelength);
//Gdx.app.debug("spectral precise", wavelength + " - " + spectralBigDecimal.toPlainString());
}
//expected output: 2.19308090702e+13
// 5772k, 502nm
// Radiant emittance: 6.29403e+07 W/m2
// Radiance: 2.00345e+07 W/m2/sr
// Peak spectral radiance: 2.19308090702e+13 (W*sr-1*m-3)
// 26239737.802334465 (W/m2-sr-um)
// Spectral Radiance: 4207.38 W/m2/sr/µm (5.03412e+19 photons/J)
//
//current broken outputs:
// [Raleigh Jean ] 502 - 7.94834e-30
// [spectralRadiance] 502 - 1.01051e-29
// [spectral precise] 502 - 0.000000000000000000000000000010105
//502 - 1.17864e+13
//1.01051e-29
//7.50587e-28
//7.52394e-22
}
/** approximate RGB [0-255] values for wavelengths between 380 nm and 780 nm
* Ported from: RGB VALUES FOR VISIBLE WAVELENGTHS by Dan Bruton (astro@tamu.edu)
* http://www.physics.sfasu.edu/astro/color/spectra.html
*/
public static int[] wavelengthToRGB(double wavelength, double gamma) {
double factor;
double red, green, blue;
if ((wavelength >= 380) && (wavelength < 440)) {
red = -(wavelength - 440) / (440 - 380);
green = 0.0;
blue = 1.0;
} else if ((wavelength >= 440) && (wavelength < 490)) {
red = 0.0;
green = (wavelength - 440) / (490 - 440);
blue = 1.0;
} else if ((wavelength >= 490) && (wavelength < 510)) {
red = 0.0;
green = 1.0;
blue = -(wavelength - 510) / (510 - 490);
} else if ((wavelength >= 510) && (wavelength < 580)) {
red = (wavelength - 510) / (580 - 510);
green = 1.0;
blue = 0.0;
} else if ((wavelength >= 580) && (wavelength < 645)) {
red = 1.0;
green = -(wavelength - 645) / (645 - 580);
blue = 0.0;
} else if ((wavelength >= 645) && (wavelength < 781)) {
red = 1.0;
green = 0.0;
blue = 0.0;
} else {
red = 0.0;
green = 0.0;
blue = 0.0;
}
// Let the intensity fall off near the vision limits
if ((wavelength >= 380) && (wavelength < 420)) {
factor = 0.3 + 0.7 * (wavelength - 380) / (420 - 380);
} else if ((wavelength >= 420) && (wavelength < 701)) {
factor = 1.0;
} else if ((wavelength >= 701) && (wavelength < 781)) {
factor = 0.3 + 0.7 * (780 - wavelength) / (780 - 700);
} else {
factor = 0.0;
}
// Don't want 0^x = 1 for x <> 0
final double intensityMax = 255;
int[] rgb = new int[3];
rgb[0] = red == 0.0 ? 0 : (int)Math.round(intensityMax * Math.pow(red * factor, gamma));
rgb[1] = green == 0.0 ? 0 : (int)Math.round(intensityMax * Math.pow(green * factor, gamma));
rgb[2] = blue == 0.0 ? 0 : (int)Math.round(intensityMax * Math.pow(blue * factor, gamma));
return rgb;
}
/** approximate RGB [0-255] values for wavelengths between 380 nm and 780 nm with a default gamma of 0.8 */
public static int[] wavelengthToRGB(double wavelength) {
return wavelengthToRGB(wavelength, 0.8);
}
public static void test() {
/* Black Body Radiation!
* Common color temperatures (Kelvin):
* 1900 Candle flame
* 2000 Sunlight at sunset
* 2800 Tungsten bulb—60 watt
* 2900 Tungsten bulb—200 watt
* 3300 Tungsten/halogen lamp
* 3780 Carbon arc lamp
* 5500 Sunlight plus skylight
* 5772 Sun "effective temperature"
* 6000 Xenon strobe light
* 6500 Overcast sky
* 7500 North sky light
*
* Harvard spectral classification
* O ≥ 33,000 K blue
* B 10,000–33,000 K blue white
* A 7,500–10,000 K white
* F 6,000–7,500 K yellow white
* G 5,200–6,000 K yellow
* K 3,700–5,200 K orange
* M 2,000–3,700 K red
* R 1,300–2,000 K red
* N 1,300–2,000 K red
* S 1,300–2,000 K red
*/
//Known sun values: 5772K | 502nm | 597.2 terahertz | 2.47 eV
double kelvin = Sun.kelvin; //5772
double expectedWavelength = 502;
double expectedFrequency = 597.2;
double expectedEnergy = 2.47;
double calculatedWavelength = temperatureToWavelength(kelvin);
double calculatedTemperature = wavelengthToTemperature(expectedWavelength);
double calculatedFrequency = wavelengthToFrequency(expectedWavelength);
Gdx.app.debug("PhysicsDebug", kelvin + " K = " + MyMath.round(calculatedWavelength * 1000000, 1) + " nm");
Gdx.app.debug("PhysicsDebug", expectedWavelength + " nm = " + MyMath.round(calculatedTemperature * 1000000, 1) + " K");
Gdx.app.debug("PhysicsDebug", "temp(wave(" + kelvin + ")) = " + wavelengthToTemperature(calculatedWavelength));
Gdx.app.debug("PhysicsDebug", "wave(temp(" + expectedWavelength +")) = " + temperatureToWavelength(calculatedTemperature));
Gdx.app.debug("PhysicsDebug", expectedWavelength + " nm = " + MyMath.round(calculatedFrequency / 1000, 1) + " THz");
Gdx.app.debug("PhysicsDebug", "wavelength expected: " + MathUtils.isEqual((float)calculatedWavelength * 1000000, (float) expectedWavelength, 0.1f));
Gdx.app.debug("PhysicsDebug", "temperature expected: " + MathUtils.isEqual((float)calculatedTemperature * 1000000, (float) kelvin, 0.5f));
//Gdx.app.debug("PhysicsDebug", "frequency expected: " + MathUtils.isEqual((float)calculatedFrequency , (float) expectedFrequency, 0.1f));
//todo: photon energy calculations are returning 3.95706346613546E-28, expecting 2.47 eV
// bug: planck is coming out as -291.54400000000004. expected: 6.626 * (10 ^ -34)
// update, turns out i need to use math.pow, not ^ [^ = Bitwise exclusive OR] ....i'm a little rusty
// have we hit the Double.MIN_EXPONENT...is there a precision bug or is my math wrong?
// frequencyToPhotonEnergy: 502.0 nm = 3.9570634604560330026360810734331607818603515625E-28 eV
// wavelengthToPhotonEnergy: 502.0 nm = 3.95706346613546E-28 eV
// expected: 2.47 eV
// photonEnergy 0.000000000000000000000000198644586 precision: 47 - scale: 74
Gdx.app.debug("PhysicsDebug", "planck double: " + planckConstant);
Gdx.app.debug("PhysicsDebug", "size of double: [" + Double.MIN_VALUE + " to " + Double.MAX_VALUE
+ "] exp: [" + Double.MIN_EXPONENT + " to " + Double.MAX_EXPONENT + "]");
//high precision big decimals
Gdx.app.debug("PhysicsDebug","planck bigdecimal: " + planckBig.toString() + " -> " + planckBig.toPlainString()
+ " | precision: " + planckBig.precision() + " - scale: " + planckBig.scale());
Gdx.app.debug("PhysicsDebug","h * c def: " + hcBig.toPlainString()
+ " | precision: " + hcBig.precision() + " - scale: " + hcBig.scale());
Gdx.app.debug("PhysicsDebug","h * c calc: " + hcCalculated.toString() + " -> " + hcCalculated.toPlainString()
+ " | precision: " + hcCalculated.precision() + " - scale: " + hcCalculated.scale());
//BigDecimal photonEnergy = frequencyToPhotonEnergy(calculatedFrequency);
//Gdx.app.debug("PhysicsDebug", expectedWavelength + " nm = " + photonEnergy.toString() + " eV -> " + hcBig.toPlainString() + " | precision: " + photonEnergy.precision() + " - scale: " + photonEnergy.scale());
double photonEnergy = frequencyToPhotonEnergy(calculatedFrequency);
Gdx.app.debug("PhysicsDebug", expectedWavelength + " nm = " + photonEnergy + " eV ");
Gdx.app.debug("PhysicsDebug", expectedWavelength + " nm = " + wavelengthToPhotonEnergy(expectedWavelength) + " eV");
/* A typical human eye will respond to wavelengths from about 380 to about 750 nanometers.
* Tristimulus values: The human eye with normal vision has three kinds of cone cells that sense light, having peaks of spectral sensitivity in
* short 420 nm – 440 nm
* middle 530 nm – 540 nm
* long 560 nm – 580 nm
*
* Typical color ranges:
* Color Wavelength(nm) Frequency(THz)
* Red 620-750 484-400
* Orange 590-620 508-484
* Yellow 570-590 526-508
* Green 495-570 606-526
* Blue 450-495 668-606
* Violet 380-450 789-668
*/
double gamma = 0.8;
int red = 650;
int green = 540;
int blue = 470;
Gdx.app.debug("PhysicsDebug", expectedWavelength + " -> " + Arrays.toString(wavelengthToRGB(expectedWavelength, gamma)));
Gdx.app.debug("PhysicsDebug", red + " -> " + Arrays.toString(wavelengthToRGB(red, gamma)));//red-ish
Gdx.app.debug("PhysicsDebug", green + " -> " + Arrays.toString(wavelengthToRGB(green, gamma)));//green-ish
Gdx.app.debug("PhysicsDebug", blue + " -> " + Arrays.toString(wavelengthToRGB(blue, gamma)));//blue-ish
//wavelengthToRGB() approximates 380 nm and 780 nm
int rgbMinWavelength = 380;
int rgbMaxWavelength = 780;
double lowestVisibleTemperature = wavelengthToTemperature(rgbMinWavelength);
double highestVisibleTemperature = wavelengthToTemperature(rgbMaxWavelength);
Gdx.app.debug("PhysicsDebug", "380nm to 780nm = " + MyMath.round(lowestVisibleTemperature * 1000000, 1)
+ "K" + " to " + MyMath.round(highestVisibleTemperature * 1000000, 1) + "K");
Gdx.app.debug("PhysicsDebug", rgbMinWavelength + "nm " + MyMath.round(lowestVisibleTemperature, 1) + "K -> " + Arrays.toString(wavelengthToRGB(rgbMinWavelength, gamma)));
Gdx.app.debug("PhysicsDebug", rgbMaxWavelength + "nm " + MyMath.round(highestVisibleTemperature, 1) + "K -> " + Arrays.toString(wavelengthToRGB(rgbMaxWavelength, gamma)));
//calculateBlackBody(rgbMinWavelength, rgbMaxWavelength, kelvin);
//calculateBlackBody(380, 400);
BlackBodyColorSpectrum.test();
// 5772 K -> xyz 0.3266 0.3359 0.3376 -> rgb 1.000 0.867 0.813
Vector3 spectrum = BlackBodyColorSpectrum.spectrumToXYZ(kelvin);
Vector3 color = BlackBodyColorSpectrum.xyzToRGB(BlackBodyColorSpectrum.SMPTEsystem, spectrum.x, spectrum.y, spectrum.z);
String xyzTemp = String.format(" %5.0f K %.4f %.4f %.4f ", kelvin, spectrum.x, spectrum.y, spectrum.z);
if (BlackBodyColorSpectrum.constrainRGB(color)) {
Vector3 normal = BlackBodyColorSpectrum.normRGB(color.x, color.y, color.z);
Gdx.app.log("PhysicsDebug", xyzTemp + String.format("%.3f %.3f %.3f (Approximation)", normal.x, normal.y, normal.z));
//Gdx.app.log(this.getClass().getSimpleName(), xyzTemp + String.format("%.3f %.3f %.3f (Approximation)", color.z, color.y, color.z));
} else {
Vector3 normal = BlackBodyColorSpectrum.normRGB(color.x, color.y, color.z);
//Gdx.app.log(this.getClass().getSimpleName(), xyzTemp + String.format("%.3f %.3f %.3f", color.x, color.y, color.z));
Gdx.app.log("PhysicsDebug", xyzTemp + String.format("%.3f %.3f %.3f", normal.x, normal.y, normal.z));
}
}
public static class Sun {
public static final String spectralClass = "GV2 (main sequence)";
//mass: nominal solar mass parameter: GM⊙ = 1.3271244 × 10^20 m3 s−2 or 1.9885 × 10^30 kg.
public static final double mass = 1.9885 * Math.pow(10, 30);//kg
//radius: nominal solar radius R⊙ = 6.957 × 10^8 m
public static final double radius = 6.957 * Math.pow(10, 8);//m
//effective temperature
public static final double kelvin = 5772; //K
//5772K = 502nm = 597 THz = green light
public static final double peakWavelength = temperatureToWavelength(kelvin) * 1000000;
//luminosity: 1 sol -> L⊙ = nominal solar luminosity: L⊙ = 3.828 × 10^26 W
public static final double luminosity = 3.828 * Math.pow(10, 26); //Watts
//public static final age = 4.78 billion years
//AU Astronomical unit: roughly the distance from Earth to the Sun ~1.495978707 × 10^11 m
public static final long astronomicalUnit = 149597870700L;
}
}
| 0XDE57/SpaceProject | core/src/com/spaceproject/math/Physics.java | 6,565 | // b: Wien's displacement constant: 2.897771955 × 10−3 m⋅K,[1] or b ≈ 2898 μm⋅K | line_comment | nl | package com.spaceproject.math;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector3;
import java.math.BigDecimal;
import java.util.Arrays;
/**
* Disclaimer: I am not a physicist. There may be errata but I will do my best.
* Sources:
* https://en.wikipedia.org/wiki/Black-body_radiation
* https://en.wikipedia.org/wiki/Planck%27s_law
* https://en.wikipedia.org/wiki/Wien%27s_displacement_law
* https://en.wikipedia.org/wiki/Rayleigh%E2%80%93Jeans_law
* https://en.wikipedia.org/wiki/Stefan%E2%80%93Boltzmann_law
* https://en.wikipedia.org/wiki/Stellar_classification
*
* https://www.fourmilab.ch/documents/specrend/
* https://en.wikipedia.org/wiki/CIE_1931_color_space#Color_matching_functions
*
* Wolfram Alpha for testing and confirming formulas and values.
* https://www.wolframalpha.com/widgets/view.jsp?id=5072e9b72faacd73c9a4e4cb36ad08d
*
* Also found a tool that simulates:
* https://phet.colorado.edu/sims/html/blackbody-spectrum/latest/blackbody-spectrum_en.html
*/
public class Physics {
// ------ Universal Constants ------
// c: Speed of light: 299,792,458 (meters per second)
public static final long speedOfLight = 299792458; //m/s
// h: Planck's constant: 6.626 × 10^-34 (Joule seconds)
public static final double planckConstant = 6.626 * Math.pow(10, -34); //Js
public static final BigDecimal planckBig = new BigDecimal("6.62607015").movePointLeft(34);
// h*c: precalculated planckConstant * speedOfLight = 1.98644586...× 10^−25 J⋅m
public static final double hc = planckConstant * speedOfLight;
public static final BigDecimal hcBig = new BigDecimal("1.98644586").movePointLeft(25);
public static final BigDecimal hcCalculated = planckBig.multiply(new BigDecimal(speedOfLight));
// k: Boltzmann constant: 1.380649 × 10^-23 J⋅K (Joules per Kelvin)
public static final double boltzmannConstant = 1.380649 * Math.pow(10, -23); //JK
public static final BigDecimal boltzmannBig = new BigDecimal("1.380649").movePointLeft(23); //JK
// b: Wien's<SUF>
public static final double wiensConstant = 2.8977719; //mK
// G: Gravitational constant: 6.674×10−11 Nm^2 / kg^2 (newton square meters per kilogram squared)
public static final double gravitationalConstant = 6.674 * Math.pow(10, -11);
// ? : not sure what to call this, but it doesn't change so we can precalculate it
public static final double unnamedConstant = (2 * planckConstant * Math.pow(speedOfLight, 2));
/** Wien's displacement law: λₘT = b
* Hotter things - peak at shorter wavelengths - bluer
* Cooler things - peak at longer wavelengths - redder
* λₘ = The maximum wavelength in nanometers corresponding to peak intensity
* T = The absolute temperature in kelvin
* b = Wein’s Constant: 2.88 x 10-3 m-K or 0.288 cm-K
*/
public static double temperatureToWavelength(double kelvin) {
return wiensConstant / kelvin;
}
/** T = b / λₘ */
public static double wavelengthToTemperature(double wavelength) {
return wiensConstant / wavelength;
}
/** ν = c / λ
* ν = frequency (hertz)
* λ = wavelength (nanometers)
* c = speed of light
*/
public static double wavelengthToFrequency(double wavelength) {
return speedOfLight / wavelength;
}
/** E = (h * c) / λ
* E = energy
* λ = wavelength (nanometers)
* h = planck constant
* c = speed of light
*/
public static double wavelengthToPhotonEnergy(double wavelength) {
//energy = (planckConstant * speedOfLight) / wavelength;
return hc / wavelength;
}
/** E = hv
* E = energy
* v = frequency (hertz)
* h = planck constant
*/
public static double frequencyToPhotonEnergy(double frequency) {
//energy = planckConstant * frequency;
return planckConstant * frequency;
}
/** Rayleigh–Jeans law: uν = (8 * π * (ν^2) * k * T) / (c^2)
* Note: formula fits low frequencies but fails increasingly for higher frequencies.
* see: "ultraviolet catastrophe"
* uν =
* v = frequency (hertz)
* k = Boltzmann's constant
* T = is the absolute temperature of the radiating bod
* c = speed of light
*/
public static double RayleighJeansLaw(int wavelength) {
double frequency = wavelengthToFrequency(wavelength);
double temperature = wavelengthToTemperature(wavelength);
return (8 * Math.PI * Math.pow(frequency, 2) * boltzmannConstant * temperature) / Math.pow(speedOfLight, 2);
}
/** Planck's law of black-body radiation: L(λ) = (2 h c^2) / (λ^5 (e^((h c)/(λ k T)) - 1))
* L(λ) = spectral radiance as function of wavelength
* λ = wavelength
* T = temperature of the body Kelvin
* h = Planck constant (≈ 6.626×10^-34 J s)
* c = speed of light (≈ 2.998×10^8 m/s)
* k Boltzmann constant (≈ 1.381×10^-23 J/K)
*/
public static double calcSpectralRadiance(int wavelength, double temperature) {
//L(λ) = (2 h c^2) / (λ^5 (e^((h c)/(λ k T)) - 1))
//L = (2 * planckConstant * (speedOfLight ^ 2)) /
//((wavelength ^ 5) * (Math.E ^ ( ((planckConstant * speedOfLight) / (wavelength * boltzmannConstant * temperature)) - 1)));
//break down
//double unnamedConstant = (2.0 * planckConstant * Math.pow(speedOfLight, 2));//(2 h c^2)
//double hc = planckConstant * speedOfLight;
double a = wavelength * boltzmannConstant * temperature;
double b = Math.exp(hc / a) - 1; //(e^((h c)/(λ k T)) - 1)
return unnamedConstant / (Math.pow(wavelength, 5) * b);
}
public static void calculateBlackBody(int wavelengthStart, int wavelengthEnd, double temperature) {
//double temperature = 5772;// wavelengthToTemperature(502);
for (int wavelength = wavelengthStart; wavelength <= wavelengthEnd; wavelength++) {
//we can kinda ignore rayleigh jean as we know it will produce incorrect values, just testing
//double r = RayleighJeansLaw(wavelength);
//Gdx.app.debug("Raleigh Jean ", String.format("%s - %g", wavelength, r));
double spectralRadiance = calcSpectralRadiance(wavelength, temperature);
Gdx.app.debug("spectralRadiance", String.format("%s - %g", wavelength, spectralRadiance));
//just a test: i don't think we have a precision issue...
//BigDecimal spectralBigDecimal = calcSpectralRadianceBig(wavelength);
//Gdx.app.debug("spectral precise", wavelength + " - " + spectralBigDecimal.toPlainString());
}
//expected output: 2.19308090702e+13
// 5772k, 502nm
// Radiant emittance: 6.29403e+07 W/m2
// Radiance: 2.00345e+07 W/m2/sr
// Peak spectral radiance: 2.19308090702e+13 (W*sr-1*m-3)
// 26239737.802334465 (W/m2-sr-um)
// Spectral Radiance: 4207.38 W/m2/sr/µm (5.03412e+19 photons/J)
//
//current broken outputs:
// [Raleigh Jean ] 502 - 7.94834e-30
// [spectralRadiance] 502 - 1.01051e-29
// [spectral precise] 502 - 0.000000000000000000000000000010105
//502 - 1.17864e+13
//1.01051e-29
//7.50587e-28
//7.52394e-22
}
/** approximate RGB [0-255] values for wavelengths between 380 nm and 780 nm
* Ported from: RGB VALUES FOR VISIBLE WAVELENGTHS by Dan Bruton (astro@tamu.edu)
* http://www.physics.sfasu.edu/astro/color/spectra.html
*/
public static int[] wavelengthToRGB(double wavelength, double gamma) {
double factor;
double red, green, blue;
if ((wavelength >= 380) && (wavelength < 440)) {
red = -(wavelength - 440) / (440 - 380);
green = 0.0;
blue = 1.0;
} else if ((wavelength >= 440) && (wavelength < 490)) {
red = 0.0;
green = (wavelength - 440) / (490 - 440);
blue = 1.0;
} else if ((wavelength >= 490) && (wavelength < 510)) {
red = 0.0;
green = 1.0;
blue = -(wavelength - 510) / (510 - 490);
} else if ((wavelength >= 510) && (wavelength < 580)) {
red = (wavelength - 510) / (580 - 510);
green = 1.0;
blue = 0.0;
} else if ((wavelength >= 580) && (wavelength < 645)) {
red = 1.0;
green = -(wavelength - 645) / (645 - 580);
blue = 0.0;
} else if ((wavelength >= 645) && (wavelength < 781)) {
red = 1.0;
green = 0.0;
blue = 0.0;
} else {
red = 0.0;
green = 0.0;
blue = 0.0;
}
// Let the intensity fall off near the vision limits
if ((wavelength >= 380) && (wavelength < 420)) {
factor = 0.3 + 0.7 * (wavelength - 380) / (420 - 380);
} else if ((wavelength >= 420) && (wavelength < 701)) {
factor = 1.0;
} else if ((wavelength >= 701) && (wavelength < 781)) {
factor = 0.3 + 0.7 * (780 - wavelength) / (780 - 700);
} else {
factor = 0.0;
}
// Don't want 0^x = 1 for x <> 0
final double intensityMax = 255;
int[] rgb = new int[3];
rgb[0] = red == 0.0 ? 0 : (int)Math.round(intensityMax * Math.pow(red * factor, gamma));
rgb[1] = green == 0.0 ? 0 : (int)Math.round(intensityMax * Math.pow(green * factor, gamma));
rgb[2] = blue == 0.0 ? 0 : (int)Math.round(intensityMax * Math.pow(blue * factor, gamma));
return rgb;
}
/** approximate RGB [0-255] values for wavelengths between 380 nm and 780 nm with a default gamma of 0.8 */
public static int[] wavelengthToRGB(double wavelength) {
return wavelengthToRGB(wavelength, 0.8);
}
public static void test() {
/* Black Body Radiation!
* Common color temperatures (Kelvin):
* 1900 Candle flame
* 2000 Sunlight at sunset
* 2800 Tungsten bulb—60 watt
* 2900 Tungsten bulb—200 watt
* 3300 Tungsten/halogen lamp
* 3780 Carbon arc lamp
* 5500 Sunlight plus skylight
* 5772 Sun "effective temperature"
* 6000 Xenon strobe light
* 6500 Overcast sky
* 7500 North sky light
*
* Harvard spectral classification
* O ≥ 33,000 K blue
* B 10,000–33,000 K blue white
* A 7,500–10,000 K white
* F 6,000–7,500 K yellow white
* G 5,200–6,000 K yellow
* K 3,700–5,200 K orange
* M 2,000–3,700 K red
* R 1,300–2,000 K red
* N 1,300–2,000 K red
* S 1,300–2,000 K red
*/
//Known sun values: 5772K | 502nm | 597.2 terahertz | 2.47 eV
double kelvin = Sun.kelvin; //5772
double expectedWavelength = 502;
double expectedFrequency = 597.2;
double expectedEnergy = 2.47;
double calculatedWavelength = temperatureToWavelength(kelvin);
double calculatedTemperature = wavelengthToTemperature(expectedWavelength);
double calculatedFrequency = wavelengthToFrequency(expectedWavelength);
Gdx.app.debug("PhysicsDebug", kelvin + " K = " + MyMath.round(calculatedWavelength * 1000000, 1) + " nm");
Gdx.app.debug("PhysicsDebug", expectedWavelength + " nm = " + MyMath.round(calculatedTemperature * 1000000, 1) + " K");
Gdx.app.debug("PhysicsDebug", "temp(wave(" + kelvin + ")) = " + wavelengthToTemperature(calculatedWavelength));
Gdx.app.debug("PhysicsDebug", "wave(temp(" + expectedWavelength +")) = " + temperatureToWavelength(calculatedTemperature));
Gdx.app.debug("PhysicsDebug", expectedWavelength + " nm = " + MyMath.round(calculatedFrequency / 1000, 1) + " THz");
Gdx.app.debug("PhysicsDebug", "wavelength expected: " + MathUtils.isEqual((float)calculatedWavelength * 1000000, (float) expectedWavelength, 0.1f));
Gdx.app.debug("PhysicsDebug", "temperature expected: " + MathUtils.isEqual((float)calculatedTemperature * 1000000, (float) kelvin, 0.5f));
//Gdx.app.debug("PhysicsDebug", "frequency expected: " + MathUtils.isEqual((float)calculatedFrequency , (float) expectedFrequency, 0.1f));
//todo: photon energy calculations are returning 3.95706346613546E-28, expecting 2.47 eV
// bug: planck is coming out as -291.54400000000004. expected: 6.626 * (10 ^ -34)
// update, turns out i need to use math.pow, not ^ [^ = Bitwise exclusive OR] ....i'm a little rusty
// have we hit the Double.MIN_EXPONENT...is there a precision bug or is my math wrong?
// frequencyToPhotonEnergy: 502.0 nm = 3.9570634604560330026360810734331607818603515625E-28 eV
// wavelengthToPhotonEnergy: 502.0 nm = 3.95706346613546E-28 eV
// expected: 2.47 eV
// photonEnergy 0.000000000000000000000000198644586 precision: 47 - scale: 74
Gdx.app.debug("PhysicsDebug", "planck double: " + planckConstant);
Gdx.app.debug("PhysicsDebug", "size of double: [" + Double.MIN_VALUE + " to " + Double.MAX_VALUE
+ "] exp: [" + Double.MIN_EXPONENT + " to " + Double.MAX_EXPONENT + "]");
//high precision big decimals
Gdx.app.debug("PhysicsDebug","planck bigdecimal: " + planckBig.toString() + " -> " + planckBig.toPlainString()
+ " | precision: " + planckBig.precision() + " - scale: " + planckBig.scale());
Gdx.app.debug("PhysicsDebug","h * c def: " + hcBig.toPlainString()
+ " | precision: " + hcBig.precision() + " - scale: " + hcBig.scale());
Gdx.app.debug("PhysicsDebug","h * c calc: " + hcCalculated.toString() + " -> " + hcCalculated.toPlainString()
+ " | precision: " + hcCalculated.precision() + " - scale: " + hcCalculated.scale());
//BigDecimal photonEnergy = frequencyToPhotonEnergy(calculatedFrequency);
//Gdx.app.debug("PhysicsDebug", expectedWavelength + " nm = " + photonEnergy.toString() + " eV -> " + hcBig.toPlainString() + " | precision: " + photonEnergy.precision() + " - scale: " + photonEnergy.scale());
double photonEnergy = frequencyToPhotonEnergy(calculatedFrequency);
Gdx.app.debug("PhysicsDebug", expectedWavelength + " nm = " + photonEnergy + " eV ");
Gdx.app.debug("PhysicsDebug", expectedWavelength + " nm = " + wavelengthToPhotonEnergy(expectedWavelength) + " eV");
/* A typical human eye will respond to wavelengths from about 380 to about 750 nanometers.
* Tristimulus values: The human eye with normal vision has three kinds of cone cells that sense light, having peaks of spectral sensitivity in
* short 420 nm – 440 nm
* middle 530 nm – 540 nm
* long 560 nm – 580 nm
*
* Typical color ranges:
* Color Wavelength(nm) Frequency(THz)
* Red 620-750 484-400
* Orange 590-620 508-484
* Yellow 570-590 526-508
* Green 495-570 606-526
* Blue 450-495 668-606
* Violet 380-450 789-668
*/
double gamma = 0.8;
int red = 650;
int green = 540;
int blue = 470;
Gdx.app.debug("PhysicsDebug", expectedWavelength + " -> " + Arrays.toString(wavelengthToRGB(expectedWavelength, gamma)));
Gdx.app.debug("PhysicsDebug", red + " -> " + Arrays.toString(wavelengthToRGB(red, gamma)));//red-ish
Gdx.app.debug("PhysicsDebug", green + " -> " + Arrays.toString(wavelengthToRGB(green, gamma)));//green-ish
Gdx.app.debug("PhysicsDebug", blue + " -> " + Arrays.toString(wavelengthToRGB(blue, gamma)));//blue-ish
//wavelengthToRGB() approximates 380 nm and 780 nm
int rgbMinWavelength = 380;
int rgbMaxWavelength = 780;
double lowestVisibleTemperature = wavelengthToTemperature(rgbMinWavelength);
double highestVisibleTemperature = wavelengthToTemperature(rgbMaxWavelength);
Gdx.app.debug("PhysicsDebug", "380nm to 780nm = " + MyMath.round(lowestVisibleTemperature * 1000000, 1)
+ "K" + " to " + MyMath.round(highestVisibleTemperature * 1000000, 1) + "K");
Gdx.app.debug("PhysicsDebug", rgbMinWavelength + "nm " + MyMath.round(lowestVisibleTemperature, 1) + "K -> " + Arrays.toString(wavelengthToRGB(rgbMinWavelength, gamma)));
Gdx.app.debug("PhysicsDebug", rgbMaxWavelength + "nm " + MyMath.round(highestVisibleTemperature, 1) + "K -> " + Arrays.toString(wavelengthToRGB(rgbMaxWavelength, gamma)));
//calculateBlackBody(rgbMinWavelength, rgbMaxWavelength, kelvin);
//calculateBlackBody(380, 400);
BlackBodyColorSpectrum.test();
// 5772 K -> xyz 0.3266 0.3359 0.3376 -> rgb 1.000 0.867 0.813
Vector3 spectrum = BlackBodyColorSpectrum.spectrumToXYZ(kelvin);
Vector3 color = BlackBodyColorSpectrum.xyzToRGB(BlackBodyColorSpectrum.SMPTEsystem, spectrum.x, spectrum.y, spectrum.z);
String xyzTemp = String.format(" %5.0f K %.4f %.4f %.4f ", kelvin, spectrum.x, spectrum.y, spectrum.z);
if (BlackBodyColorSpectrum.constrainRGB(color)) {
Vector3 normal = BlackBodyColorSpectrum.normRGB(color.x, color.y, color.z);
Gdx.app.log("PhysicsDebug", xyzTemp + String.format("%.3f %.3f %.3f (Approximation)", normal.x, normal.y, normal.z));
//Gdx.app.log(this.getClass().getSimpleName(), xyzTemp + String.format("%.3f %.3f %.3f (Approximation)", color.z, color.y, color.z));
} else {
Vector3 normal = BlackBodyColorSpectrum.normRGB(color.x, color.y, color.z);
//Gdx.app.log(this.getClass().getSimpleName(), xyzTemp + String.format("%.3f %.3f %.3f", color.x, color.y, color.z));
Gdx.app.log("PhysicsDebug", xyzTemp + String.format("%.3f %.3f %.3f", normal.x, normal.y, normal.z));
}
}
public static class Sun {
public static final String spectralClass = "GV2 (main sequence)";
//mass: nominal solar mass parameter: GM⊙ = 1.3271244 × 10^20 m3 s−2 or 1.9885 × 10^30 kg.
public static final double mass = 1.9885 * Math.pow(10, 30);//kg
//radius: nominal solar radius R⊙ = 6.957 × 10^8 m
public static final double radius = 6.957 * Math.pow(10, 8);//m
//effective temperature
public static final double kelvin = 5772; //K
//5772K = 502nm = 597 THz = green light
public static final double peakWavelength = temperatureToWavelength(kelvin) * 1000000;
//luminosity: 1 sol -> L⊙ = nominal solar luminosity: L⊙ = 3.828 × 10^26 W
public static final double luminosity = 3.828 * Math.pow(10, 26); //Watts
//public static final age = 4.78 billion years
//AU Astronomical unit: roughly the distance from Earth to the Sun ~1.495978707 × 10^11 m
public static final long astronomicalUnit = 149597870700L;
}
}
|
194699_31 | /**
* Mengen nichtnegativer ganzer Zahlen in kompakter
* Speicherrepraesentation: ob eine Zahl in der Menge enthalten
* ist, wird durch EIN BIT im Speicher erfasst!
*
* <br>
* Beispiel:
* <br>
* <code>
* <br>IntSet set = new IntSet(8);
* <br>int a[] = { 1, 3, 4, 5 };
* <br>set.include( a );
* <br>
* <br> ... +---+---+---+---+---+---+---+---+
* <br> ... | 0 | 0 | 1 | 1 | 1 | 0 | 1 | 0 |
* <br> ... +---+---+---+---+---+---+---+---+
* <br></code>
*/
public class IntSet implements Iterable<Integer> {
private static final int BitsPerWord = Integer.SIZE;
// TODO: Instanzvariablen deklarieren
private int capacity;
/**
* Konstruiert ein leere Zahlenmenge der Kapazitaet <code>n</code>:
* eine Menge, die (nichtnegative ganze) Zahlen im
* Bereich 0 bis n-1 als Elemente enthalten kann.
*
* @param n die Kapazitaet der Menge
*/
public IntSet(int n) {
// TODO: Konstruktor implementieren
capacity = n;
}
/**
* Ermittelt die Kapazitaet der Menge.
*
* @return die Kapazitaet der Menge
*/
public int capacity() {
// TODO: Anzahl potenziell enthaltener Elemente zurueckgeben
return capacity;
}
/**
* Erzeugt aus <code>this</code> eine neue (identisch belegte) Zahlenmenge,
* die Werte im Bereich 0 bis n-1 als Elemente enthalten kann.
*
* Die Originalmenge bleibt unveraendert!
*
* @param n die Kapazitaet der Ergebnismenge
* @return die Ergebnismenge mit veraenderter Kapazitaet
*/
public IntSet resize(int n) {
IntSet s = new IntSet(n);
// TODO: urspruengliche Elemente uebernehmen
return s;
}
/**
* Ermittelt, ob eine nicht-negative ganze Zahl in der Menge enthalten ist.
*
* @param e eine nichtnegative ganze Zahl
* @return ist e in dieser Menge enthalten?
*/
public boolean contains(int e) {
// TODO: Bit an der richtigen Stelle isolieren und zurueckgeben
return false;
}
/**
* Nimmt die Zahl <code>e</code> in diese Menge auf.
*
* @param e eine nichtnegative ganze Zahl zwischen 0 und capacity
*/
public void insert(int e) {
// TODO: Position im IntSet berechnen und entsprechendes Bit setzen
}
/**
* Nimmt alle Elemente aus dem Array <code>es</code> in die Menge auf.
*
* @param es ein Array von nichtnegativen ganzen Zahlen
*/
public void insert(int es[]) {
// TODO: alle Elemente im Array einfuegen
}
/**
* Entfernt die Zahl <code>e</code> aus dieser Menge.
*
* @param e eine nichtnegative ganze Zahl zwischen 0 und capacity
*/
public void remove(int e) {
// TODO: Position im IntSet berechnen und entsprechendes Bit nullen
}
/**
* Entfernt alle Elemente aus dem Array <code>es</code> aus der Menge.
*
* @param es ein Array von nichtnegativen ganzen Zahlen
*/
public void remove(int[] es) {
// TODO: alle Elemente aus dem Array entfernen
}
/**
* Berechnet die Komplementaermenge zu dieser Menge: die Menge gleicher
* Kapazitaet, die genau alle Elemente enthaelt, die nicht in
* <code>this</code> enthalten sind.
*
* Originalmenge bleibt unveraendert !
*
* @return die Komplementaermenge
*/
public IntSet complement() {
// TODO: alle Elemente identifizieren, die nicht in dieser Menge enthalten sind
return null;
}
/**
* Erzeuge aus <code>s1</code> und <code>s2</code> die Vereinigungsmenge
* <br>
* es wird eine Menge der Kapazitaet der groesseren
* Kapazitaet der beiden Mengen erzeugt
* <br>
* <code>s1</code> und <code>s2</code> bleiben unveraendert !
*
* @param s1 Mengen, die
* @param s2 verknuepft werden sollen
* @return die Vereinigungsmenge
*/
public static IntSet union(IntSet s1, IntSet s2) {
// TODO: alle Elemente identifizieren, die in s1 oder s2 enthalten sind
return null;
}
/**
* Erzeuge aus <code>s1</code> und <code>s2</code> die symmetrische
* Differenzmenge.
*
* Die Eingabemengen bleiben unveraendert!
*
* @param s1 erste Menge
* @param s2 zweite Menge
* @return die symmetrische Differenzmenge
*/
public static IntSet intersection(IntSet s1, IntSet s2) {
// TODO: alle Elemente identifizieren, die in s1 und s2 enthalten sind
return null;
}
/**
* Erzeugt aus <code>s1</code> und <code>s2</code> die Differenzmenge mit
* der Kapazitaet von s1.
*
* Beide Eingabemengen bleiben unveraendert!
*
* @param s1 erste Menge
* @param s2 zweite Menge
* @return die Differenzmenge
*/
public static IntSet difference(IntSet s1, IntSet s2) {
// TODO: alle Elemente identifizieren, die in s1 aber nicht in s2 sind
return null;
}
/**
* Stringrepraesentation der Bits dieser Menge beginnend mit Index 0,
* etwa "01011100".
*
* @return Stringrepraesentation der Bits der Menge
*/
public String bits() {
String bitString = "";
// TODO: Bitstring konstruieren: 1 falls das Element enthalten ist, 0 sonst
return bitString;
}
/**
* Ermittelt die Stringrepraesentation dieser Menge, etwa "{1, 3, 4, 6}".
*
* @return Stringrepraesentation der Menge
*/
@Override
public String toString() {
String s = "{";
// TODO: Indizes aller enthaltenen Elemente kommasepariert ausgeben
return s + "}";
}
/**
* Erzeugt einen Iterator, mit dem ueber die Menge iteriert werden kann:
* <br>
* <code>
* <br>for (IntSet.Iterator it = menge.iterator(); it.hasNext(); )
* <br> { ... it.next() ... }
* </code>
*
* @return ein Iterator auf diese Menge
*/
@Override
public Iterator iterator() {
return new Iterator(this);
}
/**
* IntSet Mengen-Iterator
*/
public class Iterator implements java.util.Iterator<Integer> {
// TODO: Instanzvariablen deklarieren
/**
* Erzeugt einen Iterator ueber <code>s</code>.
*
* @param s die Menge, ueber die iteriert werden soll
*/
public Iterator(IntSet s) {
// TODO: Initialisierung der Instanzvariablen
}
/**
* Ermittelt, ob noch weitere Elemente in der Menge existieren.
*/
@Override
public boolean hasNext() {
// TODO: ermitteln, ob weitere Elemente im IntSet sind
return false;
}
/**
* Gibt das naechste Element zurueck und setzt den Iterator weiter.
*
* @return das naechste Element
*/
@Override
public Integer next() {
// TODO: naechstes (enthaltenes) Element zurueckgeben
return -1;
}
}
}
| 0dentitaet/gdp | gdp/IntSet.java | 2,233 | /**
* IntSet Mengen-Iterator
*/ | block_comment | nl | /**
* Mengen nichtnegativer ganzer Zahlen in kompakter
* Speicherrepraesentation: ob eine Zahl in der Menge enthalten
* ist, wird durch EIN BIT im Speicher erfasst!
*
* <br>
* Beispiel:
* <br>
* <code>
* <br>IntSet set = new IntSet(8);
* <br>int a[] = { 1, 3, 4, 5 };
* <br>set.include( a );
* <br>
* <br> ... +---+---+---+---+---+---+---+---+
* <br> ... | 0 | 0 | 1 | 1 | 1 | 0 | 1 | 0 |
* <br> ... +---+---+---+---+---+---+---+---+
* <br></code>
*/
public class IntSet implements Iterable<Integer> {
private static final int BitsPerWord = Integer.SIZE;
// TODO: Instanzvariablen deklarieren
private int capacity;
/**
* Konstruiert ein leere Zahlenmenge der Kapazitaet <code>n</code>:
* eine Menge, die (nichtnegative ganze) Zahlen im
* Bereich 0 bis n-1 als Elemente enthalten kann.
*
* @param n die Kapazitaet der Menge
*/
public IntSet(int n) {
// TODO: Konstruktor implementieren
capacity = n;
}
/**
* Ermittelt die Kapazitaet der Menge.
*
* @return die Kapazitaet der Menge
*/
public int capacity() {
// TODO: Anzahl potenziell enthaltener Elemente zurueckgeben
return capacity;
}
/**
* Erzeugt aus <code>this</code> eine neue (identisch belegte) Zahlenmenge,
* die Werte im Bereich 0 bis n-1 als Elemente enthalten kann.
*
* Die Originalmenge bleibt unveraendert!
*
* @param n die Kapazitaet der Ergebnismenge
* @return die Ergebnismenge mit veraenderter Kapazitaet
*/
public IntSet resize(int n) {
IntSet s = new IntSet(n);
// TODO: urspruengliche Elemente uebernehmen
return s;
}
/**
* Ermittelt, ob eine nicht-negative ganze Zahl in der Menge enthalten ist.
*
* @param e eine nichtnegative ganze Zahl
* @return ist e in dieser Menge enthalten?
*/
public boolean contains(int e) {
// TODO: Bit an der richtigen Stelle isolieren und zurueckgeben
return false;
}
/**
* Nimmt die Zahl <code>e</code> in diese Menge auf.
*
* @param e eine nichtnegative ganze Zahl zwischen 0 und capacity
*/
public void insert(int e) {
// TODO: Position im IntSet berechnen und entsprechendes Bit setzen
}
/**
* Nimmt alle Elemente aus dem Array <code>es</code> in die Menge auf.
*
* @param es ein Array von nichtnegativen ganzen Zahlen
*/
public void insert(int es[]) {
// TODO: alle Elemente im Array einfuegen
}
/**
* Entfernt die Zahl <code>e</code> aus dieser Menge.
*
* @param e eine nichtnegative ganze Zahl zwischen 0 und capacity
*/
public void remove(int e) {
// TODO: Position im IntSet berechnen und entsprechendes Bit nullen
}
/**
* Entfernt alle Elemente aus dem Array <code>es</code> aus der Menge.
*
* @param es ein Array von nichtnegativen ganzen Zahlen
*/
public void remove(int[] es) {
// TODO: alle Elemente aus dem Array entfernen
}
/**
* Berechnet die Komplementaermenge zu dieser Menge: die Menge gleicher
* Kapazitaet, die genau alle Elemente enthaelt, die nicht in
* <code>this</code> enthalten sind.
*
* Originalmenge bleibt unveraendert !
*
* @return die Komplementaermenge
*/
public IntSet complement() {
// TODO: alle Elemente identifizieren, die nicht in dieser Menge enthalten sind
return null;
}
/**
* Erzeuge aus <code>s1</code> und <code>s2</code> die Vereinigungsmenge
* <br>
* es wird eine Menge der Kapazitaet der groesseren
* Kapazitaet der beiden Mengen erzeugt
* <br>
* <code>s1</code> und <code>s2</code> bleiben unveraendert !
*
* @param s1 Mengen, die
* @param s2 verknuepft werden sollen
* @return die Vereinigungsmenge
*/
public static IntSet union(IntSet s1, IntSet s2) {
// TODO: alle Elemente identifizieren, die in s1 oder s2 enthalten sind
return null;
}
/**
* Erzeuge aus <code>s1</code> und <code>s2</code> die symmetrische
* Differenzmenge.
*
* Die Eingabemengen bleiben unveraendert!
*
* @param s1 erste Menge
* @param s2 zweite Menge
* @return die symmetrische Differenzmenge
*/
public static IntSet intersection(IntSet s1, IntSet s2) {
// TODO: alle Elemente identifizieren, die in s1 und s2 enthalten sind
return null;
}
/**
* Erzeugt aus <code>s1</code> und <code>s2</code> die Differenzmenge mit
* der Kapazitaet von s1.
*
* Beide Eingabemengen bleiben unveraendert!
*
* @param s1 erste Menge
* @param s2 zweite Menge
* @return die Differenzmenge
*/
public static IntSet difference(IntSet s1, IntSet s2) {
// TODO: alle Elemente identifizieren, die in s1 aber nicht in s2 sind
return null;
}
/**
* Stringrepraesentation der Bits dieser Menge beginnend mit Index 0,
* etwa "01011100".
*
* @return Stringrepraesentation der Bits der Menge
*/
public String bits() {
String bitString = "";
// TODO: Bitstring konstruieren: 1 falls das Element enthalten ist, 0 sonst
return bitString;
}
/**
* Ermittelt die Stringrepraesentation dieser Menge, etwa "{1, 3, 4, 6}".
*
* @return Stringrepraesentation der Menge
*/
@Override
public String toString() {
String s = "{";
// TODO: Indizes aller enthaltenen Elemente kommasepariert ausgeben
return s + "}";
}
/**
* Erzeugt einen Iterator, mit dem ueber die Menge iteriert werden kann:
* <br>
* <code>
* <br>for (IntSet.Iterator it = menge.iterator(); it.hasNext(); )
* <br> { ... it.next() ... }
* </code>
*
* @return ein Iterator auf diese Menge
*/
@Override
public Iterator iterator() {
return new Iterator(this);
}
/**
* IntSet Mengen-Iterator
<SUF>*/
public class Iterator implements java.util.Iterator<Integer> {
// TODO: Instanzvariablen deklarieren
/**
* Erzeugt einen Iterator ueber <code>s</code>.
*
* @param s die Menge, ueber die iteriert werden soll
*/
public Iterator(IntSet s) {
// TODO: Initialisierung der Instanzvariablen
}
/**
* Ermittelt, ob noch weitere Elemente in der Menge existieren.
*/
@Override
public boolean hasNext() {
// TODO: ermitteln, ob weitere Elemente im IntSet sind
return false;
}
/**
* Gibt das naechste Element zurueck und setzt den Iterator weiter.
*
* @return das naechste Element
*/
@Override
public Integer next() {
// TODO: naechstes (enthaltenes) Element zurueckgeben
return -1;
}
}
}
|
21772_5 | package gameapplication.model.chess;
import gameapplication.model.MoveManager;
import gameapplication.model.chess.piece.Piece;
import gameapplication.model.chess.piece.PieceColor;
import gameapplication.model.chess.piece.PieceSets;
import gameapplication.model.chess.piece.pieces.King;
import gameapplication.model.chess.piece.pieces.Piecetype;
import gameapplication.model.chess.spot.Spot;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
/**
* The Board class is the main class of the game. It contains all the pieces and the methods to move them
*/
public class Board {
// Creating an array of pieces.
private Piece[][] pieceIntern;
//creer 2 pieceSets voor black and white
private PieceSets[] pieceSets = new PieceSets[2];
private Player[] players;
//initiliseer laatse ronde kleur met wit;
private PieceColor lastTurnColor = PieceColor.WHITE;
//creer een moveManager
private MoveManager moveManager;
private Player currentPlayer;
private boolean checkedState;
private PieceColor checkedColor;
private boolean gameOver = false;
public Board() {
//Creer 2 pieceSets
pieceSets[0] = new PieceSets(PieceColor.WHITE);
pieceSets[1] = new PieceSets(PieceColor.BLACK);
moveManager = new MoveManager(this);
players = new Player[2];
drawBoard();
}
public void generatePlayers() {
Random random = new Random();
int generatedRandomColor = random.nextInt(2);
//Zet een random kleur
players[0].setColor(PieceColor.values()[generatedRandomColor]);
//Zet de omgekeerde van de eerste kleur
players[1].setColor(PieceColor.values()[generatedRandomColor == 0 ? 1 : 0]);
//Zet huidige speler
currentPlayer = players[0];
}
/**
* For each piece set, for each piece in the piece set, set the piece's location to the piece's location
*/
public void drawBoard() {
pieceIntern = new Piece[8][8];
//Update each spot with the latest piece -> get it's type
for (PieceSets pieceSet : pieceSets) {
for (Piece piece : pieceSet.getPieces()) {
pieceIntern[piece.getColumn()][piece.getRow()] = piece;
//Zet de piece bij de bijhorende spot
pieceIntern[piece.getColumn()][piece.getRow()].getPieceLocation().setPiece(piece);
piece.getPieceLocation().setPiece(piece);
}
}
}
/**
* Find the next player in the list of players
*/
public void switchPlayer() {
//Loop through players
for (Player pl : players) {
// Find the next player
if (pl.getColor() != lastTurnColor) {
currentPlayer = pl;
}
}
lastTurnColor = currentPlayer.getColor();
}
public void nextTurn() {
drawBoard();
}
/**
* Check if the king is in check, and if so, check if it's checkmate
*/
public void checkForCheck() {
// Get all pieces from current player
List<Piece> pieces = getPieceSets()[getArrayIndexForColor(getCurrentPlayer().getColor())].getPieces();
// Initialize the king
King king = null;
// Find the king
for (Iterator<Piece> iterator = pieces.iterator(); iterator.hasNext(); ) {
Piece next = iterator.next();
if (next.getPieceType() == Piecetype.KING) {
king = (King) next;
break;
}
}
// Check if king is in check
boolean isCheck = king.isCheck(this);
// Put the status of isCheck, in the current players pieceSet
pieceSets[getArrayIndexForColor(getCurrentPlayer().getColor())].setChecked(isCheck);
// If, it's check
if (isCheck) {
// Set the color of the player, to later be retrieved by the presenter
setCheckedColor(getCurrentPlayer().getColor());
}
// Add the state to the board
setCheckedState(isCheck);
if (isCheck) {
checkForCheckmate();
}
}
// The above code is looping through all the pieces of the current player and checking if the piece can move to any of
// the spots in the valid moves array. If the spot is null, then it is not a valid move. If the spot is not null, then
// it is a valid move. If the spot is not null and the test move returns false, then the spot will evade the check.
public void checkForCheckmate() {
// Get all pieces from current player
List<Piece> pieces = getPieceSets()[getArrayIndexForColor(getCurrentPlayer().getColor())].getPieces();
//Keep a list of available moves to make during chess
List<Spot> availableMovesDuringChess = new ArrayList<>();
//loop through the pieces
for (Iterator<Piece> iterator = pieces.iterator(); iterator.hasNext(); ) {
Piece next = iterator.next();
//get the array of the current piece valid move
Spot[][] validSpots = next.validMoves(this);
//loop through them
for (Spot[] columns : validSpots) {
for (Spot spot : columns) {
if (spot == null) continue;
//if the test move return false, then the spot will evade the check
if (!moveManager.testMove(spot, next.getPieceLocation())) {
availableMovesDuringChess.add(spot);
}
}
}
}
//if list is empty, then checkmate
if (availableMovesDuringChess.isEmpty()) {
setGameOver(true);
}
}
// This is a getter method. It is used to get the value of a variable.
public Piece getPieceFromSpot(int column, int row) {
return pieceIntern[column][row];
}
public PieceColor getLastTurnColor() {
return lastTurnColor;
}
public MoveManager getMoveManager() {
return moveManager;
}
public Player getCurrentPlayer() {
return currentPlayer;
}
//get pieces by color from board
/**
* Get all the pieces from the internal board with the same color as the given color
*
* @param color The color of the pieces you want to get.
* @return A list of pieces with the same color as the parameter.
*/
public List<Piece> getPiecesFromInternalBoard(PieceColor color) {
//Initialize a list of piece as type
List<Piece> pieces = new ArrayList<>();
//Loop through pieces
for (Piece[] pieceColumns : getPieceIntern()) {
for (Piece piece : pieceColumns) {
if (piece != null && piece.getPieceColor() == color) {
//add the piece with same color
pieces.add(piece);
}
}
}
return pieces;
}
//Get array index of piecesets array
/**
* Given a color, return the array index for that color
*
* @param color The color of the piece.
* @return The index of the array that corresponds to the color.
*/
public int getArrayIndexForColor(PieceColor color) {
return color == PieceColor.WHITE ? 0 : 1;
}
/**
* This function returns the piece array
*
* @return The pieceIntern array.
*/
public Piece[][] getPieceIntern() {
return pieceIntern;
}
/**
* It sets the checked state of the checkbox.
*
* @param checkedState A boolean value that indicates whether the checkbox is checked or not.
*/
public void setCheckedState(boolean checkedState) {
this.checkedState = checkedState;
}
/**
* Returns the checked state of the checkbox
*
* @return The checked state of the checkbox.
*/
public boolean getCheckedState() {
return checkedState;
}
/**
* Get the king of a given color
*
* @param color The color of the piece you want to get.
* @return The King object for the specified color.
*/
public King getKing(PieceColor color) {
return pieceSets[getArrayIndexForColor(color)].getKing();
}
/**
* Given the current player's color, return the opponent's color
*
* @return The color of the opponent.
*/
public PieceColor getOpponentColor() {
// This is a ternary operator. It is a shorthand way of writing an if statement.
return getCurrentPlayer().getColor() == PieceColor.WHITE ? PieceColor.BLACK : PieceColor.WHITE;
}
/**
* It sets the checked color of the checkbox.
*
* @param checkedColor The color of the piece that is currently checked.
*/
public void setCheckedColor(PieceColor checkedColor) {
this.checkedColor = checkedColor;
}
/**
* Returns the color of the piece that is currently being checked
*
* @return The color that is checked.
*/
public PieceColor getCheckedColor() {
return checkedColor;
}
/**
* Returns an array of all the players in the game
*
* @return An array of Player objects.
*/
public Player[] getPlayers() {
return players;
}
/**
* It sets the players array to the players array passed in.
*
* @param players An array of Player objects.
*/
public void setPlayers(Player[] players) {
this.players = players;
}
// Setting the value of the variable `gameOver` to the value of the parameter `gameOver`.
/**
* It sets the gameOver variable to the value passed in.
*
* @param gameOver boolean
*/
private void setGameOver(boolean gameOver) {
this.gameOver = gameOver;
}
/**
* Return true if the game is over, otherwise return false.
*
* @return A boolean value.
*/
public boolean isGameOver() {
return gameOver;
}
/**
* Add a player to the game
*
* @param name The name of the player.
* @param index The index of the player to add.
*/
public void addPlayer(String name, int index) {
players[index] = new Player(name);
}
/**
* This function returns an array of PieceSets
*
* @return An array of PieceSets.
*/
public PieceSets[] getPieceSets() {
return pieceSets;
}
}
| 0xBienCuit/ChessGame | src/gameapplication/model/chess/Board.java | 2,895 | //Creer 2 pieceSets | line_comment | nl | package gameapplication.model.chess;
import gameapplication.model.MoveManager;
import gameapplication.model.chess.piece.Piece;
import gameapplication.model.chess.piece.PieceColor;
import gameapplication.model.chess.piece.PieceSets;
import gameapplication.model.chess.piece.pieces.King;
import gameapplication.model.chess.piece.pieces.Piecetype;
import gameapplication.model.chess.spot.Spot;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
/**
* The Board class is the main class of the game. It contains all the pieces and the methods to move them
*/
public class Board {
// Creating an array of pieces.
private Piece[][] pieceIntern;
//creer 2 pieceSets voor black and white
private PieceSets[] pieceSets = new PieceSets[2];
private Player[] players;
//initiliseer laatse ronde kleur met wit;
private PieceColor lastTurnColor = PieceColor.WHITE;
//creer een moveManager
private MoveManager moveManager;
private Player currentPlayer;
private boolean checkedState;
private PieceColor checkedColor;
private boolean gameOver = false;
public Board() {
//Creer 2<SUF>
pieceSets[0] = new PieceSets(PieceColor.WHITE);
pieceSets[1] = new PieceSets(PieceColor.BLACK);
moveManager = new MoveManager(this);
players = new Player[2];
drawBoard();
}
public void generatePlayers() {
Random random = new Random();
int generatedRandomColor = random.nextInt(2);
//Zet een random kleur
players[0].setColor(PieceColor.values()[generatedRandomColor]);
//Zet de omgekeerde van de eerste kleur
players[1].setColor(PieceColor.values()[generatedRandomColor == 0 ? 1 : 0]);
//Zet huidige speler
currentPlayer = players[0];
}
/**
* For each piece set, for each piece in the piece set, set the piece's location to the piece's location
*/
public void drawBoard() {
pieceIntern = new Piece[8][8];
//Update each spot with the latest piece -> get it's type
for (PieceSets pieceSet : pieceSets) {
for (Piece piece : pieceSet.getPieces()) {
pieceIntern[piece.getColumn()][piece.getRow()] = piece;
//Zet de piece bij de bijhorende spot
pieceIntern[piece.getColumn()][piece.getRow()].getPieceLocation().setPiece(piece);
piece.getPieceLocation().setPiece(piece);
}
}
}
/**
* Find the next player in the list of players
*/
public void switchPlayer() {
//Loop through players
for (Player pl : players) {
// Find the next player
if (pl.getColor() != lastTurnColor) {
currentPlayer = pl;
}
}
lastTurnColor = currentPlayer.getColor();
}
public void nextTurn() {
drawBoard();
}
/**
* Check if the king is in check, and if so, check if it's checkmate
*/
public void checkForCheck() {
// Get all pieces from current player
List<Piece> pieces = getPieceSets()[getArrayIndexForColor(getCurrentPlayer().getColor())].getPieces();
// Initialize the king
King king = null;
// Find the king
for (Iterator<Piece> iterator = pieces.iterator(); iterator.hasNext(); ) {
Piece next = iterator.next();
if (next.getPieceType() == Piecetype.KING) {
king = (King) next;
break;
}
}
// Check if king is in check
boolean isCheck = king.isCheck(this);
// Put the status of isCheck, in the current players pieceSet
pieceSets[getArrayIndexForColor(getCurrentPlayer().getColor())].setChecked(isCheck);
// If, it's check
if (isCheck) {
// Set the color of the player, to later be retrieved by the presenter
setCheckedColor(getCurrentPlayer().getColor());
}
// Add the state to the board
setCheckedState(isCheck);
if (isCheck) {
checkForCheckmate();
}
}
// The above code is looping through all the pieces of the current player and checking if the piece can move to any of
// the spots in the valid moves array. If the spot is null, then it is not a valid move. If the spot is not null, then
// it is a valid move. If the spot is not null and the test move returns false, then the spot will evade the check.
public void checkForCheckmate() {
// Get all pieces from current player
List<Piece> pieces = getPieceSets()[getArrayIndexForColor(getCurrentPlayer().getColor())].getPieces();
//Keep a list of available moves to make during chess
List<Spot> availableMovesDuringChess = new ArrayList<>();
//loop through the pieces
for (Iterator<Piece> iterator = pieces.iterator(); iterator.hasNext(); ) {
Piece next = iterator.next();
//get the array of the current piece valid move
Spot[][] validSpots = next.validMoves(this);
//loop through them
for (Spot[] columns : validSpots) {
for (Spot spot : columns) {
if (spot == null) continue;
//if the test move return false, then the spot will evade the check
if (!moveManager.testMove(spot, next.getPieceLocation())) {
availableMovesDuringChess.add(spot);
}
}
}
}
//if list is empty, then checkmate
if (availableMovesDuringChess.isEmpty()) {
setGameOver(true);
}
}
// This is a getter method. It is used to get the value of a variable.
public Piece getPieceFromSpot(int column, int row) {
return pieceIntern[column][row];
}
public PieceColor getLastTurnColor() {
return lastTurnColor;
}
public MoveManager getMoveManager() {
return moveManager;
}
public Player getCurrentPlayer() {
return currentPlayer;
}
//get pieces by color from board
/**
* Get all the pieces from the internal board with the same color as the given color
*
* @param color The color of the pieces you want to get.
* @return A list of pieces with the same color as the parameter.
*/
public List<Piece> getPiecesFromInternalBoard(PieceColor color) {
//Initialize a list of piece as type
List<Piece> pieces = new ArrayList<>();
//Loop through pieces
for (Piece[] pieceColumns : getPieceIntern()) {
for (Piece piece : pieceColumns) {
if (piece != null && piece.getPieceColor() == color) {
//add the piece with same color
pieces.add(piece);
}
}
}
return pieces;
}
//Get array index of piecesets array
/**
* Given a color, return the array index for that color
*
* @param color The color of the piece.
* @return The index of the array that corresponds to the color.
*/
public int getArrayIndexForColor(PieceColor color) {
return color == PieceColor.WHITE ? 0 : 1;
}
/**
* This function returns the piece array
*
* @return The pieceIntern array.
*/
public Piece[][] getPieceIntern() {
return pieceIntern;
}
/**
* It sets the checked state of the checkbox.
*
* @param checkedState A boolean value that indicates whether the checkbox is checked or not.
*/
public void setCheckedState(boolean checkedState) {
this.checkedState = checkedState;
}
/**
* Returns the checked state of the checkbox
*
* @return The checked state of the checkbox.
*/
public boolean getCheckedState() {
return checkedState;
}
/**
* Get the king of a given color
*
* @param color The color of the piece you want to get.
* @return The King object for the specified color.
*/
public King getKing(PieceColor color) {
return pieceSets[getArrayIndexForColor(color)].getKing();
}
/**
* Given the current player's color, return the opponent's color
*
* @return The color of the opponent.
*/
public PieceColor getOpponentColor() {
// This is a ternary operator. It is a shorthand way of writing an if statement.
return getCurrentPlayer().getColor() == PieceColor.WHITE ? PieceColor.BLACK : PieceColor.WHITE;
}
/**
* It sets the checked color of the checkbox.
*
* @param checkedColor The color of the piece that is currently checked.
*/
public void setCheckedColor(PieceColor checkedColor) {
this.checkedColor = checkedColor;
}
/**
* Returns the color of the piece that is currently being checked
*
* @return The color that is checked.
*/
public PieceColor getCheckedColor() {
return checkedColor;
}
/**
* Returns an array of all the players in the game
*
* @return An array of Player objects.
*/
public Player[] getPlayers() {
return players;
}
/**
* It sets the players array to the players array passed in.
*
* @param players An array of Player objects.
*/
public void setPlayers(Player[] players) {
this.players = players;
}
// Setting the value of the variable `gameOver` to the value of the parameter `gameOver`.
/**
* It sets the gameOver variable to the value passed in.
*
* @param gameOver boolean
*/
private void setGameOver(boolean gameOver) {
this.gameOver = gameOver;
}
/**
* Return true if the game is over, otherwise return false.
*
* @return A boolean value.
*/
public boolean isGameOver() {
return gameOver;
}
/**
* Add a player to the game
*
* @param name The name of the player.
* @param index The index of the player to add.
*/
public void addPlayer(String name, int index) {
players[index] = new Player(name);
}
/**
* This function returns an array of PieceSets
*
* @return An array of PieceSets.
*/
public PieceSets[] getPieceSets() {
return pieceSets;
}
}
|
208429_0 |
package net.bipro.namespace.datentypen;
import javax.annotation.Generated;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for ST_Wasserfahrzeugtyp.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="ST_Wasserfahrzeugtyp">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="01"/>
* <enumeration value="02"/>
* <enumeration value="03"/>
* <enumeration value="04"/>
* <enumeration value="05"/>
* <enumeration value="06"/>
* <enumeration value="07"/>
* <enumeration value="08"/>
* <enumeration value="09"/>
* <enumeration value="10"/>
* <enumeration value="11"/>
* <enumeration value="12"/>
* <enumeration value="13"/>
* <enumeration value="14"/>
* <enumeration value="15"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "ST_Wasserfahrzeugtyp")
@XmlEnum
@Generated(value = "com.sun.tools.xjc.Driver", date = "2021-04-19T05:38:04+02:00", comments = "JAXB RI v2.3.2")
public enum STWasserfahrzeugtyp {
/**
* Motorboote und Motorsegler (Ein Motorboot ist ein von einem oder mehreren Verbrennungsmotoren oder Elektromotoren angetriebenes Wasserfahrzeug.
* Motorsegelschiffe, meistens kurz als Motorsegler oder Fifty-Fifty bezeichnet, sind Yachten, die sowohl mit Segeln als auch unter Motor zufriedenstellend angetrieben werden.)
*
*/
@XmlEnumValue("01")
MOTORBOOTE_MOTORSEGLER("01"),
/**
* Motor-Wasserfahrzeug (Ein Motor-Wasserfahrzeug ist ein von einem oder mehreren Verbrennungsmotoren oder Elektromotoren angetriebenes Wasserfahrzeug, welches z.B. als Fahrgastschiffe und Fährboote der Binnen Schifffahrt, Wattfahrt und kleinen Küstenfahrt genutzt wird.)
*
*/
@XmlEnumValue("02")
MOTOR_WASSERFAHRZEUG("02"),
/**
* Dampf- oder Motorgüterschiff (Ein Motor-Wasserfahrzeug ist ein von einem oder mehreren Verbrennungsmotoren oder Elektromotoren angetriebenes Wasserfahrzeug, welches vorrangig zum Gütertransport genutzt wird. Nicht dazu gehören Tankschiffe.)
*
*/
@XmlEnumValue("03")
DAMPF_MOTORGUETERSCHIFF("03"),
/**
* Tankschiff (Ein Tankschiff, oder kurz Tanker, ist ein Schiff zum Transport von flüssigen Stoffen, wie Wasser, Rohöl, Ölen, Kraftstoffen, Flüssiggas oder petrochemischen Erzeugnissen.)
*
*/
@XmlEnumValue("04")
TANKSCHIFF("04"),
/**
* Schlepper (Schlepper, auch Schleppschiffe genannt,sind Schiffe mit leistungsstarker Antriebsanlage, die zum Ziehen und Schieben anderer Schiffe oder großer schwimmfähiger Objekte eingesetzt werden.)
*
*/
@XmlEnumValue("05")
SCHLEPPER("05"),
/**
* Schleppkahn (Ein Schleppkahn (oder auch Schute) ist ein Schiff ohne eigenen Antrieb, mit dem Frachtgut auf Flüssen und Kanälen transportiert werden.)
*
*/
@XmlEnumValue("06")
SCHLEPPERKAHN("06"),
/**
* Schubboot (Als Schubboot, umgangssprachlich auch Schuber / Schieber, bezeichnet man ein schiebendes Schiff in der Binnenschifffahrt, welches selbst keine Ladung befördert und ein oder mehrere Schubleichter schiebt.
* Die sog. Schubleichter gehören zu der gleichen Klasse/Ausprägung wie Schubboote.)
*
*/
@XmlEnumValue("07")
SCHUBBOOT("07"),
/**
* Fischereifahrzeug für Binnenschifffahrt (Als Fischereifahrzeuge werden alle (Wasser-)Fahrzeuge bezeichnet, die auf den Fang von Wassertieren in Binnengewässern spezialisiert sind.)
*
*/
@XmlEnumValue("08")
FISCHEREIFAHRZEUG_BINNENSCHIFFFAHRT("08"),
/**
* Fischereifahrzeug für Wattfahrt oder kleine Küstenfahrt (Als Fischereifahrzeuge werden alle (Wasser-)Fahrzeuge bezeichnet, die auf den Fang von Wassertieren in Watt- oder Küstenfahrt spezialisiert sind.)
*
*/
@XmlEnumValue("09")
FISCHEREIFAHRZEUG_WATTFAHRT("09"),
/**
* Spezialschiffe mit eigenen Antrieb (Hierunter werden alle nicht klassifizierbaren Schiffe spezieller Funktion und/oder Ausführung gezählt, welche einen eigenen Antrieb besitzen.)
*
*/
@XmlEnumValue("10")
SPEZIALSCHIFFE_EIGENER_ANTRIEB("10"),
/**
* Spezialschiffe ohne eigenen Antrieb (Hierunter werden alle nicht klassifizierbaren Schiffe spezieller Funktion und/oder Ausführung gezählt, welche keinen eigenen Antrieb besitzen.)
*
*/
@XmlEnumValue("11")
SPEZIALSCHIFFE_OHNE_EIGENEN_ANTRIEB("11"),
/**
* Segelboot oder -jacht (Ein Segelboot ist ein Sportboot, das in erster Linie durch Windkraft betrieben wird. Vom Segelschiff unterscheidet es sich durch seine geringere Größe.
* Der Begriff Segelyacht (auch Segeljacht) bezeichnet ein Segelschiff, das hauptsächlich für Freizeit- oder Sportaktivitäten verwendet wird oder gelegentlich auch repräsentativen Zwecken dient.)
*
*/
@XmlEnumValue("12")
SEGELBOOT_JACHT("12"),
/**
* Jetboot (Wassermotorräder, auch bekannt als Jet-Ski oder Jet-Boot, sind relativ kleine, aus glasfaserverstärktem Kunststoff bestehende Wasserfahrzeuge ohne Bordwand. Man unterscheidet Steher für eine Person von Sitzern, Modellen mit Sitzbank, für zwei bis vier Personen. Im Wettkampfbetrieb werden diese beiden Grundmodelle als Ski und Runabout bezeichnet.)
*
*/
@XmlEnumValue("13")
JETBOOT("13"),
/**
* Ruderboot (Ruderboote sind Wasserfahrzeuge, die mit Hilfe von Riemen oder Skulls bewegt werden.
*
*/
@XmlEnumValue("14")
RUDERBOOT("14"),
/**
* Surfbrett (Ein Surfbrett ist ein aus einem schwimmfähigen Material hergestelltes Brett, das als Sportgerät zum Wellenreiten oder zum Windsurfen dient.)
*
*/
@XmlEnumValue("15")
SURFBRETT("15");
private final String value;
STWasserfahrzeugtyp(String v) {
value = v;
}
public String value() {
return value;
}
public static STWasserfahrzeugtyp fromValue(String v) {
for (STWasserfahrzeugtyp c: STWasserfahrzeugtyp.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
}
| 0xE282B0/test-bipro | norm426-jaxb-270-template/target/generated-sources/bipro/net/bipro/namespace/datentypen/STWasserfahrzeugtyp.java | 2,279 | /**
* <p>Java class for ST_Wasserfahrzeugtyp.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="ST_Wasserfahrzeugtyp">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="01"/>
* <enumeration value="02"/>
* <enumeration value="03"/>
* <enumeration value="04"/>
* <enumeration value="05"/>
* <enumeration value="06"/>
* <enumeration value="07"/>
* <enumeration value="08"/>
* <enumeration value="09"/>
* <enumeration value="10"/>
* <enumeration value="11"/>
* <enumeration value="12"/>
* <enumeration value="13"/>
* <enumeration value="14"/>
* <enumeration value="15"/>
* </restriction>
* </simpleType>
* </pre>
*
*/ | block_comment | nl |
package net.bipro.namespace.datentypen;
import javax.annotation.Generated;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for<SUF>*/
@XmlType(name = "ST_Wasserfahrzeugtyp")
@XmlEnum
@Generated(value = "com.sun.tools.xjc.Driver", date = "2021-04-19T05:38:04+02:00", comments = "JAXB RI v2.3.2")
public enum STWasserfahrzeugtyp {
/**
* Motorboote und Motorsegler (Ein Motorboot ist ein von einem oder mehreren Verbrennungsmotoren oder Elektromotoren angetriebenes Wasserfahrzeug.
* Motorsegelschiffe, meistens kurz als Motorsegler oder Fifty-Fifty bezeichnet, sind Yachten, die sowohl mit Segeln als auch unter Motor zufriedenstellend angetrieben werden.)
*
*/
@XmlEnumValue("01")
MOTORBOOTE_MOTORSEGLER("01"),
/**
* Motor-Wasserfahrzeug (Ein Motor-Wasserfahrzeug ist ein von einem oder mehreren Verbrennungsmotoren oder Elektromotoren angetriebenes Wasserfahrzeug, welches z.B. als Fahrgastschiffe und Fährboote der Binnen Schifffahrt, Wattfahrt und kleinen Küstenfahrt genutzt wird.)
*
*/
@XmlEnumValue("02")
MOTOR_WASSERFAHRZEUG("02"),
/**
* Dampf- oder Motorgüterschiff (Ein Motor-Wasserfahrzeug ist ein von einem oder mehreren Verbrennungsmotoren oder Elektromotoren angetriebenes Wasserfahrzeug, welches vorrangig zum Gütertransport genutzt wird. Nicht dazu gehören Tankschiffe.)
*
*/
@XmlEnumValue("03")
DAMPF_MOTORGUETERSCHIFF("03"),
/**
* Tankschiff (Ein Tankschiff, oder kurz Tanker, ist ein Schiff zum Transport von flüssigen Stoffen, wie Wasser, Rohöl, Ölen, Kraftstoffen, Flüssiggas oder petrochemischen Erzeugnissen.)
*
*/
@XmlEnumValue("04")
TANKSCHIFF("04"),
/**
* Schlepper (Schlepper, auch Schleppschiffe genannt,sind Schiffe mit leistungsstarker Antriebsanlage, die zum Ziehen und Schieben anderer Schiffe oder großer schwimmfähiger Objekte eingesetzt werden.)
*
*/
@XmlEnumValue("05")
SCHLEPPER("05"),
/**
* Schleppkahn (Ein Schleppkahn (oder auch Schute) ist ein Schiff ohne eigenen Antrieb, mit dem Frachtgut auf Flüssen und Kanälen transportiert werden.)
*
*/
@XmlEnumValue("06")
SCHLEPPERKAHN("06"),
/**
* Schubboot (Als Schubboot, umgangssprachlich auch Schuber / Schieber, bezeichnet man ein schiebendes Schiff in der Binnenschifffahrt, welches selbst keine Ladung befördert und ein oder mehrere Schubleichter schiebt.
* Die sog. Schubleichter gehören zu der gleichen Klasse/Ausprägung wie Schubboote.)
*
*/
@XmlEnumValue("07")
SCHUBBOOT("07"),
/**
* Fischereifahrzeug für Binnenschifffahrt (Als Fischereifahrzeuge werden alle (Wasser-)Fahrzeuge bezeichnet, die auf den Fang von Wassertieren in Binnengewässern spezialisiert sind.)
*
*/
@XmlEnumValue("08")
FISCHEREIFAHRZEUG_BINNENSCHIFFFAHRT("08"),
/**
* Fischereifahrzeug für Wattfahrt oder kleine Küstenfahrt (Als Fischereifahrzeuge werden alle (Wasser-)Fahrzeuge bezeichnet, die auf den Fang von Wassertieren in Watt- oder Küstenfahrt spezialisiert sind.)
*
*/
@XmlEnumValue("09")
FISCHEREIFAHRZEUG_WATTFAHRT("09"),
/**
* Spezialschiffe mit eigenen Antrieb (Hierunter werden alle nicht klassifizierbaren Schiffe spezieller Funktion und/oder Ausführung gezählt, welche einen eigenen Antrieb besitzen.)
*
*/
@XmlEnumValue("10")
SPEZIALSCHIFFE_EIGENER_ANTRIEB("10"),
/**
* Spezialschiffe ohne eigenen Antrieb (Hierunter werden alle nicht klassifizierbaren Schiffe spezieller Funktion und/oder Ausführung gezählt, welche keinen eigenen Antrieb besitzen.)
*
*/
@XmlEnumValue("11")
SPEZIALSCHIFFE_OHNE_EIGENEN_ANTRIEB("11"),
/**
* Segelboot oder -jacht (Ein Segelboot ist ein Sportboot, das in erster Linie durch Windkraft betrieben wird. Vom Segelschiff unterscheidet es sich durch seine geringere Größe.
* Der Begriff Segelyacht (auch Segeljacht) bezeichnet ein Segelschiff, das hauptsächlich für Freizeit- oder Sportaktivitäten verwendet wird oder gelegentlich auch repräsentativen Zwecken dient.)
*
*/
@XmlEnumValue("12")
SEGELBOOT_JACHT("12"),
/**
* Jetboot (Wassermotorräder, auch bekannt als Jet-Ski oder Jet-Boot, sind relativ kleine, aus glasfaserverstärktem Kunststoff bestehende Wasserfahrzeuge ohne Bordwand. Man unterscheidet Steher für eine Person von Sitzern, Modellen mit Sitzbank, für zwei bis vier Personen. Im Wettkampfbetrieb werden diese beiden Grundmodelle als Ski und Runabout bezeichnet.)
*
*/
@XmlEnumValue("13")
JETBOOT("13"),
/**
* Ruderboot (Ruderboote sind Wasserfahrzeuge, die mit Hilfe von Riemen oder Skulls bewegt werden.
*
*/
@XmlEnumValue("14")
RUDERBOOT("14"),
/**
* Surfbrett (Ein Surfbrett ist ein aus einem schwimmfähigen Material hergestelltes Brett, das als Sportgerät zum Wellenreiten oder zum Windsurfen dient.)
*
*/
@XmlEnumValue("15")
SURFBRETT("15");
private final String value;
STWasserfahrzeugtyp(String v) {
value = v;
}
public String value() {
return value;
}
public static STWasserfahrzeugtyp fromValue(String v) {
for (STWasserfahrzeugtyp c: STWasserfahrzeugtyp.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
}
|
183866_45 | /* -*-mode:java; c-basic-offset:2; -*- */
/*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. 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. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jsch.jzlib;
final class Tree{
static final private int MAX_BITS=15;
static final private int BL_CODES=19;
static final private int D_CODES=30;
static final private int LITERALS=256;
static final private int LENGTH_CODES=29;
static final private int L_CODES=(LITERALS+1+LENGTH_CODES);
static final private int HEAP_SIZE=(2*L_CODES+1);
// Bit length codes must not exceed MAX_BL_BITS bits
static final int MAX_BL_BITS=7;
// end of block literal code
static final int END_BLOCK=256;
// repeat previous bit length 3-6 times (2 bits of repeat count)
static final int REP_3_6=16;
// repeat a zero length 3-10 times (3 bits of repeat count)
static final int REPZ_3_10=17;
// repeat a zero length 11-138 times (7 bits of repeat count)
static final int REPZ_11_138=18;
// extra bits for each length code
static final int[] extra_lbits={
0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0
};
// extra bits for each distance code
static final int[] extra_dbits={
0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13
};
// extra bits for each bit length code
static final int[] extra_blbits={
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7
};
static final byte[] bl_order={
16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
// The lengths of the bit length codes are sent in order of decreasing
// probability, to avoid transmitting the lengths for unused bit
// length codes.
static final int Buf_size=8*2;
// see definition of array dist_code below
static final int DIST_CODE_LEN=512;
static final byte[] _dist_code = {
0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
};
static final byte[] _length_code={
0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
};
static final int[] base_length = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
64, 80, 96, 112, 128, 160, 192, 224, 0
};
static final int[] base_dist = {
0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
};
// Mapping from a distance to a distance code. dist is the distance - 1 and
// must not have side effects. _dist_code[256] and _dist_code[257] are never
// used.
static int d_code(int dist){
return ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>>7)]);
}
short[] dyn_tree; // the dynamic tree
int max_code; // largest code with non zero frequency
StaticTree stat_desc; // the corresponding static tree
// Compute the optimal bit lengths for a tree and update the total bit length
// for the current block.
// IN assertion: the fields freq and dad are set, heap[heap_max] and
// above are the tree nodes sorted by increasing frequency.
// OUT assertions: the field len is set to the optimal bit length, the
// array bl_count contains the frequencies for each bit length.
// The length opt_len is updated; static_len is also updated if stree is
// not null.
void gen_bitlen(Deflate s){
short[] tree = dyn_tree;
short[] stree = stat_desc.static_tree;
int[] extra = stat_desc.extra_bits;
int base = stat_desc.extra_base;
int max_length = stat_desc.max_length;
int h; // heap index
int n, m; // iterate over the tree elements
int bits; // bit length
int xbits; // extra bits
short f; // frequency
int overflow = 0; // number of elements with bit length too large
for (bits = 0; bits <= MAX_BITS; bits++) s.bl_count[bits] = 0;
// In a first pass, compute the optimal bit lengths (which may
// overflow in the case of the bit length tree).
tree[s.heap[s.heap_max]*2+1] = 0; // root of the heap
for(h=s.heap_max+1; h<HEAP_SIZE; h++){
n = s.heap[h];
bits = tree[tree[n*2+1]*2+1] + 1;
if (bits > max_length){ bits = max_length; overflow++; }
tree[n*2+1] = (short)bits;
// We overwrite tree[n*2+1] which is no longer needed
if (n > max_code) continue; // not a leaf node
s.bl_count[bits]++;
xbits = 0;
if (n >= base) xbits = extra[n-base];
f = tree[n*2];
s.opt_len += f * (bits + xbits);
if (stree!=null) s.static_len += f * (stree[n*2+1] + xbits);
}
if (overflow == 0) return;
// This happens for example on obj2 and pic of the Calgary corpus
// Find the first bit length which could increase:
do {
bits = max_length-1;
while(s.bl_count[bits]==0) bits--;
s.bl_count[bits]--; // move one leaf down the tree
s.bl_count[bits+1]+=2; // move one overflow item as its brother
s.bl_count[max_length]--;
// The brother of the overflow item also moves one step up,
// but this does not affect bl_count[max_length]
overflow -= 2;
}
while (overflow > 0);
for (bits = max_length; bits != 0; bits--) {
n = s.bl_count[bits];
while (n != 0) {
m = s.heap[--h];
if (m > max_code) continue;
if (tree[m*2+1] != bits) {
s.opt_len += ((long)bits - (long)tree[m*2+1])*(long)tree[m*2];
tree[m*2+1] = (short)bits;
}
n--;
}
}
}
// Construct one Huffman tree and assigns the code bit strings and lengths.
// Update the total bit length for the current block.
// IN assertion: the field freq is set for all tree elements.
// OUT assertions: the fields len and code are set to the optimal bit length
// and corresponding code. The length opt_len is updated; static_len is
// also updated if stree is not null. The field max_code is set.
void build_tree(Deflate s){
short[] tree=dyn_tree;
short[] stree=stat_desc.static_tree;
int elems=stat_desc.elems;
int n, m; // iterate over heap elements
int max_code=-1; // largest code with non zero frequency
int node; // new node being created
// Construct the initial heap, with least frequent element in
// heap[1]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
// heap[0] is not used.
s.heap_len = 0;
s.heap_max = HEAP_SIZE;
for(n=0; n<elems; n++) {
if(tree[n*2] != 0) {
s.heap[++s.heap_len] = max_code = n;
s.depth[n] = 0;
}
else{
tree[n*2+1] = 0;
}
}
// The pkzip format requires that at least one distance code exists,
// and that at least one bit should be sent even if there is only one
// possible code. So to avoid special checks later on we force at least
// two codes of non zero frequency.
while (s.heap_len < 2) {
node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
tree[node*2] = 1;
s.depth[node] = 0;
s.opt_len--; if (stree!=null) s.static_len -= stree[node*2+1];
// node is 0 or 1 so it does not have extra bits
}
this.max_code = max_code;
// The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
// establish sub-heaps of increasing lengths:
for(n=s.heap_len/2;n>=1; n--)
s.pqdownheap(tree, n);
// Construct the Huffman tree by repeatedly combining the least two
// frequent nodes.
node=elems; // next internal node of the tree
do{
// n = node of least frequency
n=s.heap[1];
s.heap[1]=s.heap[s.heap_len--];
s.pqdownheap(tree, 1);
m=s.heap[1]; // m = node of next least frequency
s.heap[--s.heap_max] = n; // keep the nodes sorted by frequency
s.heap[--s.heap_max] = m;
// Create a new node father of n and m
tree[node*2] = (short)(tree[n*2] + tree[m*2]);
s.depth[node] = (byte)(Math.max(s.depth[n],s.depth[m])+1);
tree[n*2+1] = tree[m*2+1] = (short)node;
// and insert the new node in the heap
s.heap[1] = node++;
s.pqdownheap(tree, 1);
}
while(s.heap_len>=2);
s.heap[--s.heap_max] = s.heap[1];
// At this point, the fields freq and dad are set. We can now
// generate the bit lengths.
gen_bitlen(s);
// The field len is now set, we can generate the bit codes
gen_codes(tree, max_code, s.bl_count, s.next_code);
}
// Generate the codes for a given tree and bit counts (which need not be
// optimal).
// IN assertion: the array bl_count contains the bit length statistics for
// the given tree and the field len is set for all tree elements.
// OUT assertion: the field code is set for all tree elements of non
// zero code length.
private final static void gen_codes(
short[] tree, // the tree to decorate
int max_code, // largest code with non zero frequency
short[] bl_count, // number of codes at each bit length
short[] next_code){
short code = 0; // running code value
int bits; // bit index
int n; // code index
// The distribution counts are first used to generate the code values
// without bit reversal.
next_code[0]=0;
for (bits = 1; bits <= MAX_BITS; bits++) {
next_code[bits] = code = (short)((code + bl_count[bits-1]) << 1);
}
// Check that the bit counts in bl_count are consistent. The last code
// must be all ones.
//Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
// "inconsistent bit counts");
//Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
for (n = 0; n <= max_code; n++) {
int len = tree[n*2+1];
if (len == 0) continue;
// Now reverse the bits
tree[n*2] = (short)(bi_reverse(next_code[len]++, len));
}
}
// Reverse the first len bits of a code, using straightforward code (a faster
// method would use a table)
// IN assertion: 1 <= len <= 15
private final static int bi_reverse(
int code, // the value to invert
int len // its bit length
){
int res = 0;
do{
res|=code&1;
code>>>=1;
res<<=1;
}
while(--len>0);
return res>>>1;
}
}
| 0xRustlang/keepass2android | src/java/JavaFileStorage/app/src/main/java/com/jcraft/jsch/jzlib/Tree.java | 6,522 | // iterate over heap elements | line_comment | nl | /* -*-mode:java; c-basic-offset:2; -*- */
/*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. 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. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jsch.jzlib;
final class Tree{
static final private int MAX_BITS=15;
static final private int BL_CODES=19;
static final private int D_CODES=30;
static final private int LITERALS=256;
static final private int LENGTH_CODES=29;
static final private int L_CODES=(LITERALS+1+LENGTH_CODES);
static final private int HEAP_SIZE=(2*L_CODES+1);
// Bit length codes must not exceed MAX_BL_BITS bits
static final int MAX_BL_BITS=7;
// end of block literal code
static final int END_BLOCK=256;
// repeat previous bit length 3-6 times (2 bits of repeat count)
static final int REP_3_6=16;
// repeat a zero length 3-10 times (3 bits of repeat count)
static final int REPZ_3_10=17;
// repeat a zero length 11-138 times (7 bits of repeat count)
static final int REPZ_11_138=18;
// extra bits for each length code
static final int[] extra_lbits={
0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0
};
// extra bits for each distance code
static final int[] extra_dbits={
0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13
};
// extra bits for each bit length code
static final int[] extra_blbits={
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7
};
static final byte[] bl_order={
16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
// The lengths of the bit length codes are sent in order of decreasing
// probability, to avoid transmitting the lengths for unused bit
// length codes.
static final int Buf_size=8*2;
// see definition of array dist_code below
static final int DIST_CODE_LEN=512;
static final byte[] _dist_code = {
0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
};
static final byte[] _length_code={
0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
};
static final int[] base_length = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
64, 80, 96, 112, 128, 160, 192, 224, 0
};
static final int[] base_dist = {
0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
};
// Mapping from a distance to a distance code. dist is the distance - 1 and
// must not have side effects. _dist_code[256] and _dist_code[257] are never
// used.
static int d_code(int dist){
return ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>>7)]);
}
short[] dyn_tree; // the dynamic tree
int max_code; // largest code with non zero frequency
StaticTree stat_desc; // the corresponding static tree
// Compute the optimal bit lengths for a tree and update the total bit length
// for the current block.
// IN assertion: the fields freq and dad are set, heap[heap_max] and
// above are the tree nodes sorted by increasing frequency.
// OUT assertions: the field len is set to the optimal bit length, the
// array bl_count contains the frequencies for each bit length.
// The length opt_len is updated; static_len is also updated if stree is
// not null.
void gen_bitlen(Deflate s){
short[] tree = dyn_tree;
short[] stree = stat_desc.static_tree;
int[] extra = stat_desc.extra_bits;
int base = stat_desc.extra_base;
int max_length = stat_desc.max_length;
int h; // heap index
int n, m; // iterate over the tree elements
int bits; // bit length
int xbits; // extra bits
short f; // frequency
int overflow = 0; // number of elements with bit length too large
for (bits = 0; bits <= MAX_BITS; bits++) s.bl_count[bits] = 0;
// In a first pass, compute the optimal bit lengths (which may
// overflow in the case of the bit length tree).
tree[s.heap[s.heap_max]*2+1] = 0; // root of the heap
for(h=s.heap_max+1; h<HEAP_SIZE; h++){
n = s.heap[h];
bits = tree[tree[n*2+1]*2+1] + 1;
if (bits > max_length){ bits = max_length; overflow++; }
tree[n*2+1] = (short)bits;
// We overwrite tree[n*2+1] which is no longer needed
if (n > max_code) continue; // not a leaf node
s.bl_count[bits]++;
xbits = 0;
if (n >= base) xbits = extra[n-base];
f = tree[n*2];
s.opt_len += f * (bits + xbits);
if (stree!=null) s.static_len += f * (stree[n*2+1] + xbits);
}
if (overflow == 0) return;
// This happens for example on obj2 and pic of the Calgary corpus
// Find the first bit length which could increase:
do {
bits = max_length-1;
while(s.bl_count[bits]==0) bits--;
s.bl_count[bits]--; // move one leaf down the tree
s.bl_count[bits+1]+=2; // move one overflow item as its brother
s.bl_count[max_length]--;
// The brother of the overflow item also moves one step up,
// but this does not affect bl_count[max_length]
overflow -= 2;
}
while (overflow > 0);
for (bits = max_length; bits != 0; bits--) {
n = s.bl_count[bits];
while (n != 0) {
m = s.heap[--h];
if (m > max_code) continue;
if (tree[m*2+1] != bits) {
s.opt_len += ((long)bits - (long)tree[m*2+1])*(long)tree[m*2];
tree[m*2+1] = (short)bits;
}
n--;
}
}
}
// Construct one Huffman tree and assigns the code bit strings and lengths.
// Update the total bit length for the current block.
// IN assertion: the field freq is set for all tree elements.
// OUT assertions: the fields len and code are set to the optimal bit length
// and corresponding code. The length opt_len is updated; static_len is
// also updated if stree is not null. The field max_code is set.
void build_tree(Deflate s){
short[] tree=dyn_tree;
short[] stree=stat_desc.static_tree;
int elems=stat_desc.elems;
int n, m; // iterate over<SUF>
int max_code=-1; // largest code with non zero frequency
int node; // new node being created
// Construct the initial heap, with least frequent element in
// heap[1]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
// heap[0] is not used.
s.heap_len = 0;
s.heap_max = HEAP_SIZE;
for(n=0; n<elems; n++) {
if(tree[n*2] != 0) {
s.heap[++s.heap_len] = max_code = n;
s.depth[n] = 0;
}
else{
tree[n*2+1] = 0;
}
}
// The pkzip format requires that at least one distance code exists,
// and that at least one bit should be sent even if there is only one
// possible code. So to avoid special checks later on we force at least
// two codes of non zero frequency.
while (s.heap_len < 2) {
node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
tree[node*2] = 1;
s.depth[node] = 0;
s.opt_len--; if (stree!=null) s.static_len -= stree[node*2+1];
// node is 0 or 1 so it does not have extra bits
}
this.max_code = max_code;
// The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
// establish sub-heaps of increasing lengths:
for(n=s.heap_len/2;n>=1; n--)
s.pqdownheap(tree, n);
// Construct the Huffman tree by repeatedly combining the least two
// frequent nodes.
node=elems; // next internal node of the tree
do{
// n = node of least frequency
n=s.heap[1];
s.heap[1]=s.heap[s.heap_len--];
s.pqdownheap(tree, 1);
m=s.heap[1]; // m = node of next least frequency
s.heap[--s.heap_max] = n; // keep the nodes sorted by frequency
s.heap[--s.heap_max] = m;
// Create a new node father of n and m
tree[node*2] = (short)(tree[n*2] + tree[m*2]);
s.depth[node] = (byte)(Math.max(s.depth[n],s.depth[m])+1);
tree[n*2+1] = tree[m*2+1] = (short)node;
// and insert the new node in the heap
s.heap[1] = node++;
s.pqdownheap(tree, 1);
}
while(s.heap_len>=2);
s.heap[--s.heap_max] = s.heap[1];
// At this point, the fields freq and dad are set. We can now
// generate the bit lengths.
gen_bitlen(s);
// The field len is now set, we can generate the bit codes
gen_codes(tree, max_code, s.bl_count, s.next_code);
}
// Generate the codes for a given tree and bit counts (which need not be
// optimal).
// IN assertion: the array bl_count contains the bit length statistics for
// the given tree and the field len is set for all tree elements.
// OUT assertion: the field code is set for all tree elements of non
// zero code length.
private final static void gen_codes(
short[] tree, // the tree to decorate
int max_code, // largest code with non zero frequency
short[] bl_count, // number of codes at each bit length
short[] next_code){
short code = 0; // running code value
int bits; // bit index
int n; // code index
// The distribution counts are first used to generate the code values
// without bit reversal.
next_code[0]=0;
for (bits = 1; bits <= MAX_BITS; bits++) {
next_code[bits] = code = (short)((code + bl_count[bits-1]) << 1);
}
// Check that the bit counts in bl_count are consistent. The last code
// must be all ones.
//Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
// "inconsistent bit counts");
//Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
for (n = 0; n <= max_code; n++) {
int len = tree[n*2+1];
if (len == 0) continue;
// Now reverse the bits
tree[n*2] = (short)(bi_reverse(next_code[len]++, len));
}
}
// Reverse the first len bits of a code, using straightforward code (a faster
// method would use a table)
// IN assertion: 1 <= len <= 15
private final static int bi_reverse(
int code, // the value to invert
int len // its bit length
){
int res = 0;
do{
res|=code&1;
code>>>=1;
res<<=1;
}
while(--len>0);
return res>>>1;
}
}
|
23167_12 | package XML;
import Correction.Correction;
import Correction.Corrector;
import java.awt.geom.FlatteningPathIterator;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
public class XML_Parser {
public static ArrayList<Measurement> ReadXML(String data) {
data = data.replace("<?xml version=\"1.0\"?>\n", "");
if (!data.trim().startsWith("<WEATHERDATA>")) {
return null;
}
String line;
ArrayList<Measurement> measurements = new ArrayList<Measurement>();
ArrayList<String> XMLstack = new ArrayList<String>();
SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd");
data = data.replace(">", ">\n");
data = data.replace("<", "\n<");
data = data.replace("\t", "");
while (data.contains("\n\n")) {
data = data.replace("\n\n", "\n");
}
BufferedReader reader = new BufferedReader(new StringReader(data));
try {
while ((line = reader.readLine()) != null) {
line = line.replace("\n", "");
if (line.isEmpty() || line.contains("?")) { // filter out blank lines and information tags
continue;
}
// System.out.println(line);
if (line.startsWith("<")) { // if true the given line is a tag
line = line.replace("<", "");
line = line.replace(">", "");
if (line.contains("/")) { //it is a closing tag
if (XMLstack.get(XMLstack.size() - 1).equals(line.replace("/", ""))) {
XMLstack.remove(XMLstack.size() -1);
}
else {
System.err.println("Invalid XML");
}
}
else { //it is an opening tag
XMLstack.add(line);
// System.out.println("added to XML_Stack: " + line);
if (line.equals("MEASUREMENT")) {
measurements.add(new Measurement());
}
}
}
else { // the line is not a tag
switch (XMLstack.get(XMLstack.size() -1)) {
case "STN": //Het station waarvan deze gegevens zijn
measurements.get(measurements.size() -1).STN = Integer.parseInt(line);
break;
case "DATE": //Datum van versturen van deze gegevens, formaat: yyyy-mm-dd
try {
measurements.get(measurements.size() - 1).DATETIME = ft.parse(line);
}
catch (ParseException e) {System.err.println("Unable to set DATETIME");}
break;
case "TIME": //Tijd van versturen van deze gegevens, formaat: hh:mm:ss
String s[] = line.split(":");
int time = Integer.parseInt(s[0]) * 3600000;
time += Integer.parseInt(s[1]) * 60000;
time += Integer.parseInt(s[2]) * 1000;
measurements.get(measurements.size() - 1).DATETIME.setTime(measurements.get(measurements.size() - 1).DATETIME.getTime() + time);
break;
case "TEMP": //Temperatuur in graden Celsius, geldige waardes van -9999.9 t/m 9999.9 met 1 decimaal
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).TEMP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).TEMP = Float.parseFloat(line);
}
break;
case "DEWP": // Dauwpunt in graden Celsius, geldige waardes van -9999.9 t/m 9999.9 met 1 decimaal
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).DEWP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).DEWP = Float.parseFloat(line);
}
break;
case "STP": //Luchtdruk op stationsniveau in millibar, geldige waardes van 0.0 t/m 9999.9 met 1 decimaal
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).STP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).STP = Float.parseFloat(line);
}
break;
case "SLP": //Luchtdruk op zeeniveau in millibar, geldige waardes van 0.0 t/m 9999.9 met 1 decimaal
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).SLP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).SLP = Float.parseFloat(line);
}
break;
case "VISIB": //Zichtbaarheid in kilometers, geldige waardes van 0.0 t/m 999.9 met 1 decimaal
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).VISIB = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).VISIB = Float.parseFloat(line);
}
break;
case "WDSP": //Windsnelheid in kilometers per uur, geldige waardes van 0.0 t/m 999.9 met 1 decimaal
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).TEMP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).WDSP = Float.parseFloat(line);
}
break;
case "PRCP": //Neerslag in centimeters, geldige waardes van 0.00 t/m 999.99 met 2 decimalen
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).PRCP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).PRCP = Float.parseFloat(line);
}
break;
case "SNDP": //Gevallen sneeuw in centimeters, geldige waardes van -9999.9 t/m 9999.9 met 1 decimaal
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).SNDP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).SNDP = Float.parseFloat(line);
}
break;
// Gebeurtenissen op deze dag, cummulatief, binair uitgedrukt.
// Opeenvolgend, van meest- naar minst significant:
// Vriezen, geeft aan of het gevroren heeft
// Regen, geeft aan of het geregend heeft.
// Sneeuw, geeft aan of het gesneeuwd heeft.
// Hagel, geeft aan of het gehageld heeft.
// Onweer, geeft aan of er onweer is geweest.
// Tornado/windhoos, geeft aan of er een tornado of windhoos geweest is.
case "FRSHTT":
measurements.get(measurements.size() - 1).FRSHTT = Byte.parseByte(line, 2);
break;
case "CLDC": //Bewolking in procenten, geldige waardes van 0.0 t/m 99.9 met 1 decimaal
measurements.get(measurements.size() - 1).CLDC = Float.parseFloat(line);
break;
case "WNDDIR": //Windrichting in graden, geldige waardes van 0 t/m 359 alleen gehele getallen
measurements.get(measurements.size() - 1).WNDDIR = Short.parseShort(line);
break;
}
}
}
}
catch (IOException ioe) { }
// measurements = Corrector.makeList(measurements);
// Sends all measurments trough the corrector
for (Measurement m: measurements) {
m = Correction.testAndAddMeasurement(m);
}
return measurements;
}
}
| 0xSMN/2.2-Leertaak_3 | Data_Processor/XML/XML_Parser.java | 2,525 | //Luchtdruk op zeeniveau in millibar, geldige waardes van 0.0 t/m 9999.9 met 1 decimaal | line_comment | nl | package XML;
import Correction.Correction;
import Correction.Corrector;
import java.awt.geom.FlatteningPathIterator;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
public class XML_Parser {
public static ArrayList<Measurement> ReadXML(String data) {
data = data.replace("<?xml version=\"1.0\"?>\n", "");
if (!data.trim().startsWith("<WEATHERDATA>")) {
return null;
}
String line;
ArrayList<Measurement> measurements = new ArrayList<Measurement>();
ArrayList<String> XMLstack = new ArrayList<String>();
SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd");
data = data.replace(">", ">\n");
data = data.replace("<", "\n<");
data = data.replace("\t", "");
while (data.contains("\n\n")) {
data = data.replace("\n\n", "\n");
}
BufferedReader reader = new BufferedReader(new StringReader(data));
try {
while ((line = reader.readLine()) != null) {
line = line.replace("\n", "");
if (line.isEmpty() || line.contains("?")) { // filter out blank lines and information tags
continue;
}
// System.out.println(line);
if (line.startsWith("<")) { // if true the given line is a tag
line = line.replace("<", "");
line = line.replace(">", "");
if (line.contains("/")) { //it is a closing tag
if (XMLstack.get(XMLstack.size() - 1).equals(line.replace("/", ""))) {
XMLstack.remove(XMLstack.size() -1);
}
else {
System.err.println("Invalid XML");
}
}
else { //it is an opening tag
XMLstack.add(line);
// System.out.println("added to XML_Stack: " + line);
if (line.equals("MEASUREMENT")) {
measurements.add(new Measurement());
}
}
}
else { // the line is not a tag
switch (XMLstack.get(XMLstack.size() -1)) {
case "STN": //Het station waarvan deze gegevens zijn
measurements.get(measurements.size() -1).STN = Integer.parseInt(line);
break;
case "DATE": //Datum van versturen van deze gegevens, formaat: yyyy-mm-dd
try {
measurements.get(measurements.size() - 1).DATETIME = ft.parse(line);
}
catch (ParseException e) {System.err.println("Unable to set DATETIME");}
break;
case "TIME": //Tijd van versturen van deze gegevens, formaat: hh:mm:ss
String s[] = line.split(":");
int time = Integer.parseInt(s[0]) * 3600000;
time += Integer.parseInt(s[1]) * 60000;
time += Integer.parseInt(s[2]) * 1000;
measurements.get(measurements.size() - 1).DATETIME.setTime(measurements.get(measurements.size() - 1).DATETIME.getTime() + time);
break;
case "TEMP": //Temperatuur in graden Celsius, geldige waardes van -9999.9 t/m 9999.9 met 1 decimaal
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).TEMP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).TEMP = Float.parseFloat(line);
}
break;
case "DEWP": // Dauwpunt in graden Celsius, geldige waardes van -9999.9 t/m 9999.9 met 1 decimaal
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).DEWP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).DEWP = Float.parseFloat(line);
}
break;
case "STP": //Luchtdruk op stationsniveau in millibar, geldige waardes van 0.0 t/m 9999.9 met 1 decimaal
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).STP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).STP = Float.parseFloat(line);
}
break;
case "SLP": //Luchtdruk op<SUF>
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).SLP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).SLP = Float.parseFloat(line);
}
break;
case "VISIB": //Zichtbaarheid in kilometers, geldige waardes van 0.0 t/m 999.9 met 1 decimaal
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).VISIB = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).VISIB = Float.parseFloat(line);
}
break;
case "WDSP": //Windsnelheid in kilometers per uur, geldige waardes van 0.0 t/m 999.9 met 1 decimaal
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).TEMP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).WDSP = Float.parseFloat(line);
}
break;
case "PRCP": //Neerslag in centimeters, geldige waardes van 0.00 t/m 999.99 met 2 decimalen
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).PRCP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).PRCP = Float.parseFloat(line);
}
break;
case "SNDP": //Gevallen sneeuw in centimeters, geldige waardes van -9999.9 t/m 9999.9 met 1 decimaal
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).SNDP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).SNDP = Float.parseFloat(line);
}
break;
// Gebeurtenissen op deze dag, cummulatief, binair uitgedrukt.
// Opeenvolgend, van meest- naar minst significant:
// Vriezen, geeft aan of het gevroren heeft
// Regen, geeft aan of het geregend heeft.
// Sneeuw, geeft aan of het gesneeuwd heeft.
// Hagel, geeft aan of het gehageld heeft.
// Onweer, geeft aan of er onweer is geweest.
// Tornado/windhoos, geeft aan of er een tornado of windhoos geweest is.
case "FRSHTT":
measurements.get(measurements.size() - 1).FRSHTT = Byte.parseByte(line, 2);
break;
case "CLDC": //Bewolking in procenten, geldige waardes van 0.0 t/m 99.9 met 1 decimaal
measurements.get(measurements.size() - 1).CLDC = Float.parseFloat(line);
break;
case "WNDDIR": //Windrichting in graden, geldige waardes van 0 t/m 359 alleen gehele getallen
measurements.get(measurements.size() - 1).WNDDIR = Short.parseShort(line);
break;
}
}
}
}
catch (IOException ioe) { }
// measurements = Corrector.makeList(measurements);
// Sends all measurments trough the corrector
for (Measurement m: measurements) {
m = Correction.testAndAddMeasurement(m);
}
return measurements;
}
}
|
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
- Downloads last month
- 41